use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::process::Command;
use super::report::{Check, Context};
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 claude_dir_exists(ctx: &Context) -> bool {
ctx.claude_settings.parent().is_some_and(Path::is_dir)
}
fn mcp(ctx: &Context, exec: &mut dyn daemon::Exec) -> Check {
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),
);
}
match claude_mcp::resolve(exec) {
Ok(Resolved { shadow, user }) => judge_mcp(ctx, mcp_bin, shadow.as_ref(), user),
Err(e) => mcp_unrunnable(ctx, &e),
}
}
fn mcp_unrunnable(ctx: &Context, err: &anyhow::Error) -> Check {
if daemon::is_not_found(err) && claude_dir_exists(ctx) {
return Check::fail(
"mcp",
format!(
"`claude` is not on PATH, so the {SERVER} registration cannot be checked \
and `sb setup` could not make it"
),
format!("put `claude` on PATH, then run `{}`", setup(ctx)),
);
}
if daemon::is_not_found(err) {
return Check::warn(
"mcp",
"Claude Code is not installed, so nothing is registered; \
other agents can still use the daemon",
format!("install Claude Code, then run `{}`", setup(ctx)),
);
}
Check::fail(
"mcp",
format!(
"`claude mcp get {SERVER}` could not run ({err:#}), so the registration is unknown"
),
"check that the `claude` CLI runs, for example with `claude --version`",
)
}
fn judge_mcp(ctx: &Context, mcp_bin: &Path, shadow: Option<&Entry>, user: Lookup) -> Check {
let entry = match user {
Lookup::Found(entry) if entry.scope != Scope::User => return shadowed(mcp_bin, &entry),
Lookup::Found(entry) => entry,
Lookup::Absent => {
return Check::fail(
"mcp",
format!(
"{SERVER} is not registered at user scope in Claude Code{}, \
so sessions have no memory tools",
shadow_note(shadow)
),
setup(ctx),
);
}
Lookup::Unreadable => {
return Check::fail(
"mcp",
format!(
"`claude mcp get {SERVER}` printed output sb cannot read, \
so the registration is unknown"
),
setup(ctx),
);
}
};
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)
),
setup(ctx),
);
}
match shadow {
Some(shadow) => shadowed(mcp_bin, 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, entry: &Entry) -> Check {
let runs = entry.command.as_deref().unwrap_or("an unknown command");
let mcp_bin = mcp_bin.display();
match &entry.scope {
Scope::Other(label) => Check::warn(
"mcp",
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}"
),
format!("remove the {SERVER} entry from {label}"),
),
scope => {
let scope = scope.name();
Check::warn(
"mcp",
format!(
"a {scope} scope entry named {SERVER} shadows the user-scope one in this \
directory, so Claude Code here runs {runs} instead of {mcp_bin}"
),
format!("run `claude mcp remove {SERVER} --scope {scope}` in this directory"),
)
}
}
}
fn hooks(ctx: &Context) -> Check {
let judged: Vec<Profile> = settings_files(ctx)
.into_iter()
.filter_map(|settings| judge_profile(ctx, settings))
.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 profile in &judged {
match &profile.verdict {
Verdict::Hooked => hooked.push(profile.settings.display().to_string()),
Verdict::Lacking(problem) => {
problems.push(problem.clone());
setups.push(setup_for(ctx, &profile.settings));
}
Verdict::Broken { detail, repair } => {
problems.push(detail.clone());
repairs.push(format!(
"{repair}, then run `{}`",
setup_for(ctx, &profile.settings)
));
}
}
}
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)
}
}
fn settings_files(ctx: &Context) -> Vec<PathBuf> {
let mut profiles: Vec<PathBuf> = std::fs::read_dir(&ctx.home)
.into_iter()
.flatten()
.flatten()
.filter(|entry| entry.file_name().to_string_lossy().starts_with(".claude-"))
.map(|entry| entry.path())
.filter(|dir| dir.join("projects").is_dir())
.map(|dir| dir.join(SETTINGS_FILE))
.collect();
profiles.sort();
let mut files = vec![ctx.claude_settings.clone()];
for file in std::iter::once(ctx.home.join(".claude").join(SETTINGS_FILE)).chain(profiles) {
if !files.contains(&file) {
files.push(file);
}
}
files
}
struct Profile {
settings: PathBuf,
verdict: Verdict,
}
enum Verdict {
Hooked,
Lacking(String),
Broken { detail: String, repair: String },
}
fn judge_profile(ctx: &Context, settings: PathBuf) -> Option<Profile> {
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(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, settings: &Path) -> String {
match settings.parent() {
Some(dir) if settings != ctx.claude_settings => format!(
"CLAUDE_CONFIG_DIR={} {}",
daemon::shell_word(&dir.to_string_lossy()),
setup(ctx)
),
_ => setup(ctx),
}
}
#[cfg(test)]
mod tests {
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::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);
home
}
fn set_mcp_mode(&self, mode: u32) {
let bin = self.mcp_bin();
fs::create_dir_all(bin.parent().unwrap()).unwrap();
fs::write(&bin, "#!/bin/sh\n").unwrap();
fs::set_permissions(&bin, fs::Permissions::from_mode(mode)).unwrap();
}
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_settings: home.join(".claude").join("settings.json"),
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_settings = claude_hooks::settings_path(Some(dir.as_os_str()), &ctx.home);
ctx
}
}
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 no_claude() -> Result<Output> {
Err(
anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::NotFound))
.context("failed to run claude mcp get second-brain"),
)
}
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_eq!(&call[..3], ["claude", "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 {
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_without_claude_or_its_config_dir_warns_and_says_to_install_it() {
let home = Home::new();
assert!(!home.ctx().claude_settings.parent().unwrap().exists());
let check = mcp(&home, &mut FakeExec::new(|_, _| no_claude()));
assert_check(
&check,
Status::Warn,
"Claude Code is not installed",
&super::setup(&home.ctx()),
);
assert!(fix(&check).contains("install Claude Code"), "{check:?}");
}
#[test]
fn mcp_without_claude_on_path_beside_its_config_dir_fails_saying_to_put_it_on_path() {
let home = Home::new();
let ctx = home.ctx();
fs::create_dir_all(ctx.claude_settings.parent().unwrap()).unwrap();
let check = mcp(&home, &mut FakeExec::new(|_, _| no_claude()));
assert_check(&check, Status::Fail, "not on PATH", &super::setup(&ctx));
assert!(check.detail.contains("registration"), "{check:?}");
assert!(fix(&check).contains("PATH"), "{check:?}");
assert!(!check.detail.contains("not installed"), "{check:?}");
assert!(!fix(&check).contains("install Claude Code"), "{check:?}");
}
#[test]
fn mcp_not_registered_fails_with_setup_as_the_fix() {
let home = Home::new();
let check = mcp(&home, &mut FakeExec::new(|_, _| not_registered()));
assert_check(&check, Status::Fail, "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_fails_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::Fail, "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",
"claude --version",
);
}
#[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_name_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:?}");
let default_dir = home.ctx().claude_settings.parent().unwrap().to_path_buf();
assert!(
fix(&check).contains(&*default_dir.to_string_lossy()),
"{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_eq!(check.status, Status::Fail, "{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:?}");
}
}