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