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