1use std::{
14 env,
15 io::Write,
16 path::Path,
17 process::{Command, Stdio},
18};
19
20use anyhow::Result;
21
22use crate::adapter::which_all;
23
24#[path = "doctor_yupana.rs"]
25mod yupana_guard;
26
27use crate::{
28 adapter,
29 model::{CrewMode, Plan, Profile, QuipuFlavor, State, ToolName},
30};
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum Level {
34 Ok,
35 Warn,
36 Fail,
37}
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Finding {
41 pub level: Level,
42 pub subject: String,
43 pub detail: String,
44}
45
46impl Finding {
47 fn new(level: Level, subject: impl Into<String>, detail: impl Into<String>) -> Self {
48 Self {
49 level,
50 subject: subject.into(),
51 detail: detail.into(),
52 }
53 }
54}
55
56pub struct Scope {
59 pub tools: Vec<ToolName>,
60 pub quipu_flavor: QuipuFlavor,
61 pub external_quipu: bool,
62 pub remote_quipu: Option<String>,
63 pub crew: Option<CrewMode>,
64 pub work_dir: bool,
68}
69
70impl Scope {
71 pub fn from_plan(plan: &Plan) -> Self {
72 Self {
73 tools: plan.tools.clone(),
74 quipu_flavor: plan.quipu_flavor,
75 external_quipu: plan.external_quipu,
76 remote_quipu: env::var("QUIPU_SERVER")
77 .ok()
78 .filter(|url| !url.trim().is_empty())
79 .or_else(|| plan.quipu_mcp.as_ref().map(|mcp| mcp.url.clone())),
80 crew: plan.crew.as_ref().map(|crew| crew.mode),
81 work_dir: false,
82 }
83 }
84
85 pub fn everything() -> Self {
86 Self {
87 tools: Profile::Everything.tools(),
88 quipu_flavor: QuipuFlavor::Release,
89 external_quipu: false,
90 remote_quipu: env::var("QUIPU_SERVER")
91 .ok()
92 .filter(|url| !url.trim().is_empty()),
93 crew: None,
94 work_dir: false,
95 }
96 }
97}
98
99pub fn installed(plan: &Plan, state: &State) -> bool {
101 !plan.tools.is_empty()
102 && plan.tools.iter().all(|tool| {
103 state
104 .tools
105 .get(tool.as_str())
106 .is_some_and(|recorded| recorded.verified)
107 })
108}
109
110pub fn is_work_dir(plan: &Path) -> bool {
113 plan.parent().map_or(true, |dir| {
114 dir.as_os_str().is_empty() || dir == Path::new(".")
115 })
116}
117
118fn one_line(text: &str) -> String {
120 text.split_whitespace().collect::<Vec<_>>().join(" ")
121}
122
123fn crew_prerequisites(mode: CrewMode) -> Vec<&'static str> {
124 let mut commands = vec!["curl"];
125 if matches!(mode, CrewMode::Shantytown | CrewMode::Both) {
126 commands.push("python3");
127 }
128 if matches!(mode, CrewMode::Creel | CrewMode::Both) {
129 commands.push("tar");
130 }
131 commands
132}
133
134fn prerequisite_hint(command: &str) -> &'static str {
135 match command {
136 "go" => "Desire Path is built from source: install Go 1.22+ from https://go.dev/dl/",
137 "cargo" => "install Rust from https://rustup.rs",
138 "python3" => "install Python 3.9+ from your package manager",
139 "git" | "curl" | "tar" | "bash" => "install it from your package manager",
140 _ => "install it and rerun `tambo doctor`",
141 }
142}
143
144pub const SELF_VERSION: &str = concat!(
146 "caboodle ",
147 env!("CARGO_PKG_VERSION"),
148 " (",
149 env!("CABOODLE_GIT_SHA"),
150 ")"
151);
152
153fn check_self_on_path(path: Option<&std::ffi::OsStr>) -> Option<Finding> {
157 let current = env::current_exe().ok()?;
158 let command = if current.file_name().is_some_and(|name| name == "tambo") {
159 "tambo"
160 } else {
161 "caboodle"
162 };
163 let self_version = format!(
164 "{command} {} ({})",
165 env!("CARGO_PKG_VERSION"),
166 env!("CABOODLE_GIT_SHA")
167 );
168 let runs = which_all(command, path).into_iter().next()?;
169 let canonical = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
170 if canonical(&runs) == canonical(¤t) {
171 return None;
172 }
173 let runs_version = Command::new(&runs)
174 .arg("--version")
175 .stdin(Stdio::null())
176 .output()
177 .ok()
178 .map(|out| {
179 String::from_utf8_lossy(&out.stdout)
180 .lines()
181 .next()
182 .unwrap_or("")
183 .trim()
184 .to_owned()
185 })
186 .filter(|v| !v.is_empty())
187 .unwrap_or_else(|| "version unreadable".to_owned());
188 Some(if runs_version == self_version {
189 Finding::new(
190 Level::Ok,
191 format!("{command} on PATH"),
192 format!(
193 "{} is a copy of this build ({self_version})",
194 runs.display()
195 ),
196 )
197 } else {
198 Finding::new(
199 Level::Warn,
200 format!("{command} on PATH"),
201 format!(
202 "PATH runs {} ({runs_version}), NOT this {command} {} ({self_version}). Remove the stale copy or reorder PATH",
203 runs.display(),
204 current.display()
205 ),
206 )
207 })
208}
209
210pub fn diagnose(scope: &Scope) -> Vec<Finding> {
212 let path = env::var_os("PATH");
213 let mut findings = vec![Finding::new(
214 Level::Ok,
215 "platform",
216 format!("{}-{}", env::consts::ARCH, env::consts::OS),
217 )];
218 findings.extend(check_bin_dir_on_path(
219 adapter::managed_bin_dir().as_deref(),
220 path.as_deref(),
221 ));
222 findings.extend(check_self_on_path(path.as_deref()));
223 findings.extend(check_prerequisites(scope, path.as_deref()));
224 for &tool in &scope.tools {
225 if tool == ToolName::Quipu && scope.external_quipu {
226 let mut plan = Plan::for_profile(Profile::Kg);
227 plan.external_quipu = true;
228 let identity = adapter::adapter_for_plan(tool, &plan).and_then(|a| a.version());
229 findings.push(match identity {
230 Ok(version) => Finding::new(
231 Level::Ok,
232 "quipu",
233 format!("externally owned ({})", one_line(&version)),
234 ),
235 Err(error) => Finding::new(
236 Level::Fail,
237 "quipu",
238 format!("external identity unavailable: {error:#}"),
239 ),
240 });
241 } else {
242 findings.extend(check_tool(tool, scope.quipu_flavor, path.as_deref()));
243 }
244 }
245 if let Some(server) = &scope.remote_quipu {
246 if scope.tools.contains(&ToolName::Camayoc) || scope.tools.contains(&ToolName::Quipu) {
247 findings.extend(check_graph(server));
248 }
249 }
250 findings.extend(check_mcp(scope));
251 if scope.tools.contains(&ToolName::Yupana) {
252 findings.extend(yupana_guard::check(path.as_deref()));
253 }
254 findings
255}
256
257fn expected_mcp_servers(scope: &Scope) -> Vec<&'static str> {
260 let mut names = Vec::new();
261 if scope.tools.contains(&ToolName::Bobbin) {
262 names.push("bobbin");
263 }
264 if scope.tools.contains(&ToolName::Yupana) {
265 names.push("yupana");
266 }
267 names
268}
269
270pub(crate) fn parse_mcp_list(text: &str) -> Vec<(String, bool)> {
272 text.lines()
273 .filter_map(|line| {
274 let (name, rest) = line.split_once(": ")?;
275 let (_, status) = rest.rsplit_once(" - ")?;
276 let name = name.trim();
277 if name.is_empty() || name.contains(' ') && !name.starts_with("claude.ai") {
278 return None;
279 }
280 Some((
281 name.to_owned(),
282 status.contains("Connected") && !status.contains("Failed"),
283 ))
284 })
285 .collect()
286}
287
288pub(crate) fn mcp_add_command(want: &str) -> String {
292 if want == "bobbin" {
293 "bobbin init && bobbin index && claude mcp add bobbin -- \"$(command -v bobbin)\" serve \"$PWD\"".to_owned()
294 } else {
295 format!("claude mcp add {want} -- \"$(command -v {want})\" serve")
296 }
297}
298
299pub(crate) fn mcp_findings(
300 expected: &[&str],
301 listed: &[(String, bool)],
302 work_dir: bool,
303) -> Vec<Finding> {
304 expected
305 .iter()
306 .map(|want| match listed.iter().find(|(name, _)| name == want) {
307 Some((_, true)) => Finding::new(Level::Ok, format!("mcp {want}"), "registered and connected"),
308 Some((_, false)) => Finding::new(
309 Level::Warn,
310 format!("mcp {want}"),
311 "registered but NOT connecting; agents in this directory get no tools from it. Run `claude mcp list` for the error",
312 ),
313 None if work_dir => Finding::new(
314 Level::Ok,
315 format!("mcp {want}"),
316 format!("not registered here, as expected: registration is per repository, and this is the Tambo work directory. In each repository you want searchable, run: `{}`", mcp_add_command(want)),
317 ),
318 None => Finding::new(
319 Level::Warn,
320 format!("mcp {want}"),
321 format!("not registered for this directory; agents here get no {want} tools. After install, from inside this repository: `{}`", mcp_add_command(want)),
322 ),
323 })
324 .collect()
325}
326
327fn check_mcp(scope: &Scope) -> Vec<Finding> {
328 let expected = expected_mcp_servers(scope);
329 if expected.is_empty() {
330 return Vec::new();
331 }
332 if which_all("claude", env::var_os("PATH").as_deref()).is_empty() {
333 return vec![Finding::new(
334 Level::Warn,
335 "mcp",
336 "cannot check MCP registration: the `claude` CLI is not on PATH",
337 )];
338 }
339 match Command::new("claude")
340 .args(["mcp", "list"])
341 .stdin(Stdio::null())
342 .output()
343 {
344 Ok(out) if out.status.success() => mcp_findings(
345 &expected,
346 &parse_mcp_list(&String::from_utf8_lossy(&out.stdout)),
347 scope.work_dir,
348 ),
349 Ok(out) => vec![Finding::new(
350 Level::Warn,
351 "mcp",
352 format!(
353 "`claude mcp list` failed ({}); MCP registration unknown",
354 out.status
355 ),
356 )],
357 Err(error) => vec![Finding::new(
358 Level::Warn,
359 "mcp",
360 format!("could not run `claude mcp list`: {error}; MCP registration unknown"),
361 )],
362 }
363}
364
365pub(crate) fn classify_write_probe(code: u16, body: &str, token_set: bool) -> Finding {
367 let token = if token_set {
368 "token from environment or configured file"
369 } else {
370 "no token (environment/file empty or absent)"
371 };
372 let data: serde_json::Value = serde_json::from_str(body).unwrap_or(serde_json::Value::Null);
373 let error = data["error"].as_str().unwrap_or("");
374 match code {
375 403 if data["reason"] == "server_is_read_only" => Finding::new(
376 Level::Warn, "quipu write",
377 "READ-ONLY: no credential can authorize writes; use the intended writable server",
378 ),
379 400 if error.starts_with("invalid episode JSON:") && error.contains("missing field") => Finding::new(
380 Level::Ok,
381 "quipu write",
382 format!("authorized ({token}); the probe was refused as an empty episode, nothing written"),
383 ),
384 401 => Finding::new(
385 Level::Warn,
386 "quipu write",
387 format!("{}: REFUSED with HTTP {code} ({token}). Obtain an accepted credential from the server administrator; install at ~/.config/quipu/token (mode 0400), or set QUIPU_AUTH_TOKEN_FILE. QUIPU_AUTH_TOKEN overrides the file", if token_set { "BAD-TOKEN" } else { "NO-TOKEN" }),
388 ),
389 0 => Finding::new(Level::Warn, "quipu write", "write probe got no HTTP answer; write path unknown"),
390 other => Finding::new(
391 Level::Warn,
392 "quipu write",
393 format!("write probe returned an unexpected HTTP {other} ({token}); write path unknown"),
394 ),
395 }
396}
397
398fn check_graph(server: &str) -> Vec<Finding> {
399 let mut findings = vec![check_quipu_server(server)];
400 let reachable = findings[0].detail.contains("is live");
401 let credential_ok = match crate::quipu_credential::verify(server) {
405 Ok(source) => {
406 findings.push(Finding::new(
407 Level::Ok,
408 "quipu credential",
409 format!("canonical file 0400/0700 and authenticated /shapes read accepted; source: {source}"),
410 ));
411 true
412 }
413 Err(error) => {
414 findings.push(Finding::new(
415 Level::Fail,
416 "quipu credential",
417 format!("{error:#}"),
418 ));
419 false
420 }
421 };
422 if !reachable {
423 return findings;
424 }
425 let base = server.trim_end_matches('/');
426 match adapter::camayoc_root()
429 .ok()
430 .map(|root| root.join("ontology/core.ttl"))
431 .filter(|path| path.exists())
432 .map(|path| adapter::camayoc_aegis_namespace(&path))
433 {
434 Some(Ok(namespace)) => {
435 let query = format!("SELECT ?p WHERE {{ <{namespace}Verification> ?p ?o }} LIMIT 1");
439 findings.push(
440 match adapter::curl_json(&format!("{base}/query"), &serde_json::json!({ "query": query })) {
441 Ok(answer) if answer["count"].as_u64().unwrap_or(0) > 0 => Finding::new(
442 Level::Ok,
443 "quipu namespace",
444 format!("{namespace} on {server}: read OK, camayoc's ontology is loaded here"),
445 ),
446 Ok(_) => Finding::new(
447 Level::Warn,
448 "quipu namespace",
449 format!("{namespace} on {server}: read OK but camayoc's ontology is NOT loaded here. Either it was never bootstrapped on this server, or this is the wrong server or namespace"),
450 ),
451 Err(error) => Finding::new(
452 Level::Warn,
453 "quipu namespace",
454 format!("{namespace} on {server}: read FAILED: {}", one_line(&format!("{error:#}"))),
455 ),
456 },
457 );
458 }
459 Some(Err(error)) => findings.push(Finding::new(
460 Level::Warn,
461 "quipu namespace",
462 format!(
463 "cannot resolve camayoc's namespace: {}",
464 one_line(&format!("{error:#}"))
465 ),
466 )),
467 None => findings.push(Finding::new(
468 Level::Ok,
469 "quipu namespace",
470 "camayoc not installed yet; namespace resolves after install",
471 )),
472 }
473 if !credential_ok {
474 return findings;
475 }
476 findings.push(match adapter::quipu_write_probe(base) {
477 Ok((code, body, token_set)) => classify_write_probe(code, &body, token_set),
478 Err(error) => Finding::new(
479 Level::Warn,
480 "quipu write",
481 format!(
482 "write probe could not run: {}",
483 one_line(&format!("{error:#}"))
484 ),
485 ),
486 });
487 findings
488}
489
490fn check_bin_dir_on_path(bin: Option<&Path>, path: Option<&std::ffi::OsStr>) -> Vec<Finding> {
491 let Some(bin) = bin else {
492 return vec![Finding::new(
493 Level::Fail,
494 "install directory",
495 "neither CARGO_HOME nor HOME is set; Tambo has nowhere to install binaries",
496 )];
497 };
498 let on_path = path.is_some_and(|path| env::split_paths(path).any(|entry| entry == bin));
499 if on_path {
500 vec![Finding::new(
501 Level::Ok,
502 "install directory",
503 format!("{} is on PATH", bin.display()),
504 )]
505 } else {
506 vec![Finding::new(
507 Level::Fail,
508 "install directory",
509 format!(
510 "{} is not on PATH, so installed tools cannot be read back; add `export PATH=\"{}:$PATH\"` to your shell profile",
511 bin.display(),
512 bin.display()
513 ),
514 )]
515 }
516}
517
518fn check_prerequisites(scope: &Scope, path: Option<&std::ffi::OsStr>) -> Vec<Finding> {
519 let mut needed: Vec<(&'static str, Vec<&'static str>)> = Vec::new();
520 let mut need = |command: &'static str, by: &'static str| match needed
521 .iter_mut()
522 .find(|(name, _)| *name == command)
523 {
524 Some((_, users)) if !users.contains(&by) => users.push(by),
525 Some(_) => {}
526 None => needed.push((command, vec![by])),
527 };
528 for &tool in &scope.tools {
529 for &command in adapter::prerequisites(tool, scope.quipu_flavor) {
530 need(command, tool.as_str());
531 }
532 }
533 if let Some(mode) = scope.crew {
534 for command in crew_prerequisites(mode) {
535 need(command, "crew");
536 }
537 }
538 needed
539 .into_iter()
540 .map(|(command, users)| match which_all(command, path).first() {
541 Some(found) => Finding::new(
542 Level::Ok,
543 format!("prerequisite {command}"),
544 found.display().to_string(),
545 ),
546 None => Finding::new(
547 Level::Fail,
548 format!("prerequisite {command}"),
549 format!(
550 "not on PATH, needed by {}; {}",
551 users.join(", "),
552 prerequisite_hint(command)
553 ),
554 ),
555 })
556 .collect()
557}
558
559fn check_tool(tool: ToolName, flavor: QuipuFlavor, path: Option<&std::ffi::OsStr>) -> Vec<Finding> {
560 let mut findings = Vec::new();
561 let adapter = adapter::adapter(tool, flavor);
562 let desired = adapter.desired_version();
563 match adapter.version() {
564 Ok(installed) if adapter.is_current(&installed) => findings.push(Finding::new(
565 Level::Ok,
566 tool.as_str(),
567 format!("installed and current ({})", one_line(&installed)),
568 )),
569 Ok(installed) => findings.push(Finding::new(
570 Level::Warn,
571 tool.as_str(),
572 format!(
573 "installed ({}) differs from the reviewed {desired}; `tambo check-updates` explains the drift",
574 one_line(&installed)
575 ),
576 )),
577 Err(_) => match adapter::release_blocker(tool, flavor) {
578 Some(blocker) => findings.push(Finding::new(
579 Level::Fail,
580 tool.as_str(),
581 format!("not installed and cannot be installed here: {blocker}. {}", source_hint(tool)),
582 )),
583 None => findings.push(Finding::new(
584 Level::Ok,
585 tool.as_str(),
586 format!("not installed yet; install will fetch {desired}"),
587 )),
588 },
589 }
590 for &program in adapter::programs(tool) {
591 let copies = which_all(program, path);
592 if copies.len() > 1 {
593 let listed = copies
594 .iter()
595 .map(|copy| copy.display().to_string())
596 .collect::<Vec<_>>()
597 .join(", ");
598 findings.push(Finding::new(
599 Level::Warn,
600 format!("{program} on PATH"),
601 format!(
602 "{} copies, the first one runs: {listed}. Remove the stale ones so a new install is the one you run",
603 copies.len()
604 ),
605 ));
606 }
607 }
608 findings
609}
610
611fn source_hint(tool: ToolName) -> String {
612 match adapter::source_install_command(tool) {
613 Some(command) => format!("Build it from source first, then rerun: `{command}`"),
614 None => "Install it by hand first, then rerun; Tambo adopts an installed tool that passes verification".to_owned(),
615 }
616}
617
618fn check_quipu_server(server: &str) -> Finding {
619 let reachable = Command::new("curl")
620 .args([
621 "-sf",
622 "-m",
623 "2",
624 &format!("{}/health", server.trim_end_matches('/')),
625 ])
626 .stdout(Stdio::null())
627 .stderr(Stdio::null())
628 .status()
629 .is_ok_and(|status| status.success());
630 match reachable {
631 false => Finding::new(
632 Level::Ok,
633 "quipu server",
634 format!(
635 "nothing answers at {server}; camayoc verification uses its own scratch server and never touches this address"
636 ),
637 ),
638 true => Finding::new(
639 Level::Ok,
640 "quipu server",
641 format!(
642 "{server} (explicit remote configuration) is live. camayoc verification does not write to it (it uses its own scratch server); run camayoc's scripts/bootstrap.sh yourself to set this server up"
643 ),
644 ),
645 }
646}
647
648pub fn report<W: Write>(findings: &[Finding], installed: bool, output: &mut W) -> Result<bool> {
652 for finding in findings {
653 let tag = match finding.level {
654 Level::Ok => "ok ",
655 Level::Warn => "warn",
656 Level::Fail => "FAIL",
657 };
658 writeln!(output, "{tag} {}: {}", finding.subject, finding.detail)?;
659 }
660 let failures = findings
661 .iter()
662 .filter(|finding| finding.level == Level::Fail)
663 .count();
664 let warnings = findings
665 .iter()
666 .filter(|finding| finding.level == Level::Warn)
667 .count();
668 let plural = if warnings == 1 { "" } else { "s" };
669 if failures == 0 && installed {
670 writeln!(
671 output,
672 "doctor: installed and verified ({warnings} warning{plural}); recheck with `tambo verify`"
673 )?;
674 } else if failures == 0 {
675 writeln!(
676 output,
677 "doctor: ready to install ({warnings} warning{plural})"
678 )?;
679 } else {
680 let earlier = if installed {
683 "installed and verified earlier, but "
684 } else {
685 ""
686 };
687 writeln!(
688 output,
689 "doctor: {earlier}{failures} blocker{} — fix the FAIL lines, then rerun `tambo doctor`",
690 if failures == 1 { "" } else { "s" }
691 )?;
692 }
693 Ok(failures == 0)
694}
695
696#[cfg(test)]
697mod tests {
698 use super::*;
699 use std::{ffi::OsString, fs, path::PathBuf};
700
701 const MCP_LIST: &str = "Checking MCP server health…\n\n\
703claude.ai Gmail: https://gmailmcp.example/mcp/v1 - ✔ Connected\n\
704bobbin: http://bobbin-mcp.example/mcp (HTTP) - ✔ Connected\n\
705yupana: yupana serve - ✗ Failed to connect\n";
706
707 #[test]
708 fn mcp_list_parses_connected_and_failed_servers() {
709 let listed = parse_mcp_list(MCP_LIST);
710 assert!(listed.contains(&("bobbin".to_owned(), true)));
711 assert!(listed.contains(&("yupana".to_owned(), false)));
712 assert!(!listed.iter().any(|(name, _)| name.starts_with("Checking")));
713 }
714
715 #[test]
716 fn mcp_findings_distinguish_connected_failing_and_missing() {
717 let listed = parse_mcp_list(MCP_LIST);
718 let got = mcp_findings(&["bobbin", "yupana", "quipu"], &listed, false);
719 assert_eq!(got[0].level, Level::Ok);
720 assert_eq!(got[1].level, Level::Warn);
721 assert!(got[1].detail.contains("NOT connecting"));
722 assert_eq!(got[2].level, Level::Warn);
723 assert!(got[2].detail.contains("not registered"));
724 assert!(mcp_findings(&["bobbin"], &[], false)
726 .iter()
727 .all(|f| f.level == Level::Warn));
728 }
729
730 #[test]
731 fn write_probe_is_authorized_only_on_a_validation_refusal() {
732 let ok = classify_write_probe(
733 400,
734 r#"{"error":"invalid episode JSON: missing field `name`"}"#,
735 true,
736 );
737 assert_eq!(ok.level, Level::Ok);
738 assert!(ok.detail.contains("nothing written"));
739
740 let refused = classify_write_probe(401, r#"{"error":"unauthorized"}"#, false);
741 assert_eq!(refused.level, Level::Warn);
742 assert!(refused.detail.contains("REFUSED") && refused.detail.contains("NO-TOKEN"));
743
744 assert!(classify_write_probe(401, "{}", true)
745 .detail
746 .contains("BAD-TOKEN"));
747 assert!(
748 classify_write_probe(403, r#"{"reason":"server_is_read_only"}"#, true)
749 .detail
750 .contains("READ-ONLY")
751 );
752 assert_eq!(
753 classify_write_probe(400, r#"{"error":"episode failed"}"#, true).level,
754 Level::Warn
755 );
756 assert_eq!(
758 classify_write_probe(400, "bad gateway html", true).level,
759 Level::Warn
760 );
761 assert_eq!(classify_write_probe(0, "", true).level, Level::Warn);
762 assert_eq!(classify_write_probe(200, "{}", true).level, Level::Warn);
763 }
764
765 fn executable(dir: &Path, name: &str) -> PathBuf {
766 let path = dir.join(name);
767 fs::write(&path, "#!/bin/sh\n").unwrap();
768 #[cfg(unix)]
769 {
770 use std::os::unix::fs::PermissionsExt;
771 fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).unwrap();
772 }
773 path
774 }
775
776 #[test]
777 fn which_all_lists_every_copy_in_path_order() {
778 let first = tempfile::tempdir().unwrap();
779 let second = tempfile::tempdir().unwrap();
780 let a = executable(first.path(), "yupana");
781 let b = executable(second.path(), "yupana");
782 fs::write(second.path().join("not-executable"), "").unwrap();
783 let path = env::join_paths([first.path(), second.path(), first.path()]).unwrap();
784 assert_eq!(which_all("yupana", Some(&path)), vec![a, b]);
785 assert!(which_all("not-executable", Some(&path)).is_empty());
786 assert!(which_all("yupana", None).is_empty());
787 }
788
789 #[test]
790 fn missing_install_directory_on_path_is_a_blocker() {
791 let bin = PathBuf::from("/opt/tambo-test/bin");
792 let without = OsString::from("/usr/bin:/bin");
793 let with = env::join_paths([Path::new("/usr/bin"), &bin]).unwrap();
794 let missing = check_bin_dir_on_path(Some(&bin), Some(&without));
795 assert_eq!(missing[0].level, Level::Fail);
796 assert!(missing[0].detail.contains("export PATH="));
797 assert_eq!(
798 check_bin_dir_on_path(Some(&bin), Some(&with))[0].level,
799 Level::Ok
800 );
801 }
802
803 #[test]
804 fn missing_prerequisite_names_the_tools_that_need_it() {
805 let empty = tempfile::tempdir().unwrap();
806 let path = env::join_paths([empty.path()]).unwrap();
807 let findings = check_prerequisites(&Scope::everything(), Some(&path));
808 let go = findings
809 .iter()
810 .find(|finding| finding.subject == "prerequisite go")
811 .expect("desire-path needs go");
812 assert_eq!(go.level, Level::Fail);
813 assert!(go.detail.contains("desire-path"));
814 let curl = findings
815 .iter()
816 .find(|finding| finding.subject == "prerequisite curl")
817 .unwrap();
818 assert!(curl.detail.contains("quipu") && curl.detail.contains("bobbin"));
819 assert_eq!(
820 findings
821 .iter()
822 .filter(|finding| finding.subject == "prerequisite curl")
823 .count(),
824 1,
825 "each command is reported once"
826 );
827 }
828
829 #[test]
830 fn report_fails_only_on_blockers() {
831 let mut out = Vec::new();
832 let warn_only = [Finding::new(Level::Warn, "x", "y")];
833 assert!(report(&warn_only, false, &mut out).unwrap());
834 let blocked = [Finding::new(Level::Fail, "x", "y")];
835 assert!(!report(&blocked, false, &mut out).unwrap());
836 let text = String::from_utf8(out).unwrap();
837 assert!(text.contains("ready to install (1 warning)"));
838 assert!(text.contains("FAIL x: y"));
839 }
840
841 #[test]
844 fn missing_registration_hint_uses_the_absolute_path_form() {
845 for work_dir in [false, true] {
846 let got = mcp_findings(&["bobbin"], &[], work_dir);
847 assert!(
848 got[0]
849 .detail
850 .contains(r#"claude mcp add bobbin -- "$(command -v bobbin)" serve "$PWD""#),
851 "{}",
852 got[0].detail
853 );
854 assert!(
855 !got[0].detail.contains("-- bobbin serve"),
856 "{}",
857 got[0].detail
858 );
859 }
860 let readme = include_str!("../README.md");
861 assert!(
862 readme.contains(r#"claude mcp add bobbin -- "$(command -v bobbin)" serve "$PWD""#),
863 "doctor and README must give the same registration"
864 );
865 }
866
867 #[test]
870 fn summary_reports_an_install_that_happened() {
871 let plan = Plan::for_profile(Profile::Retrieval);
872 let mut state = State::read(Path::new("/nonexistent/state.json")).unwrap();
873 assert!(!installed(&plan, &state), "empty state is not installed");
874 for tool in &plan.tools {
875 state.tools.insert(
876 tool.as_str().to_owned(),
877 crate::model::ToolState {
878 version: "1".into(),
879 applied: true,
880 verified: true,
881 },
882 );
883 }
884 assert!(installed(&plan, &state));
885 let first = plan.tools[0].as_str().to_owned();
886 state.tools.get_mut(&first).unwrap().verified = false;
887 assert!(
888 !installed(&plan, &state),
889 "one unverified tool is not installed"
890 );
891
892 let mut out = Vec::new();
893 assert!(report(&[], true, &mut out).unwrap());
894 let text = String::from_utf8(out).unwrap();
895 assert!(text.contains("installed and verified"), "{text}");
896 assert!(!text.contains("ready to install"), "{text}");
897 let blocked = [Finding::new(Level::Fail, "x", "y")];
898 let mut out = Vec::new();
899 assert!(!report(&blocked, true, &mut out).unwrap());
900 let text = String::from_utf8(out).unwrap();
901 assert!(
902 text.contains("installed and verified earlier, but 1 blocker"),
903 "{text}"
904 );
905 }
906
907 #[test]
910 fn missing_registration_does_not_warn_in_the_work_dir() {
911 assert!(is_work_dir(Path::new("caboodle-plan.toml")));
912 assert!(is_work_dir(Path::new("./caboodle-plan.toml")));
913 assert!(!is_work_dir(Path::new("/elsewhere/caboodle-plan.toml")));
914 let here = mcp_findings(&["bobbin"], &[], true);
915 assert_eq!(here[0].level, Level::Ok, "{}", here[0].detail);
916 assert!(
917 here[0].detail.contains("per repository"),
918 "{}",
919 here[0].detail
920 );
921 let repo = mcp_findings(&["bobbin"], &[], false);
922 assert_eq!(repo[0].level, Level::Warn);
923 }
924}