Skip to main content

fallow_api/
doctor.rs

1//! Read-only project readiness inspection.
2
3use std::path::{Path, PathBuf};
4
5use fallow_engine::project_config::{
6    ProjectConfig, ProjectConfigOptions, config_for_project_readiness,
7};
8use fallow_output::{
9    DOCTOR_SCHEMA_VERSION, DoctorCheck, DoctorCheckCategory, DoctorCheckId, DoctorCheckStatus,
10    DoctorOutput, DoctorRemediation, DoctorStatus, DoctorSummary,
11};
12use fallow_types::envelope::{SchemaVersion, ToolVersion};
13
14/// Inputs for a deterministic doctor run.
15pub struct DoctorOptions<'a> {
16    /// Project root, before canonical validation.
17    pub root: &'a Path,
18    /// Optional explicit fallow config path.
19    pub config_path: Option<&'a Path>,
20}
21
22/// Inspect project-local readiness without analysis, cache writes, telemetry,
23/// network access, or third-party execution.
24#[must_use]
25pub fn run_doctor(options: &DoctorOptions<'_>) -> DoctorOutput {
26    run_doctor_with_discovery(options, &crate::type_aware::discover_companion)
27}
28
29/// Inspect readiness using an explicit cache-directory override.
30///
31/// The override takes precedence over `FALLOW_CACHE_DIR` and `cache.dir`;
32/// relative paths resolve from the validated project root. Empty paths are
33/// ignored. [`run_doctor`] already honors `FALLOW_CACHE_DIR`, so use this
34/// variant only for a directory that the host selects itself. Inspection
35/// never writes caches.
36#[must_use]
37pub fn run_doctor_with_cache_dir(
38    options: &DoctorOptions<'_>,
39    cache_dir: Option<&Path>,
40) -> DoctorOutput {
41    run_doctor_with_cache_dir_and_discovery(
42        options,
43        cache_dir,
44        &crate::type_aware::discover_companion,
45    )
46}
47
48fn run_doctor_with_discovery<F>(options: &DoctorOptions<'_>, discover_companion: &F) -> DoctorOutput
49where
50    F: Fn(&Path) -> Result<(), String>,
51{
52    run_doctor_with_cache_dir_and_discovery(options, None, discover_companion)
53}
54
55fn run_doctor_with_cache_dir_and_discovery<F>(
56    options: &DoctorOptions<'_>,
57    cache_dir: Option<&Path>,
58    discover_companion: &F,
59) -> DoctorOutput
60where
61    F: Fn(&Path) -> Result<(), String>,
62{
63    let mut checks = Vec::with_capacity(7);
64    let root = match fallow_engine::validate::validate_root(options.root) {
65        Ok(root) => {
66            checks.push(check(
67                DoctorCheckId::Root,
68                DoctorCheckCategory::Project,
69                DoctorCheckStatus::Pass,
70                true,
71                "Project root is an accessible directory.",
72                None,
73            ));
74            root
75        }
76        Err(_) => {
77            checks.push(check(
78                DoctorCheckId::Root,
79                DoctorCheckCategory::Project,
80                DoctorCheckStatus::Fail,
81                true,
82                "Project root is not accessible. Set --root to an existing, readable directory.",
83                None,
84            ));
85            push_prerequisite_skips(&mut checks, "Project root readiness failed.");
86            return build_output(checks);
87        }
88    };
89
90    let project = config_for_project_readiness(
91        &root,
92        options.config_path,
93        ProjectConfigOptions {
94            output: fallow_config::OutputFormat::Json,
95            no_cache: true,
96            threads: 1,
97            production_override: None,
98            quiet: true,
99            analysis: fallow_config::ProductionAnalysis::DeadCode,
100            allow_remote_extends: false,
101        },
102    );
103
104    match project {
105        Ok(mut readiness) => {
106            if let Some(path) = cache_dir.filter(|path| !path.as_os_str().is_empty()) {
107                readiness
108                    .project
109                    .config
110                    .override_cache_dir(path.to_path_buf());
111            }
112            push_ready_project_checks(
113                &mut checks,
114                &root,
115                &readiness.project,
116                &readiness.configured_plugin_diagnostics,
117                discover_companion,
118            );
119        }
120        Err(error) => {
121            push_project_failure_checks(&mut checks, error.message(), &root, options.config_path);
122        }
123    }
124
125    build_output(checks)
126}
127
128fn push_ready_project_checks<F>(
129    checks: &mut Vec<DoctorCheck>,
130    root: &Path,
131    project: &ProjectConfig,
132    configured_plugin_diagnostics: &[fallow_config::ConfiguredPluginDiagnostic],
133    discover_companion: &F,
134) where
135    F: Fn(&Path) -> Result<(), String>,
136{
137    let config_message = project.path.as_ref().map_or_else(
138        || "Zero-config defaults resolved successfully.".to_string(),
139        |path| match safe_config_argument(root, path) {
140            Some(path) => format!("Configuration resolved from {path}."),
141            None => "The explicitly selected configuration resolved successfully.".to_string(),
142        },
143    );
144    checks.push(check(
145        DoctorCheckId::Config,
146        DoctorCheckCategory::Configuration,
147        DoctorCheckStatus::Pass,
148        true,
149        config_message,
150        None,
151    ));
152
153    let workspace_status = if project.workspace_diagnostics.is_empty() {
154        DoctorCheckStatus::Pass
155    } else {
156        DoctorCheckStatus::Warn
157    };
158    let workspace_count = project.workspaces.len();
159    let workspace_noun = if workspace_count == 1 {
160        "workspace package"
161    } else {
162        "workspace packages"
163    };
164    let mut workspace_message = if project.workspace_diagnostics.is_empty() {
165        format!("Workspace discovery completed ({workspace_count} {workspace_noun}).")
166    } else {
167        let diagnostic_count = project.workspace_diagnostics.len();
168        let diagnostic_noun = if diagnostic_count == 1 {
169            "diagnostic"
170        } else {
171            "diagnostics"
172        };
173        format!(
174            "Workspace discovery completed with {diagnostic_count} {diagnostic_noun}; {workspace_count} {workspace_noun} retained."
175        )
176    };
177    if workspace_status == DoctorCheckStatus::Warn {
178        append_external_config_note(&mut workspace_message, root, project.path.as_deref());
179    }
180    checks.push(check(
181        DoctorCheckId::Workspaces,
182        DoctorCheckCategory::Workspace,
183        workspace_status,
184        false,
185        workspace_message,
186        (workspace_status == DoctorCheckStatus::Warn)
187            .then(|| {
188                remediation_with_config(
189                    "fallow workspaces --format json --quiet",
190                    root,
191                    project.path.as_deref(),
192                )
193            })
194            .flatten(),
195    ));
196
197    checks.push(plugin_check(root, project, configured_plugin_diagnostics));
198
199    checks.push(type_aware_check(
200        root,
201        &project.config.type_aware,
202        discover_companion,
203    ));
204
205    checks.push(dependencies_check(root));
206    checks.push(cache_check(&project.config));
207    checks.push(graph_cache_check(&project.config));
208}
209
210/// Report whether the project has an installed dependency tree.
211///
212/// Advisory, never required: analysis runs without `node_modules`, it just
213/// runs blind to package `exports`, to plugins that activate on an installed
214/// package, and to a dependency's installed shape. Doctor used to report
215/// `pass` on a tree that had never been installed, which is the one state this
216/// command exists to catch.
217fn dependencies_check(root: &Path) -> DoctorCheck {
218    if !fallow_config::node_modules_missing(root) {
219        return check(
220            DoctorCheckId::Dependencies,
221            DoctorCheckCategory::Project,
222            DoctorCheckStatus::Pass,
223            false,
224            "Dependencies are installed, or the project runs without a node_modules directory.",
225            None,
226        );
227    }
228    check(
229        DoctorCheckId::Dependencies,
230        DoctorCheckCategory::Project,
231        DoctorCheckStatus::Warn,
232        false,
233        "No node_modules directory. Package exports, plugin activation, and dependency \
234         classification degrade until dependencies are installed.",
235        Some(remediation(
236            &project_package_manager(root).install_command(),
237            true,
238        )),
239    )
240}
241
242/// Report whether a persisted extraction cache would be reused.
243///
244/// Advisory, never required, and never a `fail`: a refused cache costs time,
245/// not correctness. A missing cache passes, because a first run legitimately
246/// has none; a cache that exists and would be discarded warns, because the
247/// project is paying for a blob it never gets back.
248fn cache_check(config: &fallow_config::ResolvedConfig) -> DoctorCheck {
249    let status = fallow_engine::cache_status::inspect_parse_cache(config);
250    let size = status
251        .size_bytes
252        .map_or_else(String::new, |bytes| format!(" ({})", format_size_mb(bytes)));
253    match status.rejection {
254        None => check(
255            DoctorCheckId::Cache,
256            DoctorCheckCategory::Cache,
257            DoctorCheckStatus::Pass,
258            false,
259            format!("Extraction cache is reusable{size}."),
260            None,
261        ),
262        Some(fallow_types::cache_rejection::CacheRejection::Absent) => check(
263            DoctorCheckId::Cache,
264            DoctorCheckCategory::Cache,
265            DoctorCheckStatus::Pass,
266            false,
267            "No extraction cache yet; the next run writes one.",
268            None,
269        ),
270        Some(rejection) => check(
271            DoctorCheckId::Cache,
272            DoctorCheckCategory::Cache,
273            DoctorCheckStatus::Warn,
274            false,
275            format!(
276                "Extraction cache{size} would not be reused: {}. The next run parses every file.",
277                rejection.describe()
278            ),
279            Some(remediation("fallow dead-code --quiet", false)),
280        ),
281    }
282}
283
284/// Report whether the persisted module graph would load.
285///
286/// Advisory for the same reason as the extraction-cache check, and reported
287/// separately because the two blobs are reused independently: a project whose
288/// extraction cache is perfectly healthy can still rebuild the whole graph on
289/// every run, and the graph is the larger file of the two.
290///
291/// This answers whether the blob LOADS, not whether a run would reuse it. The
292/// reuse decision also compares resolver options, entry points, and per-file
293/// content hashes, and computing those means running discovery and extraction,
294/// which doctor deliberately does not do.
295fn graph_cache_check(config: &fallow_config::ResolvedConfig) -> DoctorCheck {
296    let status = fallow_engine::cache_status::inspect_graph_cache(config);
297    let size = status
298        .size_bytes
299        .map_or_else(String::new, |bytes| format!(" ({})", format_size_mb(bytes)));
300    match status.rejection {
301        None => check(
302            DoctorCheckId::GraphCache,
303            DoctorCheckCategory::Cache,
304            DoctorCheckStatus::Pass,
305            false,
306            format!(
307                "Module-graph cache{size} loads; a run reuses it when the analysed files and \
308                 options are unchanged."
309            ),
310            None,
311        ),
312        Some(fallow_types::cache_rejection::CacheRejection::Absent) => check(
313            DoctorCheckId::GraphCache,
314            DoctorCheckCategory::Cache,
315            DoctorCheckStatus::Pass,
316            false,
317            "No module-graph cache yet; the next run writes one.",
318            None,
319        ),
320        Some(rejection) => check(
321            DoctorCheckId::GraphCache,
322            DoctorCheckCategory::Cache,
323            DoctorCheckStatus::Warn,
324            false,
325            format!(
326                "Module-graph cache{size} would not be reused: {}. The next run resolves imports \
327                 and rebuilds the graph.",
328                rejection.describe()
329            ),
330            Some(remediation("fallow dead-code --quiet", false)),
331        ),
332    }
333}
334
335/// Render a byte count at a unit that shows it.
336///
337/// A fixed megabyte figure reported every small blob as `0.0 MB`, which reads
338/// as "empty" next to a message about a cache that exists and was refused: a
339/// corrupt 4 KB file and a truncated 40-byte one printed the same size.
340fn format_size_mb(bytes: u64) -> String {
341    #[expect(
342        clippy::cast_precision_loss,
343        reason = "display-only size figure; precision loss past 2^53 bytes is irrelevant"
344    )]
345    let scaled = bytes as f64;
346    if bytes >= 1024 * 1024 {
347        format!("{:.1} MB", scaled / (1024.0 * 1024.0))
348    } else if bytes >= 1024 {
349        format!("{:.1} KB", scaled / 1024.0)
350    } else {
351        format!("{bytes} bytes")
352    }
353}
354
355fn plugin_check(
356    root: &Path,
357    project: &ProjectConfig,
358    configured_plugin_diagnostics: &[fallow_config::ConfiguredPluginDiagnostic],
359) -> DoctorCheck {
360    if !configured_plugin_diagnostics.is_empty() {
361        let diagnostic_count = configured_plugin_diagnostics.len();
362        let resource_noun = if diagnostic_count == 1 {
363            "resource"
364        } else {
365            "resources"
366        };
367        let mut message = format!(
368            "External plugin configuration contains {diagnostic_count} unresolved configured {resource_noun}."
369        );
370        append_external_config_note(&mut message, root, project.path.as_deref());
371        return check(
372            DoctorCheckId::Plugins,
373            DoctorCheckCategory::Plugin,
374            DoctorCheckStatus::Fail,
375            true,
376            message,
377            remediation_with_config(
378                "fallow plugin-check --format json --quiet",
379                root,
380                project.path.as_deref(),
381            ),
382        );
383    }
384
385    let configured = &project.config.external_plugins;
386    if configured.is_empty() {
387        return check(
388            DoctorCheckId::Plugins,
389            DoctorCheckCategory::Plugin,
390            DoctorCheckStatus::Pass,
391            true,
392            "No external plugins are configured; built-in detection remains available.",
393            None,
394        );
395    }
396
397    let active = configured
398        .iter()
399        .filter(|plugin| external_plugin_is_active(plugin, root, &project.workspaces))
400        .count();
401    let configured_count = configured.len();
402    let status = if active == configured_count {
403        DoctorCheckStatus::Pass
404    } else {
405        DoctorCheckStatus::Warn
406    };
407    let mut message = format!(
408        "External plugin activation evaluated ({active} active of {configured_count} configured)."
409    );
410    if status == DoctorCheckStatus::Warn {
411        append_external_config_note(&mut message, root, project.path.as_deref());
412    }
413    check(
414        DoctorCheckId::Plugins,
415        DoctorCheckCategory::Plugin,
416        status,
417        false,
418        message,
419        (status == DoctorCheckStatus::Warn)
420            .then(|| {
421                remediation_with_config(
422                    "fallow plugin-check --format json --quiet",
423                    root,
424                    project.path.as_deref(),
425                )
426            })
427            .flatten(),
428    )
429}
430
431fn external_plugin_is_active(
432    plugin: &fallow_config::ExternalPluginDef,
433    root: &Path,
434    workspaces: &[fallow_config::WorkspaceInfo],
435) -> bool {
436    std::iter::once(root)
437        .chain(workspaces.iter().map(|workspace| workspace.root.as_path()))
438        .any(|package_root| {
439            let Some(package) = fallow_config::load_dir_package_json(package_root) else {
440                return false;
441            };
442            fallow_engine::plugins::is_external_plugin_active(
443                plugin,
444                &package.all_dependency_names(),
445                package_root,
446                &[],
447            )
448        })
449}
450
451fn push_project_failure_checks(
452    checks: &mut Vec<DoctorCheck>,
453    error: &str,
454    root: &Path,
455    config_path: Option<&Path>,
456) {
457    if error.starts_with("invalid external plugin definition") {
458        checks.push(check(
459            DoctorCheckId::Config,
460            DoctorCheckCategory::Configuration,
461            DoctorCheckStatus::Pass,
462            true,
463            "Configuration parsed, but external plugin validation failed.",
464            None,
465        ));
466        checks.push(skipped(
467            DoctorCheckId::Workspaces,
468            DoctorCheckCategory::Workspace,
469            "Plugin validation failed before workspace discovery.",
470        ));
471        let mut message = "External plugin configuration is invalid.".to_string();
472        append_external_config_note(&mut message, root, config_path);
473        checks.push(check(
474            DoctorCheckId::Plugins,
475            DoctorCheckCategory::Plugin,
476            DoctorCheckStatus::Fail,
477            true,
478            message,
479            remediation_with_config(
480                "fallow plugin-check --format json --quiet",
481                root,
482                config_path,
483            ),
484        ));
485    } else if error.starts_with("root package.json") || error.starts_with("root Deno config") {
486        checks.push(check(
487            DoctorCheckId::Config,
488            DoctorCheckCategory::Configuration,
489            DoctorCheckStatus::Pass,
490            true,
491            "Fallow configuration resolved successfully.",
492            None,
493        ));
494        let mut message = "Root workspace manifest discovery failed.".to_string();
495        append_external_config_note(&mut message, root, config_path);
496        checks.push(check(
497            DoctorCheckId::Workspaces,
498            DoctorCheckCategory::Workspace,
499            DoctorCheckStatus::Fail,
500            true,
501            message,
502            remediation_with_config("fallow workspaces --format json --quiet", root, config_path),
503        ));
504        checks.push(skipped(
505            DoctorCheckId::Plugins,
506            DoctorCheckCategory::Plugin,
507            "Workspace discovery failed before readiness collection completed.",
508        ));
509    } else {
510        let mut message = "Fallow configuration could not be resolved.".to_string();
511        append_external_config_note(&mut message, root, config_path);
512        checks.push(check(
513            DoctorCheckId::Config,
514            DoctorCheckCategory::Configuration,
515            DoctorCheckStatus::Fail,
516            true,
517            message,
518            remediation_with_config("fallow config", root, config_path),
519        ));
520        checks.push(skipped(
521            DoctorCheckId::Workspaces,
522            DoctorCheckCategory::Workspace,
523            "Configuration readiness failed.",
524        ));
525        checks.push(skipped(
526            DoctorCheckId::Plugins,
527            DoctorCheckCategory::Plugin,
528            "Configuration readiness failed.",
529        ));
530    }
531    checks.push(skipped(
532        DoctorCheckId::TypeAware,
533        DoctorCheckCategory::Companion,
534        "Configuration readiness did not establish whether type-aware analysis is enabled.",
535    ));
536    checks.push(dependencies_check(root));
537    checks.push(skipped(
538        DoctorCheckId::Cache,
539        DoctorCheckCategory::Cache,
540        "Configuration readiness did not establish which cache this project uses.",
541    ));
542    checks.push(skipped(
543        DoctorCheckId::GraphCache,
544        DoctorCheckCategory::Cache,
545        "Configuration readiness did not establish which cache this project uses.",
546    ));
547}
548
549fn type_aware_check<F>(
550    root: &Path,
551    config: &fallow_config::TypeAwareConfig,
552    discover_companion: &F,
553) -> DoctorCheck
554where
555    F: Fn(&Path) -> Result<(), String>,
556{
557    let (enabled, require) = match effective_type_aware_config(config) {
558        Ok(effective) => effective,
559        Err(message) => {
560            return check(
561                DoctorCheckId::TypeAware,
562                DoctorCheckCategory::Companion,
563                DoctorCheckStatus::Fail,
564                true,
565                message,
566                None,
567            );
568        }
569    };
570    if !enabled {
571        return skipped(
572            DoctorCheckId::TypeAware,
573            DoctorCheckCategory::Companion,
574            "Type-aware analysis is not enabled.",
575        );
576    }
577
578    match discover_companion(root) {
579        Ok(()) => check(
580            DoctorCheckId::TypeAware,
581            DoctorCheckCategory::Companion,
582            DoctorCheckStatus::Pass,
583            require == fallow_config::TypeAwareRequire::Complete,
584            "A trusted type-aware companion is discoverable without starting it.",
585            None,
586        ),
587        Err(_) => {
588            let required = require == fallow_config::TypeAwareRequire::Complete;
589            check(
590                DoctorCheckId::TypeAware,
591                DoctorCheckCategory::Companion,
592                if required {
593                    DoctorCheckStatus::Fail
594                } else {
595                    DoctorCheckStatus::Warn
596                },
597                required,
598                "Type-aware analysis is enabled, but no trusted companion is discoverable.",
599                Some(remediation(
600                    &project_package_manager(root).add_dev_command(&format!(
601                        "fallow-type-aware@{}",
602                        env!("CARGO_PKG_VERSION")
603                    )),
604                    true,
605                )),
606            )
607        }
608    }
609}
610
611fn effective_type_aware_config(
612    config: &fallow_config::TypeAwareConfig,
613) -> Result<(bool, fallow_config::TypeAwareRequire), &'static str> {
614    let enabled = match std::env::var("FALLOW_TYPE_AWARE") {
615        Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
616            "1" | "true" | "yes" | "on" => true,
617            "0" | "false" | "no" | "off" => false,
618            _ => return Err("FALLOW_TYPE_AWARE must contain a supported boolean value."),
619        },
620        Err(std::env::VarError::NotPresent) => config.enabled,
621        Err(std::env::VarError::NotUnicode(_)) => {
622            return Err("FALLOW_TYPE_AWARE must contain valid UTF-8.");
623        }
624    };
625    let require = match std::env::var("FALLOW_TYPE_AWARE_REQUIRE") {
626        Ok(value) => match value.trim().to_ascii_lowercase().as_str() {
627            "best-effort" => fallow_config::TypeAwareRequire::BestEffort,
628            "complete" => fallow_config::TypeAwareRequire::Complete,
629            _ => return Err("FALLOW_TYPE_AWARE_REQUIRE must be best-effort or complete."),
630        },
631        Err(std::env::VarError::NotPresent) => config.require,
632        Err(std::env::VarError::NotUnicode(_)) => {
633            return Err("FALLOW_TYPE_AWARE_REQUIRE must contain valid UTF-8.");
634        }
635    };
636    Ok((enabled, require))
637}
638
639/// The package manager that a suggested install command names. npm is the
640/// default when the project declares none and has no lockfile.
641fn project_package_manager(root: &Path) -> fallow_config::PackageManager {
642    fallow_config::PackageManager::detect_nearest(root)
643        .unwrap_or(fallow_config::PackageManager::Npm)
644}
645
646fn remediation(command: &str, mutating: bool) -> DoctorRemediation {
647    DoctorRemediation {
648        command: command.to_string(),
649        cwd: ".".to_string(),
650        mutating,
651    }
652}
653
654fn remediation_with_config(
655    command: &str,
656    root: &Path,
657    config_path: Option<&Path>,
658) -> Option<DoctorRemediation> {
659    let command = match config_path {
660        None => command.to_string(),
661        Some(path) => format!("{command} --config={}", safe_config_argument(root, path)?),
662    };
663    Some(remediation(&command, false))
664}
665
666fn safe_config_argument(root: &Path, config_path: &Path) -> Option<String> {
667    let canonical_root = dunce::canonicalize(root).ok()?;
668    let canonical = canonicalize_with_missing_suffix(config_path)?;
669    let relative = relative_path(&canonical_root, &canonical)?;
670    relative
671        .bytes()
672        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b'/'))
673        .then_some(relative)
674}
675
676fn canonicalize_with_missing_suffix(path: &Path) -> Option<PathBuf> {
677    let mut ancestor = path;
678    let mut suffix = Vec::new();
679
680    loop {
681        match dunce::canonicalize(ancestor) {
682            Ok(mut canonical) => {
683                if !suffix.is_empty() && !canonical.is_dir() {
684                    return None;
685                }
686                for component in suffix.into_iter().rev() {
687                    canonical.push(component);
688                }
689                return Some(canonical);
690            }
691            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
692                match std::fs::symlink_metadata(ancestor) {
693                    Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
694                    _ => return None,
695                }
696                let std::path::Component::Normal(component) = ancestor.components().next_back()?
697                else {
698                    return None;
699                };
700                suffix.push(component.to_os_string());
701                ancestor = ancestor.parent()?;
702            }
703            Err(_) => return None,
704        }
705    }
706}
707
708fn append_external_config_note(message: &mut String, root: &Path, config_path: Option<&Path>) {
709    if config_path.is_some_and(|path| safe_config_argument(root, path).is_none()) {
710        message.push_str(" Repeat this diagnostic with the same explicit --config value.");
711    }
712}
713
714fn push_prerequisite_skips(checks: &mut Vec<DoctorCheck>, message: &str) {
715    for (id, category) in [
716        (DoctorCheckId::Config, DoctorCheckCategory::Configuration),
717        (DoctorCheckId::Workspaces, DoctorCheckCategory::Workspace),
718        (DoctorCheckId::Plugins, DoctorCheckCategory::Plugin),
719        (DoctorCheckId::TypeAware, DoctorCheckCategory::Companion),
720        (DoctorCheckId::Dependencies, DoctorCheckCategory::Project),
721        (DoctorCheckId::Cache, DoctorCheckCategory::Cache),
722        (DoctorCheckId::GraphCache, DoctorCheckCategory::Cache),
723    ] {
724        checks.push(skipped(id, category, message));
725    }
726}
727
728fn skipped(id: DoctorCheckId, category: DoctorCheckCategory, message: &str) -> DoctorCheck {
729    check(
730        id,
731        category,
732        DoctorCheckStatus::Skipped,
733        false,
734        message,
735        None,
736    )
737}
738
739fn check(
740    id: DoctorCheckId,
741    category: DoctorCheckCategory,
742    status: DoctorCheckStatus,
743    required: bool,
744    message: impl Into<String>,
745    remediation: Option<DoctorRemediation>,
746) -> DoctorCheck {
747    DoctorCheck {
748        id,
749        category,
750        status,
751        required,
752        message: message.into(),
753        remediation,
754    }
755}
756
757fn build_output(checks: Vec<DoctorCheck>) -> DoctorOutput {
758    let summary = checks
759        .iter()
760        .fold(DoctorSummary::default(), |mut summary, check| {
761            match check.status {
762                DoctorCheckStatus::Pass => summary.pass += 1,
763                DoctorCheckStatus::Warn => summary.warn += 1,
764                DoctorCheckStatus::Fail => summary.fail += 1,
765                DoctorCheckStatus::Skipped => summary.skipped += 1,
766            }
767            summary
768        });
769    let status = if checks
770        .iter()
771        .any(|check| check.required && check.status == DoctorCheckStatus::Fail)
772    {
773        DoctorStatus::Fail
774    } else if summary.warn > 0 {
775        DoctorStatus::Warn
776    } else {
777        DoctorStatus::Pass
778    };
779    DoctorOutput {
780        schema_version: SchemaVersion(DOCTOR_SCHEMA_VERSION),
781        version: ToolVersion(env!("CARGO_PKG_VERSION").to_string()),
782        root: ".".to_string(),
783        status,
784        summary,
785        checks,
786    }
787}
788
789fn relative_path(root: &Path, path: &Path) -> Option<String> {
790    path.strip_prefix(root).ok().map(|path| {
791        let relative = path.to_string_lossy().replace('\\', "/");
792        if relative.is_empty() {
793            ".".to_string()
794        } else {
795            relative
796        }
797    })
798}
799
800#[cfg(test)]
801mod tests {
802    use super::*;
803
804    #[test]
805    fn zero_config_is_ready_with_stable_order() {
806        let root = tempfile::tempdir().expect("temp root");
807        let output = run_doctor_with_discovery(
808            &DoctorOptions {
809                root: root.path(),
810                config_path: None,
811            },
812            &|_| Err("missing companion".to_string()),
813        );
814
815        assert_eq!(output.status, DoctorStatus::Warn);
816        assert_eq!(output.root, ".");
817        assert_eq!(
818            output
819                .checks
820                .iter()
821                .map(|check| check.id)
822                .collect::<Vec<_>>(),
823            vec![
824                DoctorCheckId::Root,
825                DoctorCheckId::Config,
826                DoctorCheckId::Workspaces,
827                DoctorCheckId::Plugins,
828                DoctorCheckId::TypeAware,
829                DoctorCheckId::Dependencies,
830                DoctorCheckId::Cache,
831                DoctorCheckId::GraphCache,
832            ]
833        );
834        assert_eq!(
835            output.checks[1].message,
836            "Zero-config defaults resolved successfully."
837        );
838        assert_eq!(output.checks[4].status, DoctorCheckStatus::Skipped);
839    }
840
841    /// Issue: doctor reported `pass` on a tree that had never been installed,
842    /// while the command exists to diagnose exactly that.
843    #[test]
844    fn missing_node_modules_warns_without_failing() {
845        let root = tempfile::tempdir().expect("temp root");
846
847        let output = run_doctor_with_discovery(
848            &DoctorOptions {
849                root: root.path(),
850                config_path: None,
851            },
852            &|_| Err("missing companion".to_string()),
853        );
854
855        let dependencies = output
856            .checks
857            .iter()
858            .find(|check| check.id == DoctorCheckId::Dependencies)
859            .expect("dependencies check is reported");
860        assert_eq!(dependencies.status, DoctorCheckStatus::Warn);
861        assert!(!dependencies.required);
862        assert_eq!(output.status, DoctorStatus::Warn);
863        assert!(
864            dependencies
865                .remediation
866                .as_ref()
867                .is_some_and(|remediation| remediation.mutating),
868            "installing dependencies mutates the project"
869        );
870    }
871
872    fn dependency_remediation_command(root: &Path) -> String {
873        run_doctor_with_discovery(
874            &DoctorOptions {
875                root,
876                config_path: None,
877            },
878            &|_| Err("missing companion".to_string()),
879        )
880        .checks
881        .into_iter()
882        .find(|check| check.id == DoctorCheckId::Dependencies)
883        .and_then(|check| check.remediation)
884        .map(|remediation| remediation.command)
885        .expect("dependencies remediation is reported")
886    }
887
888    /// Issue: doctor told pnpm, Yarn and Bun projects to run `npm install`,
889    /// which writes a foreign lockfile.
890    #[test]
891    fn dependency_remediation_uses_the_project_package_manager() {
892        for (lockfile, expected) in [
893            ("pnpm-lock.yaml", "pnpm install"),
894            ("yarn.lock", "yarn install"),
895            ("bun.lock", "bun install"),
896            ("package-lock.json", "npm install"),
897        ] {
898            let root = tempfile::tempdir().expect("temp root");
899            std::fs::write(root.path().join(lockfile), "").expect("write lockfile");
900            assert_eq!(
901                dependency_remediation_command(root.path()),
902                expected,
903                "{lockfile}"
904            );
905        }
906    }
907
908    #[test]
909    fn dependency_remediation_prefers_the_package_manager_field() {
910        let root = tempfile::tempdir().expect("temp root");
911        std::fs::write(
912            root.path().join("package.json"),
913            r#"{"packageManager":"yarn@4.5.0"}"#,
914        )
915        .expect("write package.json");
916        std::fs::write(root.path().join("package-lock.json"), "").expect("write lockfile");
917        assert_eq!(dependency_remediation_command(root.path()), "yarn install");
918    }
919
920    #[test]
921    fn dependency_remediation_defaults_to_npm_without_a_signal() {
922        let root = tempfile::tempdir().expect("temp root");
923        assert_eq!(dependency_remediation_command(root.path()), "npm install");
924    }
925
926    /// Review finding: a workspace package root fell back to `npm install`
927    /// although the monorepo root declares pnpm.
928    #[test]
929    fn dependency_remediation_finds_the_monorepo_package_manager() {
930        let root = tempfile::tempdir().expect("temp root");
931        let package = root.path().join("packages").join("app");
932        std::fs::create_dir_all(&package).expect("create package");
933        std::fs::create_dir(root.path().join(".git")).expect("create .git");
934        std::fs::write(
935            root.path().join("package.json"),
936            r#"{"private":true,"packageManager":"pnpm@10.0.0"}"#,
937        )
938        .expect("write root package.json");
939        std::fs::write(package.join("package.json"), r#"{"name":"app"}"#)
940            .expect("write package.json");
941        assert_eq!(dependency_remediation_command(&package), "pnpm install");
942    }
943
944    #[test]
945    fn type_aware_remediation_uses_the_project_package_manager() {
946        let root = tempfile::tempdir().expect("temp root");
947        std::fs::write(
948            root.path().join(".fallowrc.json"),
949            r#"{"typeAware":{"enabled":true}}"#,
950        )
951        .expect("write config");
952        std::fs::write(root.path().join("pnpm-lock.yaml"), "").expect("write lockfile");
953
954        let output = run_doctor_with_discovery(
955            &DoctorOptions {
956                root: root.path(),
957                config_path: None,
958            },
959            &|_| Err("missing companion".to_string()),
960        );
961
962        assert_eq!(
963            output.checks[4]
964                .remediation
965                .as_ref()
966                .map(|remediation| remediation.command.as_str()),
967            Some(
968                format!(
969                    "pnpm add -D fallow-type-aware@{}",
970                    env!("CARGO_PKG_VERSION")
971                )
972                .as_str()
973            )
974        );
975    }
976
977    #[test]
978    fn installed_dependencies_pass_the_dependency_check() {
979        let root = tempfile::tempdir().expect("temp root");
980        std::fs::create_dir(root.path().join("node_modules")).expect("create node_modules");
981
982        let output = run_doctor_with_discovery(
983            &DoctorOptions {
984                root: root.path(),
985                config_path: None,
986            },
987            &|_| Err("missing companion".to_string()),
988        );
989
990        let dependencies = output
991            .checks
992            .iter()
993            .find(|check| check.id == DoctorCheckId::Dependencies)
994            .expect("dependencies check is reported");
995        assert_eq!(dependencies.status, DoctorCheckStatus::Pass);
996        assert_eq!(output.status, DoctorStatus::Pass);
997    }
998
999    /// A project with no cache yet is not a problem; only a cache that exists
1000    /// and would be thrown away is worth a warning.
1001    #[test]
1002    fn absent_cache_passes_the_cache_check() {
1003        let root = tempfile::tempdir().expect("temp root");
1004
1005        let output = run_doctor_with_discovery(
1006            &DoctorOptions {
1007                root: root.path(),
1008                config_path: None,
1009            },
1010            &|_| Err("missing companion".to_string()),
1011        );
1012
1013        let cache = output
1014            .checks
1015            .iter()
1016            .find(|check| check.id == DoctorCheckId::Cache)
1017            .expect("cache check is reported");
1018        assert_eq!(cache.status, DoctorCheckStatus::Pass);
1019        assert!(!cache.required);
1020    }
1021
1022    /// Framing this build never wrote is corruption, and must not be reported
1023    /// as a format bump.
1024    ///
1025    /// "cache format version changed" sends the reader to look for an upgrade;
1026    /// the fix for a blob with no fallow framing is to delete it. The upgrade
1027    /// message has its own test below, on a blob that keeps the framing and
1028    /// moves only the declared version.
1029    #[test]
1030    fn a_corrupt_cache_warns_as_undecodable_with_a_size_that_shows() {
1031        let root = tempfile::tempdir().expect("temp root");
1032        let cache_dir = root.path().join(".fallow");
1033        std::fs::create_dir_all(&cache_dir).expect("create cache dir");
1034        std::fs::write(
1035            cache_dir.join("cache.bin"),
1036            b"not-a-payload-this-build-wrote",
1037        )
1038        .expect("write foreign cache");
1039
1040        let output = run_doctor_with_discovery(
1041            &DoctorOptions {
1042                root: root.path(),
1043                config_path: None,
1044            },
1045            &|_| Err("missing companion".to_string()),
1046        );
1047
1048        let cache = output
1049            .checks
1050            .iter()
1051            .find(|check| check.id == DoctorCheckId::Cache)
1052            .expect("cache check is reported");
1053        assert_eq!(cache.status, DoctorCheckStatus::Warn);
1054        assert!(!cache.required);
1055        assert!(
1056            cache.message.contains("could not be decoded"),
1057            "a blob without fallow's framing is corrupt, not stale: {}",
1058            cache.message
1059        );
1060        assert!(
1061            !cache.message.contains("cache format version changed"),
1062            "corruption must not send the reader hunting for an upgrade: {}",
1063            cache.message
1064        );
1065        assert!(
1066            cache.message.contains("30 bytes"),
1067            "a small blob must report a size that shows it exists, not 0.0 MB: {}",
1068            cache.message
1069        );
1070        assert_ne!(
1071            output.status,
1072            DoctorStatus::Fail,
1073            "a refused cache costs time, not correctness"
1074        );
1075    }
1076
1077    /// The message a user reads after upgrading. A blob that keeps fallow's
1078    /// framing and declares a version this build does not write is stale, and
1079    /// costs exactly one rebuild.
1080    #[test]
1081    fn a_cache_from_an_older_format_version_warns_as_a_format_change() {
1082        let root = tempfile::tempdir().expect("temp root");
1083        let cache_dir = root.path().join(".fallow");
1084        std::fs::create_dir_all(&cache_dir).expect("create cache dir");
1085        // `FLWX` plus a little-endian version, the framing `fallow-extract`
1086        // writes. Version 1 is far below anything this build produces, so the
1087        // blob is stale rather than foreign.
1088        let mut framed = b"FLWX".to_vec();
1089        framed.extend_from_slice(&1_u32.to_le_bytes());
1090        framed.extend_from_slice(b"payload-from-an-older-release");
1091        std::fs::write(cache_dir.join("cache.bin"), framed).expect("write stale cache");
1092
1093        let output = run_doctor_with_discovery(
1094            &DoctorOptions {
1095                root: root.path(),
1096                config_path: None,
1097            },
1098            &|_| Err("missing companion".to_string()),
1099        );
1100
1101        let cache = output
1102            .checks
1103            .iter()
1104            .find(|check| check.id == DoctorCheckId::Cache)
1105            .expect("cache check is reported");
1106        assert_eq!(cache.status, DoctorCheckStatus::Warn);
1107        assert!(
1108            cache.message.contains("cache format version changed"),
1109            "{}",
1110            cache.message
1111        );
1112        assert!(
1113            !cache.message.contains("could not be decoded"),
1114            "an upgrade must not be reported as corruption: {}",
1115            cache.message
1116        );
1117    }
1118
1119    /// The graph blob is the larger of the two persisted caches and is reused
1120    /// independently of the extraction blob, so a doctor that only looked at
1121    /// the extraction cache called a project healthy while the expensive half
1122    /// was discarded on every run.
1123    #[test]
1124    fn absent_graph_cache_passes_its_own_check() {
1125        let root = tempfile::tempdir().expect("temp root");
1126
1127        let output = run_doctor_with_discovery(
1128            &DoctorOptions {
1129                root: root.path(),
1130                config_path: None,
1131            },
1132            &|_| Err("missing companion".to_string()),
1133        );
1134
1135        let graph_cache = output
1136            .checks
1137            .iter()
1138            .find(|check| check.id == DoctorCheckId::GraphCache)
1139            .expect("graph cache check is reported");
1140        assert_eq!(graph_cache.status, DoctorCheckStatus::Pass);
1141        assert!(!graph_cache.required);
1142    }
1143
1144    #[test]
1145    fn a_corrupt_graph_cache_warns_as_undecodable_with_a_size_that_shows() {
1146        let root = tempfile::tempdir().expect("temp root");
1147        let cache_dir = root.path().join(".fallow");
1148        std::fs::create_dir_all(&cache_dir).expect("create cache dir");
1149        std::fs::write(
1150            cache_dir.join("graph-cache.bin"),
1151            b"not-a-payload-this-build-wrote",
1152        )
1153        .expect("write foreign graph cache");
1154
1155        let output = run_doctor_with_discovery(
1156            &DoctorOptions {
1157                root: root.path(),
1158                config_path: None,
1159            },
1160            &|_| Err("missing companion".to_string()),
1161        );
1162
1163        let graph_cache = output
1164            .checks
1165            .iter()
1166            .find(|check| check.id == DoctorCheckId::GraphCache)
1167            .expect("graph cache check is reported");
1168        assert_eq!(graph_cache.status, DoctorCheckStatus::Warn);
1169        assert!(!graph_cache.required);
1170        assert!(
1171            graph_cache.message.contains("could not be decoded"),
1172            "a blob without fallow's framing is corrupt, not stale: {}",
1173            graph_cache.message
1174        );
1175        assert!(
1176            graph_cache.message.contains("30 bytes"),
1177            "a small blob must report a size that shows it exists, not 0.0 MB: {}",
1178            graph_cache.message
1179        );
1180        assert_ne!(
1181            output.status,
1182            DoctorStatus::Fail,
1183            "a refused cache costs time, not correctness"
1184        );
1185    }
1186
1187    #[test]
1188    fn invalid_config_returns_complete_failed_report() {
1189        let root = tempfile::tempdir().expect("temp root");
1190        std::fs::write(root.path().join(".fallowrc.json"), "{").expect("write invalid config");
1191
1192        let output = run_doctor_with_discovery(
1193            &DoctorOptions {
1194                root: root.path(),
1195                config_path: None,
1196            },
1197            &|_| Err("missing companion".to_string()),
1198        );
1199
1200        // Look checks up by id, not by position: the report's completeness is
1201        // the contract, the order in which the rows happen to be pushed is not.
1202        let check = |id: DoctorCheckId| {
1203            output
1204                .checks
1205                .iter()
1206                .find(|check| check.id == id)
1207                .unwrap_or_else(|| panic!("{id:?} is reported even when config fails"))
1208        };
1209
1210        assert_eq!(output.status, DoctorStatus::Fail);
1211        assert_eq!(
1212            output.checks.len(),
1213            8,
1214            "a failing config must not truncate the report"
1215        );
1216        assert_eq!(check(DoctorCheckId::Config).status, DoctorCheckStatus::Fail);
1217        assert_eq!(
1218            check(DoctorCheckId::Workspaces).status,
1219            DoctorCheckStatus::Skipped
1220        );
1221        assert!(
1222            !check(DoctorCheckId::Config)
1223                .message
1224                .contains(&root.path().display().to_string()),
1225            "the failure must not echo the host path"
1226        );
1227    }
1228
1229    #[test]
1230    fn optional_missing_type_aware_companion_warns() {
1231        let root = tempfile::tempdir().expect("temp root");
1232        std::fs::write(
1233            root.path().join(".fallowrc.json"),
1234            r#"{"typeAware":{"enabled":true}}"#,
1235        )
1236        .expect("write config");
1237
1238        let output = run_doctor_with_discovery(
1239            &DoctorOptions {
1240                root: root.path(),
1241                config_path: None,
1242            },
1243            &|_| Err("missing companion".to_string()),
1244        );
1245
1246        assert_eq!(output.status, DoctorStatus::Warn);
1247        assert_eq!(output.checks[4].status, DoctorCheckStatus::Warn);
1248        assert!(!output.checks[4].required);
1249    }
1250
1251    #[test]
1252    fn required_missing_type_aware_companion_fails() {
1253        let root = tempfile::tempdir().expect("temp root");
1254        std::fs::write(
1255            root.path().join(".fallowrc.json"),
1256            r#"{"typeAware":{"enabled":true,"require":"complete"}}"#,
1257        )
1258        .expect("write config");
1259
1260        let output = run_doctor_with_discovery(
1261            &DoctorOptions {
1262                root: root.path(),
1263                config_path: None,
1264            },
1265            &|_| Err("missing companion".to_string()),
1266        );
1267
1268        assert_eq!(output.status, DoctorStatus::Fail);
1269        assert_eq!(output.checks[4].status, DoctorCheckStatus::Fail);
1270        assert!(output.checks[4].required);
1271        assert_eq!(
1272            output.checks[4]
1273                .remediation
1274                .as_ref()
1275                .map(|remediation| remediation.mutating),
1276            Some(true)
1277        );
1278    }
1279
1280    #[test]
1281    fn invalid_root_does_not_echo_the_host_path() {
1282        let missing = Path::new("/definitely/missing/fallow-doctor-private-root");
1283        let output = run_doctor(&DoctorOptions {
1284            root: missing,
1285            config_path: None,
1286        });
1287
1288        assert_eq!(output.status, DoctorStatus::Fail);
1289        assert_eq!(output.root, ".");
1290        assert!(output.checks[0].message.contains("--root"));
1291        assert_eq!(
1292            output.checks[0].message,
1293            "Project root is not accessible. Set --root to an existing, readable directory."
1294        );
1295        assert!(
1296            output
1297                .checks
1298                .iter()
1299                .all(|check| !check.message.contains("fallow-doctor-private-root"))
1300        );
1301    }
1302
1303    #[test]
1304    fn external_config_does_not_echo_its_host_path() {
1305        let root = tempfile::tempdir().expect("temp root");
1306        std::fs::create_dir(root.path().join("node_modules")).expect("create node_modules");
1307        let config_dir = tempfile::tempdir().expect("temp config dir");
1308        let config_path = config_dir.path().join("external.fallowrc.json");
1309        std::fs::write(&config_path, "{}").expect("write config");
1310
1311        let output = run_doctor(&DoctorOptions {
1312            root: root.path(),
1313            config_path: Some(&config_path),
1314        });
1315
1316        assert_eq!(output.status, DoctorStatus::Pass);
1317        assert_eq!(
1318            output.checks[1].message,
1319            "The explicitly selected configuration resolved successfully."
1320        );
1321        assert!(
1322            !output.checks[1]
1323                .message
1324                .contains(&config_dir.path().display().to_string())
1325        );
1326    }
1327
1328    #[test]
1329    fn parent_relative_external_config_stays_private() {
1330        let sandbox = tempfile::tempdir().expect("temp sandbox");
1331        let root = sandbox.path().join("project");
1332        std::fs::create_dir(&root).expect("create project root");
1333        std::fs::create_dir(root.join("node_modules")).expect("create node_modules");
1334        let config_path = root.join("../customer-secret.json");
1335        std::fs::write(&config_path, "{}").expect("write config");
1336
1337        let output = run_doctor(&DoctorOptions {
1338            root: &root,
1339            config_path: Some(&config_path),
1340        });
1341
1342        assert_eq!(output.status, DoctorStatus::Pass);
1343        assert_eq!(
1344            output.checks[1].message,
1345            "The explicitly selected configuration resolved successfully."
1346        );
1347        assert!(!output.checks[1].message.contains("customer-secret"));
1348    }
1349
1350    #[cfg(unix)]
1351    #[test]
1352    fn successful_config_below_external_symlink_stays_private() {
1353        let root = tempfile::tempdir().expect("temp root");
1354        std::fs::create_dir(root.path().join("node_modules")).expect("create node_modules");
1355        let external = tempfile::tempdir().expect("external root");
1356        std::fs::write(external.path().join("config.json"), "{}").expect("write config");
1357        std::os::unix::fs::symlink(external.path(), root.path().join("external"))
1358            .expect("create external symlink");
1359        let config_path = root.path().join("external/config.json");
1360
1361        let output = run_doctor(&DoctorOptions {
1362            root: root.path(),
1363            config_path: Some(&config_path),
1364        });
1365
1366        assert_eq!(output.status, DoctorStatus::Pass);
1367        assert_eq!(
1368            output.checks[1].message,
1369            "The explicitly selected configuration resolved successfully."
1370        );
1371        assert!(!output.checks[1].message.contains("external/config.json"));
1372    }
1373
1374    #[test]
1375    fn relative_explicit_config_is_preserved_in_remediation() {
1376        let root = tempfile::tempdir().expect("temp root");
1377        let config_path = root.path().join("custom.json");
1378        std::fs::write(&config_path, "{").expect("write invalid config");
1379
1380        let output = run_doctor(&DoctorOptions {
1381            root: root.path(),
1382            config_path: Some(&config_path),
1383        });
1384
1385        assert_eq!(output.status, DoctorStatus::Fail);
1386        assert_eq!(
1387            output.checks[1]
1388                .remediation
1389                .as_ref()
1390                .map(|remediation| remediation.command.as_str()),
1391            Some("fallow config --config=custom.json")
1392        );
1393    }
1394
1395    #[test]
1396    fn nested_missing_project_relative_config_is_preserved_in_remediation() {
1397        let root = tempfile::tempdir().expect("temp root");
1398        let config_path = root.path().join("missing-dir/missing.json");
1399
1400        let output = run_doctor(&DoctorOptions {
1401            root: root.path(),
1402            config_path: Some(&config_path),
1403        });
1404
1405        assert_eq!(output.status, DoctorStatus::Fail);
1406        assert_eq!(
1407            output.checks[1]
1408                .remediation
1409                .as_ref()
1410                .map(|remediation| remediation.command.as_str()),
1411            Some("fallow config --config=missing-dir/missing.json")
1412        );
1413        assert!(
1414            !output.checks[1]
1415                .message
1416                .contains("same explicit --config value")
1417        );
1418    }
1419
1420    #[test]
1421    fn leading_dash_config_name_is_bound_to_its_option() {
1422        let root = tempfile::tempdir().expect("temp root");
1423        let config_path = root.path().join("-missing.json");
1424
1425        let output = run_doctor(&DoctorOptions {
1426            root: root.path(),
1427            config_path: Some(&config_path),
1428        });
1429
1430        assert_eq!(
1431            output.checks[1]
1432                .remediation
1433                .as_ref()
1434                .map(|remediation| remediation.command.as_str()),
1435            Some("fallow config --config=-missing.json")
1436        );
1437    }
1438
1439    #[test]
1440    fn config_path_equal_to_root_never_renders_an_empty_argument() {
1441        let root = tempfile::tempdir().expect("temp root");
1442
1443        let output = run_doctor(&DoctorOptions {
1444            root: root.path(),
1445            config_path: Some(root.path()),
1446        });
1447
1448        let command = output.checks[1]
1449            .remediation
1450            .as_ref()
1451            .map(|remediation| remediation.command.as_str());
1452        assert_eq!(command, Some("fallow config --config=."));
1453        assert_ne!(command, Some("fallow config --config="));
1454    }
1455
1456    #[test]
1457    fn missing_config_traversal_outside_root_stays_private() {
1458        let sandbox = tempfile::tempdir().expect("temp sandbox");
1459        let root = sandbox.path().join("project");
1460        std::fs::create_dir(&root).expect("create project root");
1461        let config_path = root.join("../missing.json");
1462
1463        let output = run_doctor(&DoctorOptions {
1464            root: &root,
1465            config_path: Some(&config_path),
1466        });
1467
1468        assert_eq!(output.status, DoctorStatus::Fail);
1469        assert!(output.checks[1].remediation.is_none());
1470        assert!(
1471            output.checks[1]
1472                .message
1473                .contains("same explicit --config value")
1474        );
1475        assert!(!output.checks[1].message.contains("missing.json"));
1476    }
1477
1478    #[cfg(unix)]
1479    #[test]
1480    fn missing_config_below_external_symlink_stays_private() {
1481        let root = tempfile::tempdir().expect("temp root");
1482        let external = tempfile::tempdir().expect("external root");
1483        std::os::unix::fs::symlink(external.path(), root.path().join("external"))
1484            .expect("create external symlink");
1485        let config_path = root.path().join("external/missing-dir/missing.json");
1486
1487        let output = run_doctor(&DoctorOptions {
1488            root: root.path(),
1489            config_path: Some(&config_path),
1490        });
1491
1492        assert_eq!(output.status, DoctorStatus::Fail);
1493        assert!(output.checks[1].remediation.is_none());
1494        assert!(
1495            output.checks[1]
1496                .message
1497                .contains("same explicit --config value")
1498        );
1499        assert!(!output.checks[1].message.contains("missing-dir"));
1500    }
1501
1502    #[test]
1503    fn failed_external_config_requires_reusing_the_private_value() {
1504        let root = tempfile::tempdir().expect("temp root");
1505        let config_dir = tempfile::tempdir().expect("temp config dir");
1506        let config_path = config_dir.path().join("external.json");
1507        std::fs::write(&config_path, "{").expect("write invalid config");
1508
1509        let output = run_doctor(&DoctorOptions {
1510            root: root.path(),
1511            config_path: Some(&config_path),
1512        });
1513
1514        assert_eq!(output.status, DoctorStatus::Fail);
1515        assert!(output.checks[1].remediation.is_none());
1516        assert!(
1517            output.checks[1]
1518                .message
1519                .contains("same explicit --config value")
1520        );
1521        assert!(
1522            !output.checks[1]
1523                .message
1524                .contains(&config_dir.path().display().to_string())
1525        );
1526    }
1527
1528    #[test]
1529    fn missing_explicit_plugin_is_a_required_failure() {
1530        let root = tempfile::tempdir().expect("temp root");
1531        std::fs::write(
1532            root.path().join(".fallowrc.json"),
1533            r#"{"plugins":["missing-plugin.json"]}"#,
1534        )
1535        .expect("write config");
1536
1537        let output = run_doctor(&DoctorOptions {
1538            root: root.path(),
1539            config_path: None,
1540        });
1541
1542        assert_eq!(output.status, DoctorStatus::Fail);
1543        assert_eq!(output.checks[3].status, DoctorCheckStatus::Fail);
1544        assert!(output.checks[3].required);
1545        assert!(
1546            output.checks[3]
1547                .message
1548                .contains("1 unresolved configured resource")
1549        );
1550        assert!(!output.checks[3].message.contains("missing-plugin.json"));
1551    }
1552
1553    #[test]
1554    fn malformed_explicit_plugin_is_a_required_failure() {
1555        let root = tempfile::tempdir().expect("temp root");
1556        std::fs::write(
1557            root.path().join(".fallowrc.json"),
1558            r#"{"plugins":["broken.json"]}"#,
1559        )
1560        .expect("write config");
1561        std::fs::write(root.path().join("broken.json"), "{").expect("write plugin");
1562
1563        let output = run_doctor(&DoctorOptions {
1564            root: root.path(),
1565            config_path: None,
1566        });
1567
1568        assert_eq!(output.status, DoctorStatus::Fail);
1569        assert_eq!(output.checks[3].status, DoctorCheckStatus::Fail);
1570        assert!(output.checks[3].required);
1571        assert!(
1572            output.checks[3]
1573                .message
1574                .contains("1 unresolved configured resource")
1575        );
1576        assert!(!output.checks[3].message.contains("broken.json"));
1577    }
1578
1579    #[test]
1580    fn explicit_plugin_directory_without_definitions_is_a_required_failure() {
1581        let root = tempfile::tempdir().expect("temp root");
1582        std::fs::create_dir(root.path().join("plugins")).expect("create plugin directory");
1583        std::fs::write(
1584            root.path().join(".fallowrc.json"),
1585            r#"{"plugins":["plugins"]}"#,
1586        )
1587        .expect("write config");
1588
1589        let output = run_doctor(&DoctorOptions {
1590            root: root.path(),
1591            config_path: None,
1592        });
1593
1594        assert_eq!(output.status, DoctorStatus::Fail);
1595        assert_eq!(output.checks[3].status, DoctorCheckStatus::Fail);
1596        assert!(output.checks[3].required);
1597        assert!(
1598            output.checks[3]
1599                .message
1600                .contains("1 unresolved configured resource")
1601        );
1602    }
1603
1604    #[test]
1605    fn inactive_external_plugin_warns_with_project_root_remediation() {
1606        let root = tempfile::tempdir().expect("temp root");
1607        std::fs::write(
1608            root.path().join("package.json"),
1609            r#"{"name":"doctor-test"}"#,
1610        )
1611        .expect("write package manifest");
1612        std::fs::write(
1613            root.path().join("fallow-plugin-doctor.json"),
1614            r#"{"name":"doctor-plugin","enablers":["missing-framework"]}"#,
1615        )
1616        .expect("write plugin");
1617
1618        let output = run_doctor_with_discovery(
1619            &DoctorOptions {
1620                root: root.path(),
1621                config_path: None,
1622            },
1623            &|_| Err("missing companion".to_string()),
1624        );
1625
1626        assert_eq!(output.status, DoctorStatus::Warn);
1627        assert_eq!(output.checks[3].status, DoctorCheckStatus::Warn);
1628        assert!(
1629            output.checks[3]
1630                .message
1631                .contains("0 active of 1 configured")
1632        );
1633        assert_eq!(
1634            output.checks[3]
1635                .remediation
1636                .as_ref()
1637                .map(|remediation| (remediation.cwd.as_str(), remediation.mutating)),
1638            Some((".", false))
1639        );
1640    }
1641
1642    #[test]
1643    fn active_external_plugin_passes() {
1644        let root = tempfile::tempdir().expect("temp root");
1645        std::fs::create_dir(root.path().join("node_modules")).expect("create node_modules");
1646        std::fs::write(
1647            root.path().join("package.json"),
1648            r#"{"name":"doctor-test","dependencies":{"doctor-framework":"1.0.0"}}"#,
1649        )
1650        .expect("write package manifest");
1651        std::fs::write(
1652            root.path().join("fallow-plugin-doctor.json"),
1653            r#"{"name":"doctor-plugin","enablers":["doctor-framework"]}"#,
1654        )
1655        .expect("write plugin");
1656
1657        let output = run_doctor_with_discovery(
1658            &DoctorOptions {
1659                root: root.path(),
1660                config_path: None,
1661            },
1662            &|_| Err("missing companion".to_string()),
1663        );
1664
1665        assert_eq!(output.status, DoctorStatus::Pass);
1666        assert_eq!(output.checks[3].status, DoctorCheckStatus::Pass);
1667        assert!(
1668            output.checks[3]
1669                .message
1670                .contains("1 active of 1 configured")
1671        );
1672    }
1673}