mod common;
use std::collections::BTreeMap;
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
const CHECKS: [&str; 12] = [
"daemon",
"token",
"distiller",
"peers",
"identity",
"recovery",
"service",
"mcp",
"hooks",
"data-dir",
"models",
"disk",
];
fn shim(dir: &Path, name: &str, body: &str) {
let path = dir.join(name);
std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}
fn doctor(home: &Path, api: &str) -> Output {
let shims_dir = tempfile::tempdir().unwrap();
let shims = shims_dir.path();
shim(shims, "systemctl", "exit 3");
shim(
shims,
"claude",
"echo 'No MCP server found with name: second-brain' >&2; exit 1",
);
Command::new(env!("CARGO_BIN_EXE_sb"))
.arg("doctor")
.env_clear()
.env("HOME", home)
.env("PATH", shims)
.env("SECOND_BRAIN_API", api)
.env("FASTEMBED_CACHE_DIR", home.join("elsewhere"))
.output()
.unwrap()
}
fn snapshot(root: &Path) -> BTreeMap<PathBuf, (u32, Vec<u8>)> {
let mut out = BTreeMap::new();
let mut stack = vec![root.to_path_buf()];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(&dir).unwrap() {
let path = entry.unwrap().path();
let meta = std::fs::symlink_metadata(&path).unwrap();
let mode = meta.permissions().mode();
if meta.is_dir() {
stack.push(path.clone());
out.insert(path, (mode, Vec::new()));
} else {
out.insert(path.clone(), (mode, std::fs::read(&path).unwrap()));
}
}
}
out
}
#[test]
fn a_fresh_home_with_no_daemon_fails_its_install_checks_each_with_a_fix() {
let home = tempfile::tempdir().unwrap();
let out = doctor(home.path(), &common::closed_port());
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(!out.status.success(), "{stdout}");
for name in CHECKS {
assert!(
stdout
.lines()
.any(|l| l.split_whitespace().nth(1) == Some(name)),
"no {name} line in:\n{stdout}"
);
}
let lines: Vec<&str> = stdout.lines().collect();
for (at, line) in lines.iter().enumerate() {
if line.starts_with("FAIL") || line.starts_with("WARN") {
let next = lines.get(at + 1).copied().unwrap_or_default();
assert!(next.trim_start().starts_with("fix: "), "{line}: {stdout}");
}
}
let daemon_cache = home.path().join(".cache/second-brain/models");
let models = lines
.iter()
.find(|l| l.split_whitespace().nth(1) == Some("models"))
.unwrap();
assert!(
models.contains(&*daemon_cache.to_string_lossy()),
"doctor must check the daemon's cache, not FASTEMBED_CACHE_DIR: {models}"
);
for failing in ["daemon", "service", "data-dir"] {
assert!(
lines
.iter()
.any(|l| l.starts_with("FAIL") && l.split_whitespace().nth(1) == Some(failing)),
"{failing} did not fail:\n{stdout}"
);
}
assert!(
String::from_utf8_lossy(&out.stderr).contains("checks failed"),
"{}",
String::from_utf8_lossy(&out.stderr)
);
}
#[test]
fn doctor_changes_nothing_in_home() {
let home = common::Home::new();
let data = home.path().join(".second-brain");
std::fs::set_permissions(&data, std::fs::Permissions::from_mode(0o755)).unwrap();
std::fs::set_permissions(
data.join("api.token"),
std::fs::Permissions::from_mode(0o644),
)
.unwrap();
std::fs::write(data.join("sync-peers"), "peer.invalid\n").unwrap();
let before = snapshot(home.path());
let out = doctor(home.path(), &common::closed_port());
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("chmod 700"), "{stdout}");
assert_eq!(before, snapshot(home.path()));
}
#[test]
fn a_failing_daemon_is_not_asked_for_the_integrity_report() {
let home = common::Home::new();
let daemon = common::daemon(common::Answer::Status(500, "{}".into()));
let out = doctor(home.path(), &daemon.base);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.starts_with("FAIL daemon"), "{stdout}");
let targets: Vec<String> = daemon.requests().into_iter().map(|r| r.target).collect();
assert!(
!targets.iter().any(|t| t.contains(" /v1/health ")),
"{targets:?}"
);
}
#[test]
fn an_answering_daemon_is_asked_for_the_integrity_report_with_the_token() {
let home = common::Home::new();
let health = r#"{"status":"ok","version":"0.12.0","state":"ok","serving":{"state":"ok"}}"#;
let daemon = common::daemon(common::Answer::Json(health.into()));
let out = doctor(home.path(), &daemon.base);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("\nstore integrity:\n"), "{stdout}");
let integrity: Vec<_> = daemon
.requests()
.into_iter()
.filter(|r| r.target.contains(" /v1/health "))
.collect();
assert_eq!(integrity.len(), 1, "{stdout}");
let token = "t".repeat(32);
assert!(
integrity[0]
.head
.contains(&format!("authorization: bearer {token}")),
"{}",
integrity[0].head
);
}
#[test]
fn a_starting_daemon_warns_and_fails_no_daemon_check() {
let home = common::Home::new();
let daemon = common::daemon(common::Answer::Routed(common::starting));
let out = doctor(home.path(), &daemon.base);
let stdout = String::from_utf8_lossy(&out.stdout);
let lines: Vec<&str> = stdout.lines().collect();
let at = lines
.iter()
.position(|l| l.split_whitespace().nth(1) == Some("daemon"))
.unwrap();
assert!(lines[at].starts_with("WARN"), "{stdout}");
assert!(lines[at].contains(common::STARTING_REASON), "{stdout}");
assert!(lines[at + 1].contains("sb doctor"), "{stdout}");
for name in ["daemon", "token", "distiller", "peers"] {
assert!(
!lines
.iter()
.any(|l| l.starts_with("FAIL") && l.split_whitespace().nth(1) == Some(name)),
"{name} failed:\n{stdout}"
);
}
let integrity = stdout.split("\nstore integrity:\n").nth(1).unwrap_or("");
assert!(integrity.contains("the daemon is starting"), "{stdout}");
}