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