use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;
use super::report::{Check, Context, Status};
use crate::claude_code::{self, Claude, Profile};
use crate::claude_hooks::{self, Audit, SETTINGS_FILE};
use crate::claude_mcp::{self, Entry, Lookup, Resolved, SERVER, Scope};
use crate::daemon::{self, render};
use crate::ordered_json::Json;
pub(crate) fn checks(ctx: &Context, exec: &mut dyn daemon::Exec) -> Vec<Check> {
vec![mcp(ctx, exec), hooks(ctx)]
}
fn setup(ctx: &Context) -> String {
let mut cmd = Command::new(&ctx.sb_bin);
cmd.arg("setup");
render(&cmd)
}
fn reinstall_mcp(ctx: &Context) -> String {
format!(
"reinstall second-brain with the one-command installer from the README, or run \
`cargo install second-brain-mcp`, then run `{}`",
setup(ctx)
)
}
fn profiles(ctx: &Context) -> Vec<Profile> {
claude_code::profiles(&ctx.home, ctx.claude_config_dir.as_deref())
}
fn mcp(ctx: &Context, exec: &mut dyn daemon::Exec) -> Check {
let profiles: Vec<Profile> = profiles(ctx)
.into_iter()
.filter(|profile| profile.is_current() || profile.dir.is_dir())
.collect();
let Some(program) = claude_code::locate(ctx.search_path.as_deref(), &ctx.home, &profiles)
else {
return no_claude(ctx, &profiles);
};
let mcp_bin = match &ctx.mcp_bin {
Ok(mcp_bin) => mcp_bin,
Err(e) => {
return Check::fail(
"mcp",
format!("{e}, so Claude Code sessions have no memory server to run"),
reinstall_mcp(ctx),
);
}
};
if let Err(problem) = daemon::program_usable(mcp_bin) {
return Check::fail(
"mcp",
format!(
"{} {problem}, so Claude Code sessions cannot start the memory server",
mcp_bin.display()
),
reinstall_mcp(ctx),
);
}
let judged = profiles
.into_iter()
.map(|profile| {
let claude = Claude {
program: program.clone(),
profile,
};
let check = mcp_in(ctx, mcp_bin, &claude, exec);
(claude.profile.mcp_config, check)
})
.collect();
combine_mcp(mcp_bin, judged)
}
fn no_claude(ctx: &Context, profiles: &[Profile]) -> Check {
let mut configured: Vec<String> = profiles
.iter()
.filter(|profile| profile.dir.is_dir())
.map(|profile| profile.dir.display().to_string())
.collect();
configured.dedup();
let mut setups: Vec<String> = profiles.iter().map(|p| setup_for(ctx, p)).collect();
setups.dedup();
if configured.is_empty() {
return Check::skip(
"mcp",
"Claude Code is not installed (no `claude` on PATH, in ~/.local/bin or in a Claude \
Code config dir), so there is nothing to register; other agents can still use the \
daemon",
);
}
Check::warn(
"mcp",
format!(
"Claude Code is configured in {}, but no `claude` is on PATH, in ~/.local/bin or in \
a config dir's local/, so the {SERVER} registration cannot be checked",
configured.join(", ")
),
format!("put `claude` on PATH, then run `{}`", setups.join(" && ")),
)
}
fn mcp_in(ctx: &Context, mcp_bin: &Path, claude: &Claude, exec: &mut dyn daemon::Exec) -> Check {
match claude_mcp::resolve(claude, exec) {
Ok(Resolved { shadow, user }) => {
let setup = setup_for(ctx, &claude.profile);
judge_mcp(mcp_bin, claude, &setup, shadow.as_ref(), user)
}
Err(e) => {
let mut version = Command::new(&claude.program);
version.arg("--version");
Check::fail(
"mcp",
format!(
"`{}` could not run ({e:#}), so the registration is unknown",
render(&claude_mcp::get_command(claude))
),
format!("check that `{}` runs", render(&version)),
)
}
}
}
fn combine_mcp(mcp_bin: &Path, mut judged: Vec<(PathBuf, Check)>) -> Check {
if judged.len() == 1
&& let Some((_, only)) = judged.pop()
{
return only;
}
let mut status = Status::Ok;
let mut problems = Vec::new();
let mut fixes: Vec<String> = Vec::new();
let mut configs = Vec::new();
for (config, check) in judged {
let config = config.display().to_string();
match check.status {
Status::Ok | Status::Skip => {}
Status::Warn if status != Status::Fail => status = Status::Warn,
Status::Warn => {}
Status::Fail => status = Status::Fail,
}
if check.status != Status::Ok {
problems.push(format!("{config}: {}", check.detail));
}
for step in check.fix.iter().flat_map(|fix| fix.split("; ")) {
if !fixes.iter().any(|known| known == step) {
fixes.push(step.to_string());
}
}
configs.push(config);
}
if status == Status::Ok {
return Check::ok(
"mcp",
format!(
"registered at user scope as {} in {}",
mcp_bin.display(),
configs.join(", ")
),
);
}
Check {
name: "mcp",
status,
detail: problems.join("; "),
fix: Some(fixes.join("; ")),
}
}
fn judge_mcp(
mcp_bin: &Path,
claude: &Claude,
setup: &str,
shadow: Option<&Entry>,
user: Lookup,
) -> Check {
let fix = match shadow {
Some(shadow) => format!("{setup}; {}", unshadow(claude, shadow)),
None => setup.to_string(),
};
let entry = match user {
Lookup::Found(entry) if entry.scope != Scope::User => {
return shadowed(mcp_bin, claude, &entry);
}
Lookup::Found(entry) => entry,
Lookup::Absent => {
return Check::warn(
"mcp",
format!(
"{SERVER} is not registered at user scope in Claude Code{}, \
so sessions have no memory tools",
shadow_note(shadow)
),
fix,
);
}
Lookup::Unreadable => {
return Check::fail(
"mcp",
format!(
"`claude mcp get {SERVER}` printed output sb cannot read, \
so the registration is unknown"
),
fix,
);
}
};
let mismatches = entry.mismatches(mcp_bin);
if !mismatches.is_empty() {
return Check::fail(
"mcp",
format!(
"the user-scope {SERVER} MCP server {}{}, \
so sessions do not run this install's server",
mismatches.join(", "),
shadow_note(shadow)
),
fix,
);
}
match shadow {
Some(shadow) => shadowed(mcp_bin, claude, shadow),
None => Check::ok(
"mcp",
format!("registered at user scope as {}", mcp_bin.display()),
),
}
}
fn shadow_note(shadow: Option<&Entry>) -> String {
match shadow {
Some(entry) => format!(
"; only a {} scope entry exists in this directory",
entry.scope.name()
),
None => String::new(),
}
}
fn shadowed(mcp_bin: &Path, claude: &Claude, entry: &Entry) -> Check {
let runs = entry.command.as_deref().unwrap_or("an unknown command");
let mcp_bin = mcp_bin.display();
let detail = match &entry.scope {
Scope::Other(label) => format!(
"an entry named {SERVER} from {label} takes precedence over the user-scope one \
in every directory, so Claude Code runs {runs} instead of {mcp_bin}"
),
scope => format!(
"a {} scope entry named {SERVER} shadows the user-scope one in this \
directory, so Claude Code here runs {runs} instead of {mcp_bin}",
scope.name()
),
};
Check::warn("mcp", detail, unshadow(claude, entry))
}
fn unshadow(claude: &Claude, entry: &Entry) -> String {
let prefix = match &entry.scope {
Scope::Other(label) => return format!("remove the {SERVER} entry from {label}"),
Scope::Project => String::new(),
_ => claude.profile.shell_prefix(),
};
format!(
"run `{prefix}{} mcp remove {SERVER} --scope {}` in this directory",
daemon::shell_word(&claude.program.to_string_lossy()),
entry.scope.name()
)
}
fn hooks(ctx: &Context) -> Check {
let mut dirs = Vec::new();
let judged: Vec<Judged> = profiles(ctx)
.into_iter()
.filter(|profile| {
let fresh = !dirs.contains(&profile.dir);
dirs.push(profile.dir.clone());
fresh
})
.filter_map(|profile| judge_profile(ctx, profile))
.collect();
if judged.is_empty() {
return Check::skip(
"hooks",
format!(
"no Claude Code settings in {} or a ~/.claude-* profile, so no agent here runs the \
second-brain hooks; `{}` registers them if Claude Code is used here",
ctx.claude_settings().display(),
setup(ctx)
),
);
}
let mut problems = Vec::new();
let mut repairs = Vec::new();
let mut setups = Vec::new();
let mut hooked = Vec::new();
for judged in &judged {
match &judged.verdict {
Verdict::Hooked => hooked.push(judged.settings.display().to_string()),
Verdict::Lacking(problem) => {
problems.push(problem.clone());
setups.push(setup_for(ctx, &judged.profile));
}
Verdict::Broken { detail, repair } => {
problems.push(detail.clone());
repairs.push(format!(
"{repair}, then run `{}`",
setup_for(ctx, &judged.profile)
));
}
}
}
if problems.is_empty() {
return Check::ok(
"hooks",
format!("all hooks registered in {}", hooked.join(", ")),
);
}
let detail = problems.join("; ");
if !repairs.is_empty() {
if !setups.is_empty() {
repairs.push(format!("run `{}`", setups.join(" && ")));
}
return Check::fail("hooks", detail, repairs.join("; "));
}
let fix = setups.join(" && ");
if hooked.is_empty() {
Check::fail("hooks", detail, fix)
} else {
Check::warn("hooks", detail, fix)
}
}
struct Judged {
profile: Profile,
settings: PathBuf,
verdict: Verdict,
}
enum Verdict {
Hooked,
Lacking(String),
Broken { detail: String, repair: String },
}
fn judge_profile(ctx: &Context, profile: Profile) -> Option<Judged> {
let settings = profile.dir.join(SETTINGS_FILE);
let path = settings.display().to_string();
let verdict = match std::fs::read_to_string(&settings) {
Err(e) if matches!(e.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory) => {
return None;
}
Err(e) => Verdict::Broken {
detail: format!("cannot read {path} ({e}), so its hooks cannot be checked"),
repair: format!("make {path} a JSON file you can read"),
},
Ok(text) => match serde_json::from_str::<Json>(&text) {
Err(e) => broken(&path, &format!("it is not valid JSON ({e})")),
Ok(doc) => match claude_hooks::audit(&doc, &ctx.sb_bin) {
Ok(audit) => judge_hooks(ctx, &path, &audit),
Err(detail) => broken(&path, &detail),
},
},
};
Some(Judged {
profile,
settings,
verdict,
})
}
fn broken(path: &str, detail: &str) -> Verdict {
Verdict::Broken {
detail: format!("{path} cannot hold the second-brain hooks: {detail}"),
repair: format!("repair the JSON in {path}"),
}
}
fn judge_hooks(ctx: &Context, path: &str, audit: &Audit) -> Verdict {
let mut problems = Vec::new();
if !audit.missing.is_empty() {
problems.push(format!(
"{path} has no second-brain hook for {}, so those events are neither recorded \
nor given recalled context",
audit.missing.join(", ")
));
}
if !audit.stale.is_empty() {
problems.push(format!(
"the second-brain hooks in {path} run {} instead of {}, left from an older install",
audit.stale.join(", "),
ctx.sb_bin.display()
));
}
if problems.is_empty() {
Verdict::Hooked
} else {
Verdict::Lacking(problems.join("; "))
}
}
fn setup_for(ctx: &Context, profile: &Profile) -> String {
format!("{}{}", profile.shell_prefix(), setup(ctx))
}
#[cfg(test)]
mod tests {
use std::collections::BTreeMap;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::os::unix::process::ExitStatusExt;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Output};
use anyhow::Result;
use serde_json::{Value, json};
use super::super::report::Status;
use super::*;
use crate::claude_code::Profile;
use crate::commands::hook::HOOK_EVENTS;
use crate::daemon::{Exec, Os, render};
const USER_LABEL: &str = "User config (available in all your projects)";
const LOCAL_LABEL: &str = "Local config (private to you in this project)";
const PROJECT_LABEL: &str = "Project config (shared via .mcp.json)";
struct Home {
dir: tempfile::TempDir,
}
impl Home {
fn new() -> Self {
let home = Home {
dir: tempfile::tempdir().unwrap(),
};
home.set_mcp_mode(0o755);
install(&home.claude_bin(), 0o755);
home
}
fn set_mcp_mode(&self, mode: u32) {
install(&self.mcp_bin(), mode);
}
fn claude_bin(&self) -> PathBuf {
self.dir.path().join(".local/bin/claude")
}
fn without_claude(self) -> Self {
fs::remove_file(self.claude_bin()).unwrap();
self
}
fn ctx(&self) -> Context {
let home = self.dir.path().to_path_buf();
Context {
os: Os::Linux,
data_dir: home.join(".second-brain"),
sb_bin: home.join("bin").join("sb"),
mcp_bin: Ok(home.join(".cargo/bin/second-brain-mcp")),
claude_config_dir: None,
search_path: None,
model_cache: home.join("models"),
home,
}
}
fn mcp_bin(&self) -> PathBuf {
self.ctx().mcp_bin.unwrap()
}
fn sb_bin(&self) -> PathBuf {
self.ctx().sb_bin
}
fn renamed_sb_ctx(&self) -> Context {
let mut ctx = self.ctx();
ctx.sb_bin = ctx.home.join("opt/brain/sb-0.12");
assert_ne!(ctx.sb_bin, ctx.home.join("bin").join("sb"));
ctx
}
fn write_settings(&self, text: &str) {
let path = self.ctx().claude_settings();
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, text).unwrap();
}
fn write_settings_json(&self, doc: &Value) {
self.write_settings(&serde_json::to_string_pretty(doc).unwrap());
}
fn profile(&self, name: &str) -> PathBuf {
self.dir.path().join(name)
}
fn write_profile(&self, dir: &Path, doc: &Value) {
fs::create_dir_all(dir.join("projects")).unwrap();
fs::write(
dir.join("settings.json"),
serde_json::to_string_pretty(doc).unwrap(),
)
.unwrap();
}
fn hooked(&self) -> Value {
settings_for(&self.sb_bin(), &all_events())
}
fn config_dir_ctx(&self, dir: &Path) -> Context {
let mut ctx = self.ctx();
ctx.claude_config_dir = Some(dir.to_path_buf());
ctx
}
}
fn install(path: &Path, mode: u32) {
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(path, "#!/bin/sh\n").unwrap();
fs::set_permissions(path, fs::Permissions::from_mode(mode)).unwrap();
}
fn output(code: i32, stdout: &str, stderr: &str) -> Result<Output> {
Ok(Output {
status: ExitStatus::from_raw(code << 8),
stdout: stdout.as_bytes().to_vec(),
stderr: stderr.as_bytes().to_vec(),
})
}
fn argv(cmd: &Command) -> Vec<String> {
std::iter::once(cmd.get_program())
.chain(cmd.get_args())
.map(|a| a.to_string_lossy().into_owned())
.collect()
}
type Reply = Box<dyn FnMut(&[String], Option<&Path>) -> Result<Output>>;
struct FakeExec {
calls: Vec<Vec<String>>,
reply: Reply,
}
impl FakeExec {
fn new(reply: impl FnMut(&[String], Option<&Path>) -> Result<Output> + 'static) -> Self {
FakeExec {
calls: Vec::new(),
reply: Box::new(reply),
}
}
fn always(stdout: String) -> Self {
Self::new(move |_, _| output(0, &stdout, ""))
}
}
impl Exec for FakeExec {
fn output(&mut self, cmd: Command) -> Result<Output> {
let argv = argv(&cmd);
let dir = cmd.get_current_dir().map(Path::to_path_buf);
let out = (self.reply)(&argv, dir.as_deref());
self.calls.push(argv);
out
}
}
fn api_env() -> String {
format!("SECOND_BRAIN_API=http://{}", daemon::DEFAULT_BIND)
}
fn get_output(scope_label: &str, command: &str, args: &str, env: &str) -> String {
format!(
"second-brain:\n Scope: {scope_label}\n Status: \u{2713} Connected\n Type: stdio\n \
Command: {command}\n Args: {args}\n Environment:\n {env}\n\n\
To remove this server, run: claude mcp remove \"second-brain\" -s user\n"
)
}
fn ours(home: &Home) -> String {
get_output(
USER_LABEL,
&home.mcp_bin().to_string_lossy(),
"",
&api_env(),
)
}
fn not_registered() -> Result<Output> {
output(1, "", "No MCP server found with name: second-brain\n")
}
fn run(home: &Home, exec: &mut FakeExec) -> Vec<Check> {
run_in(&home.ctx(), exec)
}
fn run_in(ctx: &Context, exec: &mut FakeExec) -> Vec<Check> {
let checks = checks(ctx, exec);
for call in &exec.calls {
assert!(call[0].ends_with("/claude"), "{call:?}");
assert_eq!(&call[1..3], ["mcp", "get"], "{call:?}");
}
checks
}
fn named(checks: &[Check], name: &str) -> Check {
checks
.iter()
.find(|c| c.name == name)
.cloned()
.unwrap_or_else(|| panic!("no {name} check in {checks:?}"))
}
fn mcp(home: &Home, exec: &mut FakeExec) -> Check {
named(&run(home, exec), "mcp")
}
fn hooks(home: &Home) -> Check {
named(&run(home, &mut FakeExec::always(ours(home))), "hooks")
}
fn hooks_in(home: &Home, ctx: &Context) -> Check {
named(&run_in(ctx, &mut FakeExec::always(ours(home))), "hooks")
}
fn follow(ctx: &Context, commands: &str) {
let setup = setup_command(&ctx.sb_bin);
for command in commands.split(" && ") {
let settings = if command == setup {
ctx.claude_settings().clone()
} else if command == format!("env -u CLAUDE_CONFIG_DIR {setup}") {
claude_hooks::settings_path(None, &ctx.home)
} else {
let dir = command
.strip_prefix("CLAUDE_CONFIG_DIR=")
.and_then(|rest| rest.strip_suffix(&format!(" {setup}")))
.unwrap_or_else(|| panic!("not a setup command: {command}"));
claude_hooks::settings_path(Some(std::ffi::OsStr::new(dir)), &ctx.home)
};
claude_hooks::register(&settings, &ctx.sb_bin).unwrap();
}
}
fn between_backticks(text: &str) -> &str {
text.split('`')
.nth(1)
.unwrap_or_else(|| panic!("no command in {text}"))
}
fn every_backticked(text: &str) -> Vec<&str> {
text.split('`').skip(1).step_by(2).collect()
}
fn fix(check: &Check) -> String {
check
.fix
.clone()
.unwrap_or_else(|| panic!("{check:?} has no fix"))
}
fn assert_check(check: &Check, status: Status, detail: &str, fix_part: &str) {
assert_eq!(check.status, status, "{check:?}");
assert!(check.detail.contains(detail), "{check:?}");
assert!(fix(check).contains(fix_part), "{check:?}");
}
fn hook_command(sb: &Path, name: &str) -> String {
let mut cmd = Command::new(sb);
cmd.args(["hook", name]);
render(&cmd)
}
fn group(command: &str) -> Value {
json!({"hooks": [{"type": "command", "command": command, "timeout": 10}]})
}
fn settings_for(sb: &Path, events: &[&str]) -> Value {
let mut hooks = serde_json::Map::new();
for e in HOOK_EVENTS.iter().filter(|e| events.contains(&e.event)) {
hooks.insert(
e.event.to_string(),
json!([group(&hook_command(sb, e.name))]),
);
}
json!({"model": "opus", "hooks": hooks})
}
fn all_events() -> Vec<&'static str> {
HOOK_EVENTS.iter().map(|e| e.event).collect()
}
#[test]
fn returns_mcp_then_hooks() {
let home = Home::new();
home.write_settings_json(&settings_for(&home.sb_bin(), &all_events()));
let names: Vec<&str> = run(&home, &mut FakeExec::always(ours(&home)))
.iter()
.map(|c| c.name)
.collect();
assert_eq!(names, ["mcp", "hooks"]);
}
#[test]
fn mcp_registered_as_setup_would_is_ok_with_the_binary_path() {
let home = Home::new();
let check = mcp(&home, &mut FakeExec::always(ours(&home)));
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(
check.detail.contains(&*home.mcp_bin().to_string_lossy()),
"{check:?}"
);
assert_eq!(check.fix, None);
}
#[test]
fn mcp_not_registered_warns_with_setup_as_the_fix() {
let home = Home::new();
let check = mcp(&home, &mut FakeExec::new(|_, _| not_registered()));
assert_check(&check, Status::Warn, "not registered", "sb setup");
}
#[test]
fn mcp_pointing_at_another_binary_fails_naming_it() {
let home = Home::new();
let stale = get_output(USER_LABEL, "/old/place/second-brain-mcp", "", &api_env());
let check = mcp(&home, &mut FakeExec::always(stale));
assert_check(
&check,
Status::Fail,
"/old/place/second-brain-mcp",
"sb setup",
);
}
#[test]
fn mcp_with_extra_args_fails_naming_them() {
let home = Home::new();
let listing = get_output(
USER_LABEL,
&home.mcp_bin().to_string_lossy(),
"--debug-wire",
&api_env(),
);
let check = mcp(&home, &mut FakeExec::always(listing));
assert_check(&check, Status::Fail, "--debug-wire", "sb setup");
}
#[test]
fn mcp_with_another_api_address_fails_naming_it() {
let home = Home::new();
let listing = get_output(
USER_LABEL,
&home.mcp_bin().to_string_lossy(),
"",
"SECOND_BRAIN_API=http://127.0.0.1:9999",
);
let check = mcp(&home, &mut FakeExec::always(listing));
assert_check(&check, Status::Fail, "127.0.0.1:9999", "sb setup");
}
#[test]
fn mcp_shadowed_by_a_project_local_entry_warns_with_the_remove_command() {
for (label, scope) in [(LOCAL_LABEL, "local"), (PROJECT_LABEL, "project")] {
let home = Home::new();
let shadow = get_output(label, "/elsewhere/second-brain-mcp", "", &api_env());
let user = ours(&home);
let mut exec = FakeExec::new(move |_, dir| match dir {
None => output(0, &shadow, ""),
Some(_) => output(0, &user, ""),
});
let check = mcp(&home, &mut exec);
assert_check(
&check,
Status::Warn,
scope,
&format!("claude mcp remove second-brain --scope {scope}"),
);
}
}
#[test]
fn mcp_only_at_local_scope_warns_because_other_projects_lack_it() {
let home = Home::new();
let shadow = get_output(
LOCAL_LABEL,
&home.mcp_bin().to_string_lossy(),
"",
&api_env(),
);
let mut exec = FakeExec::new(move |_, dir| match dir {
None => output(0, &shadow, ""),
Some(_) => not_registered(),
});
let check = mcp(&home, &mut exec);
assert_check(&check, Status::Warn, "local", "sb setup");
}
#[test]
fn hooks_in_broken_json_fail_with_the_parse_error_and_the_file_to_repair() {
let home = Home::new();
home.write_settings("{\"hooks\": ");
let check = hooks(&home);
let path = home.ctx().claude_settings();
assert_check(&check, Status::Fail, "EOF while parsing", "sb setup");
assert!(fix(&check).contains(&*path.to_string_lossy()), "{check:?}");
}
#[test]
fn hooks_missing_some_events_fail_listing_them() {
let home = Home::new();
home.write_settings_json(&settings_for(&home.sb_bin(), &["Stop", "SessionStart"]));
let check = hooks(&home);
assert_check(&check, Status::Fail, "UserPromptSubmit", "sb setup");
assert!(check.detail.contains("SubagentStart"), "{check:?}");
}
#[test]
fn hooks_absent_from_valid_settings_fail_listing_every_event() {
let home = Home::new();
home.write_settings("{\"model\": \"opus\"}\n");
let check = hooks(&home);
assert_eq!(check.status, Status::Fail, "{check:?}");
for event in all_events() {
assert!(check.detail.contains(event), "{event} in {check:?}");
}
assert!(fix(&check).contains("sb setup"), "{check:?}");
}
#[test]
fn hooks_pointing_at_an_old_sb_fail_naming_that_path() {
let home = Home::new();
home.write_settings_json(&settings_for(Path::new("/old/place/sb"), &all_events()));
let check = hooks(&home);
assert_check(&check, Status::Fail, "/old/place/sb", "sb setup");
}
#[test]
fn hooks_all_current_are_ok_with_the_settings_path() {
let home = Home::new();
home.write_settings_json(&settings_for(&home.sb_bin(), &all_events()));
let check = hooks(&home);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(
check
.detail
.contains(&*home.ctx().claude_settings().to_string_lossy()),
"{check:?}"
);
assert_eq!(check.fix, None);
}
#[test]
fn hooks_current_beside_foreign_hooks_are_ok() {
let home = Home::new();
let mut doc = settings_for(&home.sb_bin(), &all_events());
doc["hooks"]["Stop"]
.as_array_mut()
.unwrap()
.insert(0, group("/usr/local/bin/notify done"));
doc["hooks"]["PreToolUse"] = json!([group("guard")]);
home.write_settings_json(&doc);
let check = hooks(&home);
assert_eq!(check.status, Status::Ok, "{check:?}");
}
#[test]
fn mcp_when_claude_cannot_run_fails_naming_the_error() {
let home = Home::new();
let mut exec = FakeExec::new(|_, _| {
Err(
anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied))
.context("failed to run claude mcp get second-brain"),
)
});
let check = mcp(&home, &mut exec);
assert_check(
&check,
Status::Fail,
"failed to run claude mcp get second-brain",
&format!("{} --version", home.claude_bin().display()),
);
let ctx = home.ctx();
let mut runs = Registry::new(&ctx);
runs.set_user(None, ours(&home));
let after = mcp_in(&ctx, &mut runs);
assert_eq!(after.status, Status::Ok, "{after:?}");
}
#[test]
fn mcp_overridden_by_a_managed_entry_warns_naming_its_source() {
let home = Home::new();
let label = "Enterprise config (managed by your organization)";
let managed = get_output(label, "/managed/second-brain-mcp", "", &api_env());
let check = mcp(&home, &mut FakeExec::always(managed));
assert_check(
&check,
Status::Warn,
label,
&format!("remove the second-brain entry from {label}"),
);
assert!(
check.detail.contains("/managed/second-brain-mcp"),
"{check:?}"
);
}
#[test]
fn hooks_under_a_hooks_list_fail_with_the_shape_setup_refuses() {
let home = Home::new();
home.write_settings("{\"hooks\": []}");
let check = hooks(&home);
assert_check(
&check,
Status::Fail,
"\"hooks\" is not an object",
"sb setup",
);
assert!(fix(&check).contains("repair the JSON"), "{check:?}");
}
#[test]
fn hooks_with_an_old_copy_beside_the_current_one_fail_naming_it() {
let home = Home::new();
let mut doc = settings_for(&home.sb_bin(), &all_events());
doc["hooks"]["Stop"]
.as_array_mut()
.unwrap()
.push(group(&hook_command(Path::new("/old/place/sb"), "stop")));
home.write_settings_json(&doc);
let check = hooks(&home);
assert_check(&check, Status::Fail, "/old/place/sb", "sb setup");
assert!(!check.detail.contains("no second-brain hook"), "{check:?}");
}
#[test]
fn hooks_without_any_claude_settings_skip_without_a_fix() {
let home = Home::new();
let check = hooks(&home);
assert_eq!(check.status, Status::Skip, "{check:?}");
assert_eq!(check.fix, None, "{check:?}");
}
#[test]
fn hooks_beside_claude_dirs_without_settings_skip() {
let home = Home::new();
fs::create_dir_all(home.ctx().claude_settings().parent().unwrap()).unwrap();
fs::create_dir_all(home.profile(".claude-work")).unwrap();
let check = hooks(&home);
assert_eq!(check.status, Status::Skip, "{check:?}");
assert_eq!(check.fix, None, "{check:?}");
}
#[test]
fn hooks_ignore_claude_prefixed_dirs_and_files_that_are_not_profiles() {
let home = Home::new();
let tool = home.profile(".claude-tool");
fs::create_dir_all(&tool).unwrap();
fs::write(tool.join("settings.json"), "{}").unwrap();
fs::write(home.profile(".claude-notes"), "{}").unwrap();
assert_eq!(hooks(&home).status, Status::Skip);
home.write_settings_json(&home.hooked());
let check = hooks(&home);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(!check.detail.contains(".claude-tool"), "{check:?}");
}
#[test]
fn hooks_in_broken_json_beside_a_profile_lacking_them_fail_and_both_fixes_clear_it() {
let home = Home::new();
let broken = home.profile(".claude-a");
let lacking = home.profile(".claude-b");
home.write_settings_json(&home.hooked());
home.write_profile(&broken, &json!({}));
fs::write(broken.join("settings.json"), "{\"hooks\": ").unwrap();
home.write_profile(&lacking, &json!({}));
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Fail, "{check:?}");
for dir in [&broken, &lacking] {
assert!(check.detail.contains(&*dir.to_string_lossy()), "{check:?}");
}
fs::write(broken.join("settings.json"), "{}").unwrap();
let fix = fix(&check);
let commands = every_backticked(&fix);
assert_eq!(commands.len(), 2, "{check:?}");
for command in commands {
follow(&ctx, command);
}
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_with_unreadable_settings_fail_and_replacing_the_file_then_the_fix_clears_it() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
fs::create_dir_all(work.join("projects")).unwrap();
fs::create_dir_all(work.join("settings.json")).unwrap();
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(fix(&check).contains("JSON file you can read"), "{check:?}");
fs::remove_dir(work.join("settings.json")).unwrap();
fs::write(work.join("settings.json"), "{}").unwrap();
follow(&ctx, between_backticks(&fix(&check)));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_failing_in_the_one_profile_are_cleared_by_their_printed_fix() {
let cases: [(&str, fn(&Home) -> Value, bool); 3] = [
(
"stale",
|_| settings_for(Path::new("/old/place/sb"), &all_events()),
false,
),
(
"partial",
|home| settings_for(&home.sb_bin(), &["Stop"]),
false,
),
("hooks as a list", |_| json!({"hooks": []}), true),
];
for (name, settings, needs_repair) in cases {
let home = Home::new();
home.write_settings_json(&settings(&home));
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Fail, "{name}: {check:?}");
let fix = fix(&check);
if needs_repair {
home.write_settings("{}");
follow(&ctx, between_backticks(&fix));
} else {
follow(&ctx, &fix);
}
let after = hooks_in(&home, &ctx);
assert_eq!(after.status, Status::Ok, "{name}: {after:?}");
}
}
#[test]
fn hooks_in_every_profile_are_ok_naming_each() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
home.write_profile(&work, &home.hooked());
let check = hooks(&home);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(check.detail.contains(&*work.to_string_lossy()), "{check:?}");
}
#[test]
fn hooks_missing_from_one_of_two_profiles_warn_and_the_fix_clears_it() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
home.write_profile(&work, &json!({"model": "opus"}));
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&*work.to_string_lossy()), "{check:?}");
assert!(
!check
.detail
.contains(&*ctx.claude_settings().to_string_lossy()),
"{check:?}"
);
assert!(fix(&check).starts_with("CLAUDE_CONFIG_DIR="), "{check:?}");
follow(&ctx, &fix(&check));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_missing_from_the_default_profile_only_need_plain_setup() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings("{}\n");
home.write_profile(&work, &home.hooked());
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_eq!(fix(&check), setup_command(&ctx.sb_bin), "{check:?}");
follow(&ctx, &fix(&check));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_missing_from_every_profile_fail_and_the_fix_clears_it() {
let home = Home::new();
home.write_settings("{}\n");
home.write_profile(&home.profile(".claude-a"), &json!({}));
home.write_profile(&home.profile(".claude-b"), &json!({}));
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Fail, "{check:?}");
for name in [".claude-a", ".claude-b"] {
assert!(check.detail.contains(name), "{name} in {check:?}");
}
follow(&ctx, &fix(&check));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_under_claude_config_dir_are_checked_with_the_default_profile() {
let home = Home::new();
let elsewhere = tempfile::tempdir().unwrap();
let active = elsewhere.path().join("claude");
home.write_profile(&active, &json!({}));
home.write_settings_json(&home.hooked());
let ctx = home.config_dir_ctx(&active);
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(
check.detail.contains(&*active.to_string_lossy()),
"{check:?}"
);
assert_eq!(fix(&check), setup_command(&ctx.sb_bin), "{check:?}");
follow(&ctx, &fix(&check));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_missing_from_the_default_profile_under_claude_config_dir_unset_it_in_the_fix() {
let home = Home::new();
let elsewhere = tempfile::tempdir().unwrap();
let active = elsewhere.path().join("claude");
home.write_profile(&active, &home.hooked());
home.write_settings("{}\n");
let ctx = home.config_dir_ctx(&active);
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_eq!(
fix(&check),
format!("env -u CLAUDE_CONFIG_DIR {}", setup_command(&ctx.sb_bin)),
"{check:?}"
);
follow(&ctx, &fix(&check));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn hooks_in_broken_json_of_another_profile_fail_and_repairing_then_the_fix_clears_it() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
fs::create_dir_all(work.join("projects")).unwrap();
fs::write(work.join("settings.json"), "{\"hooks\": ").unwrap();
let ctx = home.ctx();
let check = hooks_in(&home, &ctx);
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(check.detail.contains(&*work.to_string_lossy()), "{check:?}");
fs::write(work.join("settings.json"), "{}").unwrap();
follow(&ctx, between_backticks(&fix(&check)));
assert_eq!(hooks_in(&home, &ctx).status, Status::Ok);
}
#[test]
fn mcp_registered_with_the_located_binary_outside_bin_dir_is_ok() {
let home = Home::new();
let ctx = home.ctx();
assert_ne!(
home.mcp_bin().parent(),
Some(ctx.home.join("bin").as_path())
);
let check = mcp(&home, &mut FakeExec::always(ours(&home)));
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(
check.detail.contains(&*home.mcp_bin().to_string_lossy()),
"{check:?}"
);
}
#[test]
fn mcp_registered_beside_sb_but_not_at_the_located_binary_fails_naming_both() {
let home = Home::new();
let ctx = home.ctx();
let sibling = ctx.home.join("bin").join("second-brain-mcp");
let listing = get_output(USER_LABEL, &sibling.to_string_lossy(), "", &api_env());
let check = mcp(&home, &mut FakeExec::always(listing));
assert_check(&check, Status::Fail, &sibling.to_string_lossy(), "sb setup");
assert!(
check.detail.contains(&*home.mcp_bin().to_string_lossy()),
"{check:?}"
);
}
fn setup_command(sb: &Path) -> String {
let mut cmd = Command::new(sb);
cmd.arg("setup");
render(&cmd)
}
#[test]
fn hooks_registered_by_setup_with_a_renamed_sb_are_ok() {
let home = Home::new();
let ctx = home.renamed_sb_ctx();
home.write_settings_json(&settings_for(&ctx.sb_bin, &all_events()));
let check = named(&run_in(&ctx, &mut FakeExec::always(ours(&home))), "hooks");
assert_eq!(check.status, Status::Ok, "{check:?}");
assert_eq!(check.fix, None);
}
#[test]
fn hooks_running_bin_dir_sb_instead_of_the_running_sb_fail_naming_the_running_sb() {
let home = Home::new();
let ctx = home.renamed_sb_ctx();
home.write_settings_json(&settings_for(
&ctx.home.join("bin").join("sb"),
&all_events(),
));
let check = named(&run_in(&ctx, &mut FakeExec::always(ours(&home))), "hooks");
assert_check(
&check,
Status::Fail,
&ctx.home.join("bin").join("sb").to_string_lossy(),
&setup_command(&ctx.sb_bin),
);
assert!(
check.detail.contains(&*ctx.sb_bin.to_string_lossy()),
"{check:?}"
);
}
#[test]
fn setup_fixes_name_the_running_sb_even_when_renamed() {
let home = Home::new();
let ctx = home.renamed_sb_ctx();
home.write_settings("{}\n");
let checks = run_in(&ctx, &mut FakeExec::new(|_, _| not_registered()));
let want = setup_command(&ctx.sb_bin);
for name in ["mcp", "hooks"] {
let check = named(&checks, name);
assert_ne!(check.status, Status::Ok, "{check:?}");
assert_eq!(fix(&check), want, "{check:?}");
}
}
#[test]
fn mcp_without_a_located_binary_fails_with_the_lookup_error_and_the_install_hint() {
let home = Home::new();
let mut ctx = home.ctx();
ctx.mcp_bin = Err("second-brain-mcp was not found beside sb or on PATH".to_string());
let listing = get_output(USER_LABEL, "/elsewhere/second-brain-mcp", "", &api_env());
let check = named(&run_in(&ctx, &mut FakeExec::always(listing)), "mcp");
assert_check(
&check,
Status::Fail,
"second-brain-mcp was not found beside sb or on PATH",
"cargo install second-brain-mcp",
);
assert!(fix(&check).contains("installer"), "{check:?}");
}
#[test]
fn mcp_registered_at_a_located_binary_that_is_gone_fails_naming_it() {
let home = Home::new();
fs::remove_file(home.mcp_bin()).unwrap();
let check = mcp(&home, &mut FakeExec::always(ours(&home)));
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(
check.detail.contains(&*home.mcp_bin().to_string_lossy()),
"{check:?}"
);
assert!(check.detail.contains("does not exist"), "{check:?}");
assert!(check.fix.is_some(), "{check:?}");
}
#[test]
fn mcp_registered_at_a_located_binary_that_cannot_run_fails_saying_so() {
let home = Home::new();
home.set_mcp_mode(0o644);
let check = mcp(&home, &mut FakeExec::always(ours(&home)));
assert_eq!(check.status, Status::Fail, "{check:?}");
assert!(
check.detail.contains(&*home.mcp_bin().to_string_lossy()),
"{check:?}"
);
assert!(check.detail.contains("not executable"), "{check:?}");
assert!(check.fix.is_some(), "{check:?}");
}
const PROJECT_FILE: &str = ".mcp.json";
struct Registry {
home: PathBuf,
shell_config_dir: Option<PathBuf>,
user: BTreeMap<PathBuf, String>,
shadows: BTreeMap<PathBuf, (String, String)>,
calls: Vec<Vec<String>>,
}
impl Registry {
fn new(ctx: &Context) -> Self {
Registry {
home: ctx.home.clone(),
shell_config_dir: ctx.claude_config_dir.clone(),
user: BTreeMap::new(),
shadows: BTreeMap::new(),
calls: Vec::new(),
}
}
fn file(&self, config_dir: Option<&Path>) -> PathBuf {
config_dir.unwrap_or(&self.home).join(".claude.json")
}
fn set_user(&mut self, config_dir: Option<&Path>, listing: String) {
self.user.insert(self.file(config_dir), listing);
}
fn set_shadow(&mut self, config_dir: Option<&Path>, scope: &str, listing: String) {
let key = match scope {
"project" => PathBuf::from(PROJECT_FILE),
_ => self.file(config_dir),
};
self.shadows.insert(key, (scope.to_string(), listing));
}
fn shadow_key(&self, file: &Path) -> Option<PathBuf> {
[file.to_path_buf(), PathBuf::from(PROJECT_FILE)]
.into_iter()
.find(|key| self.shadows.contains_key(key))
}
fn global_config(&self, cmd: &Command) -> PathBuf {
let dir = match cmd.get_envs().find(|(key, _)| *key == "CLAUDE_CONFIG_DIR") {
Some((_, Some(dir))) => Some(PathBuf::from(dir)),
Some((_, None)) => None,
None => self.shell_config_dir.clone(),
};
self.file(dir.as_deref())
}
}
impl Exec for Registry {
fn output(&mut self, cmd: Command) -> Result<Output> {
let argv = argv(&cmd);
self.calls.push(argv.clone());
let file = self.global_config(&cmd);
let flag = |name: &str| {
argv.iter()
.position(|a| a == name)
.map(|i| argv[i + 1].clone())
};
match argv[2].as_str() {
"get" => {
if cmd.get_current_dir().is_none()
&& let Some(key) = self.shadow_key(&file)
{
return output(0, &self.shadows[&key].1, "");
}
match self.user.get(&file) {
Some(listing) => output(0, listing, ""),
None => not_registered(),
}
}
"add" => {
assert_eq!(flag("--scope").as_deref(), Some("user"), "{argv:?}");
let env = flag("-e").unwrap();
let listing = get_output(USER_LABEL, argv.last().unwrap(), "", &env);
self.user.insert(file, listing);
output(0, "", "")
}
"remove" => {
let removed = match flag("--scope").as_deref() {
Some("user") => self.user.remove(&file).is_some(),
Some(scope) => {
let key = match scope {
"project" => PathBuf::from(PROJECT_FILE),
_ => file,
};
self.shadows
.remove(&key)
.is_some_and(|(held, _)| held == scope)
}
None => panic!("remove without a scope: {argv:?}"),
};
if removed {
output(0, "", "")
} else {
output(1, "", "No MCP server found with name: second-brain\n")
}
}
other => panic!("unexpected `claude mcp {other}`: {argv:?}"),
}
}
}
fn follow_mcp(ctx: &Context, registry: &mut Registry, fix: &str) {
let setup = setup_command(&ctx.sb_bin);
for piece in fix.split("; ").flat_map(|piece| piece.split(" && ")) {
if piece.starts_with("remove the second-brain entry from ") {
registry.shadows.clear();
continue;
}
let command = piece
.strip_prefix("run `")
.and_then(|rest| rest.strip_suffix("` in this directory"))
.unwrap_or(piece);
let (profile, rest) =
if let Some(rest) = command.strip_prefix("env -u CLAUDE_CONFIG_DIR ") {
(Profile::default_unset(&ctx.home), rest)
} else if let Some(rest) = command.strip_prefix("CLAUDE_CONFIG_DIR=") {
let (dir, rest) = rest.split_once(' ').unwrap();
(Profile::named(Path::new(dir)), rest)
} else {
(
Profile::current(&ctx.home, ctx.claude_config_dir.as_deref()),
command,
)
};
let program = claude_code::locate(ctx.search_path.as_deref(), &ctx.home, &[])
.expect("a claude to run the fix with");
let claude = Claude { program, profile };
if rest == setup {
claude_mcp::register(ctx.mcp_bin.as_ref().unwrap(), &claude, registry).unwrap();
continue;
}
let words: Vec<&str> = rest.split(' ').collect();
assert_eq!(words[0], claude.program.to_string_lossy(), "{piece}");
let mut cmd = claude.command();
cmd.args(&words[1..]);
let out = registry.output(cmd).unwrap();
assert!(out.status.success(), "{piece}");
}
}
fn mcp_in(ctx: &Context, registry: &mut Registry) -> Check {
let check = named(&checks(ctx, registry), "mcp");
for call in ®istry.calls {
assert_eq!(call[1], "mcp", "{call:?}");
}
check
}
#[test]
fn mcp_with_claude_only_in_local_bin_checks_with_that_binary() {
let home = Home::new();
let mut ctx = home.ctx();
ctx.search_path = Some(home.dir.path().join("empty-bin").into_os_string());
let mut registry = Registry::new(&ctx);
registry.set_user(None, ours(&home));
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Ok, "{check:?}");
assert!(!registry.calls.is_empty());
for call in ®istry.calls {
assert_eq!(call[0], home.claude_bin().to_string_lossy(), "{call:?}");
}
}
#[test]
fn mcp_with_claude_only_in_local_bin_unregistered_warns_and_setup_clears_it() {
let home = Home::new();
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains("not registered"), "{check:?}");
assert_eq!(fix(&check), setup_command(&ctx.sb_bin), "{check:?}");
follow_mcp(&ctx, &mut registry, &fix(&check));
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "{after:?}");
}
#[test]
fn mcp_without_claude_anywhere_skips_without_running_anything() {
let home = Home::new().without_claude();
let mut ctx = home.ctx();
ctx.search_path = Some(home.dir.path().join("empty-bin").into_os_string());
assert!(!ctx.claude_settings().parent().unwrap().exists());
let mut exec = FakeExec::new(|argv, _| panic!("ran {argv:?}"));
let check = named(&checks(&ctx, &mut exec), "mcp");
assert_eq!(check.status, Status::Skip, "{check:?}");
assert!(check.detail.contains("not installed"), "{check:?}");
assert_eq!(check.fix, None);
}
#[test]
fn mcp_without_claude_beside_its_config_dir_warns_and_putting_it_on_path_then_setup_clears_it()
{
let home = Home::new().without_claude();
let mut ctx = home.ctx();
let config_dir = ctx.claude_settings().parent().unwrap().to_path_buf();
fs::create_dir_all(&config_dir).unwrap();
let mut registry = Registry::new(&ctx);
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(
check.detail.contains(&*config_dir.to_string_lossy()),
"{check:?}"
);
assert!(registry.calls.is_empty());
let fix = fix(&check);
assert!(fix.contains("put `claude` on PATH"), "{fix}");
let bin = home.dir.path().join("opt/claude/bin");
install(&bin.join("claude"), 0o755);
ctx.search_path = Some(bin.clone().into_os_string());
follow_mcp(&ctx, &mut registry, every_backticked(&fix)[1]);
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "{after:?}");
for call in ®istry.calls {
assert_eq!(call[0], bin.join("claude").to_string_lossy(), "{call:?}");
}
}
#[test]
fn mcp_in_two_profiles_with_one_unregistered_warns_naming_it_and_its_fix_clears_it() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
home.write_profile(&work, &home.hooked());
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
registry.set_user(None, ours(&home));
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&*work.to_string_lossy()), "{check:?}");
assert_eq!(
fix(&check),
format!(
"CLAUDE_CONFIG_DIR={} {}",
work.display(),
setup_command(&ctx.sb_bin)
),
"{check:?}"
);
follow_mcp(&ctx, &mut registry, &fix(&check));
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "{after:?}");
assert!(after.detail.contains(&*work.to_string_lossy()), "{after:?}");
assert!(
after
.detail
.contains(&*ctx.home.join(".claude.json").to_string_lossy()),
"{after:?}"
);
}
#[test]
fn mcp_missing_from_the_default_profile_under_claude_config_dir_unsets_it_in_the_fix() {
let home = Home::new();
let elsewhere = tempfile::tempdir().unwrap();
let active = elsewhere.path().join("claude");
home.write_profile(&active, &home.hooked());
home.write_settings_json(&home.hooked());
let ctx = home.config_dir_ctx(&active);
let mut registry = Registry::new(&ctx);
registry.set_user(Some(&active), ours(&home));
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_eq!(
fix(&check),
format!("env -u CLAUDE_CONFIG_DIR {}", setup_command(&ctx.sb_bin)),
"{check:?}"
);
follow_mcp(&ctx, &mut registry, &fix(&check));
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "{after:?}");
assert!(registry.user.contains_key(&ctx.home.join(".claude.json")));
}
#[test]
fn mcp_finds_claude_installed_in_a_profiles_local_dir() {
let home = Home::new().without_claude();
let work = home.profile(".claude-work");
home.write_profile(&work, &json!({}));
let installed = work.join("local/claude");
install(&installed, 0o755);
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
registry.set_user(None, ours(&home));
registry.set_user(Some(&work), ours(&home));
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Ok, "{check:?}");
for call in ®istry.calls {
assert_eq!(call[0], installed.to_string_lossy(), "{call:?}");
}
}
#[test]
fn mcp_problems_in_any_profile_are_cleared_by_their_printed_fix() {
type Arrange = fn(&Home, &mut Registry, Option<&Path>);
let cases: [(&str, Status, Arrange); 9] = [
("unregistered", Status::Warn, |_, _, _| {}),
("stale binary", Status::Fail, |_, r, dir| {
let listing = get_output(USER_LABEL, "/old/place/second-brain-mcp", "", &api_env());
r.set_user(dir, listing);
}),
("extra args", Status::Fail, |h, r, dir| {
let bin = h.mcp_bin().to_string_lossy().into_owned();
r.set_user(
dir,
get_output(USER_LABEL, &bin, "--debug-wire", &api_env()),
);
}),
("other api", Status::Fail, |h, r, dir| {
let bin = h.mcp_bin().to_string_lossy().into_owned();
let env = "SECOND_BRAIN_API=http://127.0.0.1:9999";
r.set_user(dir, get_output(USER_LABEL, &bin, "", env));
}),
("unreadable", Status::Fail, |_, r, dir| {
r.set_user(dir, "second-brain: something sb cannot read\n".to_string());
}),
("local shadow", Status::Warn, |h, r, dir| {
r.set_user(dir, ours(h));
let shadow = get_output(LOCAL_LABEL, "/elsewhere/second-brain-mcp", "", &api_env());
r.set_shadow(dir, "local", shadow);
}),
("project shadow", Status::Warn, |h, r, dir| {
r.set_user(dir, ours(h));
let shadow =
get_output(PROJECT_LABEL, "/elsewhere/second-brain-mcp", "", &api_env());
r.set_shadow(dir, "project", shadow);
}),
("only local", Status::Warn, |h, r, dir| {
let bin = h.mcp_bin().to_string_lossy().into_owned();
r.set_shadow(dir, "local", get_output(LOCAL_LABEL, &bin, "", &api_env()));
}),
("stale behind a shadow", Status::Fail, |_, r, dir| {
let listing = get_output(USER_LABEL, "/old/place/second-brain-mcp", "", &api_env());
r.set_user(dir, listing);
let shadow = get_output(LOCAL_LABEL, "/elsewhere/second-brain-mcp", "", &api_env());
r.set_shadow(dir, "local", shadow);
}),
];
for in_work in [false, true] {
for (name, status, arrange) in cases {
let home = Home::new();
let work = home.profile(".claude-work");
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
if in_work {
home.write_profile(&work, &json!({}));
registry.set_user(None, ours(&home));
}
arrange(&home, &mut registry, in_work.then_some(work.as_path()));
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, status, "{name} in work {in_work}: {check:?}");
follow_mcp(&ctx, &mut registry, &fix(&check));
let after = mcp_in(&ctx, &mut registry);
assert_eq!(
after.status,
Status::Ok,
"{name} in work {in_work}: {after:?}"
);
}
}
}
#[test]
fn mcp_overridden_by_a_managed_entry_in_two_profiles_names_its_removal_once() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
home.write_profile(&work, &json!({}));
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
let label = "Enterprise config (managed by your organization)";
for dir in [None, Some(work.as_path())] {
registry.set_user(dir, ours(&home));
let managed = get_output(label, "/managed/second-brain-mcp", "", &api_env());
registry.set_shadow(dir, label, managed);
}
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_eq!(
fix(&check),
format!("remove the second-brain entry from {label}"),
"{check:?}"
);
follow_mcp(&ctx, &mut registry, &fix(&check));
assert_eq!(mcp_in(&ctx, &mut registry).status, Status::Ok);
}
#[test]
fn mcp_without_a_runnable_binary_fails_and_reinstalling_then_setup_clears_it() {
let breakages: [fn(&Home); 2] = [
|home| fs::remove_file(home.mcp_bin()).unwrap(),
|home| home.set_mcp_mode(0o644),
];
for (case, break_it) in breakages.into_iter().enumerate() {
let home = Home::new();
break_it(&home);
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Fail, "case {case}: {check:?}");
let fix = fix(&check);
assert!(fix.contains("cargo install second-brain-mcp"), "{fix}");
home.set_mcp_mode(0o755);
follow_mcp(&ctx, &mut registry, every_backticked(&fix).last().unwrap());
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "case {case}: {after:?}");
}
}
#[test]
fn mcp_without_claude_beside_another_profile_warns_and_its_fix_registers_every_profile() {
let home = Home::new().without_claude();
let work = home.profile(".claude-work");
home.write_profile(&work, &json!({}));
let mut ctx = home.ctx();
ctx.search_path = Some(home.dir.path().join("empty-bin").into_os_string());
let mut registry = Registry::new(&ctx);
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert!(check.detail.contains(&*work.to_string_lossy()), "{check:?}");
let fix = fix(&check);
let bin = home.dir.path().join("opt/claude/bin");
install(&bin.join("claude"), 0o755);
ctx.search_path = Some(bin.into_os_string());
follow_mcp(&ctx, &mut registry, every_backticked(&fix)[1]);
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "{after:?}");
}
#[test]
fn mcp_under_claude_config_dir_set_to_the_default_dir_checks_the_unset_default_too() {
let home = Home::new();
home.write_settings_json(&home.hooked());
let default = home.dir.path().join(".claude");
let ctx = home.config_dir_ctx(&default);
let mut registry = Registry::new(&ctx);
registry.set_user(Some(&default), ours(&home));
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
let unset_config = ctx.home.join(".claude.json");
assert!(
check.detail.contains(&*unset_config.to_string_lossy()),
"{check:?}"
);
assert_eq!(
fix(&check),
format!("env -u CLAUDE_CONFIG_DIR {}", setup_command(&ctx.sb_bin)),
"{check:?}"
);
follow_mcp(&ctx, &mut registry, &fix(&check));
let after = mcp_in(&ctx, &mut registry);
assert_eq!(after.status, Status::Ok, "{after:?}");
assert!(registry.user.contains_key(&unset_config));
assert!(registry.user.contains_key(&default.join(".claude.json")));
let hooks = hooks_in(&home, &ctx);
assert_eq!(hooks.status, Status::Ok, "{hooks:?}");
assert_eq!(
hooks
.detail
.matches(&*ctx.claude_settings().to_string_lossy())
.count(),
1,
"{hooks:?}"
);
}
#[test]
fn mcp_shadowed_by_a_project_entry_in_two_profiles_names_its_removal_once() {
let home = Home::new();
let work = home.profile(".claude-work");
home.write_settings_json(&home.hooked());
home.write_profile(&work, &json!({}));
let ctx = home.ctx();
let mut registry = Registry::new(&ctx);
registry.set_user(None, ours(&home));
registry.set_user(Some(&work), ours(&home));
let shadow = get_output(PROJECT_LABEL, "/elsewhere/second-brain-mcp", "", &api_env());
registry.set_shadow(None, "project", shadow);
let check = mcp_in(&ctx, &mut registry);
assert_eq!(check.status, Status::Warn, "{check:?}");
assert_eq!(
fix(&check).matches("--scope project").count(),
1,
"{check:?}"
);
assert!(!fix(&check).contains("CLAUDE_CONFIG_DIR"), "{check:?}");
follow_mcp(&ctx, &mut registry, &fix(&check));
assert_eq!(mcp_in(&ctx, &mut registry).status, Status::Ok);
}
#[test]
fn mcp_without_claude_or_its_own_binary_skips() {
let home = Home::new().without_claude();
fs::remove_file(home.mcp_bin()).unwrap();
let mut ctx = home.ctx();
ctx.mcp_bin = Err("second-brain-mcp was not found beside sb or on PATH".to_string());
for ctx in [home.ctx(), ctx] {
let check = named(&checks(&ctx, &mut Registry::new(&ctx)), "mcp");
assert_eq!(check.status, Status::Skip, "{check:?}");
}
}
}