use std::path::Path;
use std::process::Command;
use anyhow::{Context, Result};
use crate::daemon::{self, Exec, render, run_checked};
pub const SERVER: &str = "second-brain";
#[derive(Debug, Clone, PartialEq)]
pub enum Scope {
User,
Local,
Project,
Other(String),
}
#[derive(Debug, PartialEq)]
pub struct Entry {
pub scope: Scope,
pub command: Option<String>,
pub args: Vec<String>,
pub env: Vec<(String, String)>,
}
#[derive(Debug, PartialEq)]
pub enum Outcome {
Unchanged { shadowed_by: Option<Scope> },
Registered { shadowed_by: Option<Scope> },
NoClaude { command: String },
}
#[derive(Debug, PartialEq)]
pub(crate) enum Lookup {
Absent,
Found(Entry),
Unreadable,
}
#[derive(Debug)]
pub(crate) struct Resolved {
pub(crate) shadow: Option<Entry>,
pub(crate) user: Lookup,
}
pub(crate) fn resolve(exec: &mut dyn Exec) -> Result<Resolved> {
Ok(match lookup(exec, get_command())? {
Lookup::Found(entry) if entry.scope != Scope::User => Resolved {
user: lookup_user_scope(exec).map_err(|e| anyhow::anyhow!("{e:#}"))?,
shadow: Some(entry),
},
user => Resolved { shadow: None, user },
})
}
impl Scope {
pub(crate) fn name(&self) -> &str {
match self {
Scope::User => "user",
Scope::Local => "local",
Scope::Project => "project",
Scope::Other(label) => label,
}
}
fn from_label(label: &str) -> Self {
if label.starts_with("User config") {
Scope::User
} else if label.starts_with("Local config") {
Scope::Local
} else if label.starts_with("Project config") {
Scope::Project
} else {
Scope::Other(label.to_string())
}
}
fn shadow_warning(&self) -> String {
match self {
Scope::Other(label) => format!(
"an entry named {SERVER} from {label} takes precedence over it in every directory"
),
scope => format!(
"a {} scope entry named {SERVER} shadows it in this directory",
scope.name()
),
}
}
}
impl Outcome {
pub fn report(&self) -> String {
let (head, shadowed_by) = match self {
Outcome::NoClaude { command } => {
return format!(
"`claude` is not on PATH; register the MCP server with:\n {command}"
);
}
Outcome::Unchanged { shadowed_by } => (
format!("{SERVER} already registered (user scope)"),
shadowed_by,
),
Outcome::Registered { shadowed_by } => {
(format!("registered {SERVER} (user scope)"), shadowed_by)
}
};
match shadowed_by {
None => head,
Some(scope) => format!(
"{head}\n warning: {}; setup left that entry alone",
scope.shadow_warning()
),
}
}
}
pub fn parse_get(stdout: &str) -> Option<Entry> {
let mut scope = None;
let mut command = None;
let mut args = Vec::new();
let mut env = Vec::new();
let mut in_env = false;
for line in stdout.lines() {
if in_env && let Some(pair) = line.strip_prefix(" ") {
if let Some((key, value)) = pair.split_once('=') {
env.push((key.to_string(), value.to_string()));
}
continue;
}
in_env = false;
let Some(field) = line.strip_prefix(" ") else {
continue;
};
if let Some(label) = field.strip_prefix("Scope:") {
scope = Some(Scope::from_label(label.trim()));
} else if let Some(value) = field.strip_prefix("Command:") {
command = Some(value.trim().to_string());
} else if let Some(value) = field.strip_prefix("Args:") {
args = value.split_whitespace().map(str::to_string).collect();
} else if field.trim_end() == "Environment:" {
in_env = true;
}
}
Some(Entry {
scope: scope?,
command,
args,
env,
})
}
fn api_env() -> String {
format!("SECOND_BRAIN_API=http://{}", daemon::DEFAULT_BIND)
}
fn claude(args: &[&str]) -> Command {
let mut cmd = Command::new("claude");
cmd.arg("mcp").args(args);
cmd
}
pub fn get_command() -> Command {
claude(&["get", SERVER])
}
pub fn remove_command() -> Command {
claude(&["remove", "--scope", "user", SERVER])
}
pub fn add_command(mcp_bin: &Path) -> Command {
let mut cmd = claude(&["add", "--scope", "user", SERVER, "-e"]);
cmd.arg(api_env()).arg("--").arg(mcp_bin);
cmd
}
impl Entry {
fn is_ours(&self, mcp_bin: &Path) -> bool {
self.scope == Scope::User && self.mismatches(mcp_bin).is_empty()
}
pub(crate) fn mismatches(&self, mcp_bin: &Path) -> Vec<String> {
let mut out = Vec::new();
let wanted = mcp_bin.to_string_lossy();
match self.command.as_deref() {
Some(command) if command == wanted => {}
Some(command) => out.push(format!("runs {command} instead of {wanted}")),
None => out.push(format!("has no command instead of {wanted}")),
}
if !self.args.is_empty() {
out.push(format!("passes the arguments {}", self.args.join(" ")));
}
let env: Vec<String> = self.env.iter().map(|(k, v)| format!("{k}={v}")).collect();
if env != [api_env()] {
let set = if env.is_empty() {
"no environment".to_string()
} else {
env.join(" ")
};
out.push(format!("sets {set} instead of {}", api_env()));
}
out
}
}
fn lookup(exec: &mut dyn Exec, cmd: Command) -> Result<Lookup> {
let out = exec.output(cmd)?;
if !out.status.success() {
return Ok(Lookup::Absent);
}
Ok(match parse_get(&String::from_utf8_lossy(&out.stdout)) {
Some(entry) => Lookup::Found(entry),
None => Lookup::Unreadable,
})
}
fn lookup_user_scope(exec: &mut dyn Exec) -> Result<Lookup> {
let dir = tempfile::tempdir().context("creating an empty directory for `claude mcp get`")?;
let mut cmd = get_command();
cmd.current_dir(dir.path());
lookup(exec, cmd)
}
fn by_hand(add: &str) -> String {
format!("register the MCP server with `{add}`")
}
pub fn register(mcp_bin: &Path, exec: &mut dyn Exec) -> Result<Outcome> {
let add = render(&add_command(mcp_bin));
let Resolved { shadow, user } = match resolve(exec) {
Ok(resolved) => resolved,
Err(e) if daemon::is_not_found(&e) => return Ok(Outcome::NoClaude { command: add }),
Err(e) => anyhow::bail!("{e:#}; {}", by_hand(&add)),
};
let shadowed_by = shadow.map(|entry| entry.scope);
let mut quiet_remove_failure = None;
let removed = match &user {
Lookup::Absent => false,
Lookup::Found(entry) if entry.is_ours(mcp_bin) => {
return Ok(Outcome::Unchanged { shadowed_by });
}
Lookup::Found(entry) if entry.scope == Scope::User => {
if let Err(detail) = run_checked(exec, remove_command()) {
anyhow::bail!(
"could not remove the old user-scope {SERVER} MCP entry ({detail}); \
remove it with `{}`, then rerun `sb setup`",
render(&remove_command())
);
}
true
}
Lookup::Found(_) | Lookup::Unreadable => match run_checked(exec, remove_command()) {
Ok(()) => true,
Err(detail) => {
quiet_remove_failure = Some(detail);
false
}
},
};
if let Err(detail) = run_checked(exec, add_command(mcp_bin)) {
if removed {
anyhow::bail!(
"registering the MCP server failed after the old user-scope {SERVER} entry \
was removed ({detail}); restore it with `{add}`"
);
}
if let Some(remove_detail) = quiet_remove_failure {
anyhow::bail!(
"registering the MCP server failed ({detail}), and `{}` failed first \
({remove_detail}); fix that, then {}",
render(&remove_command()),
by_hand(&add)
);
}
anyhow::bail!(
"registering the MCP server failed ({detail}); {}",
by_hand(&add)
);
}
Ok(Outcome::Registered { shadowed_by })
}
#[cfg(test)]
mod tests {
use std::os::unix::process::ExitStatusExt;
use std::path::PathBuf;
use std::process::{ExitStatus, Output};
use super::*;
const BIN: &str = "/home/u/.cargo/bin/second-brain-mcp";
const API: &str = "http://127.0.0.1:7200";
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()
}
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(),
})
}
type Reply = Box<dyn FnMut(&[String], Option<&Path>) -> Result<Output>>;
struct FakeExec {
calls: Vec<Vec<String>>,
dirs: Vec<Option<PathBuf>>,
reply: Reply,
}
impl FakeExec {
fn new(reply: impl FnMut(&[String], Option<&Path>) -> Result<Output> + 'static) -> Self {
Self {
calls: Vec::new(),
dirs: Vec::new(),
reply: Box::new(reply),
}
}
fn subcommands(&self) -> Vec<String> {
self.calls.iter().map(|c| c[2].clone()).collect()
}
}
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);
if let Some(dir) = &dir {
assert!(dir.is_dir(), "lookup dir {} must exist", dir.display());
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0);
}
let out = (self.reply)(&argv, dir.as_deref());
self.calls.push(argv);
self.dirs.push(dir);
out
}
}
fn get_output(scope_label: &str, command: &str, env: &str) -> String {
format!(
"second-brain:\n Scope: {scope_label}\n Status: \u{2713} Connected\n Type: stdio\n \
Command: {command}\n Args: \n Environment:\n {env}\n\n\
To remove this server, run: claude mcp remove \"second-brain\" -s user\n"
)
}
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)";
const ENTERPRISE_LABEL: &str = "Enterprise config (managed by your organization)";
fn ours() -> String {
get_output(USER_LABEL, BIN, &format!("SECOND_BRAIN_API={API}"))
}
fn stale() -> String {
get_output(USER_LABEL, "/old/bin", &format!("SECOND_BRAIN_API={API}"))
}
fn add_line() -> String {
format!("claude mcp add --scope user second-brain -e SECOND_BRAIN_API={API} -- {BIN}")
}
fn not_found() -> 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 register_with(exec: &mut FakeExec) -> Result<Outcome> {
register(Path::new(BIN), exec)
}
#[test]
fn commands_register_at_user_scope_with_the_api_env() {
assert_eq!(argv(&get_command()), ["claude", "mcp", "get", SERVER]);
assert_eq!(
argv(&remove_command()),
["claude", "mcp", "remove", "--scope", "user", SERVER]
);
assert_eq!(
argv(&add_command(Path::new(BIN))),
[
"claude",
"mcp",
"add",
"--scope",
"user",
SERVER,
"-e",
"SECOND_BRAIN_API=http://127.0.0.1:7200",
"--",
BIN,
]
);
}
#[test]
fn parses_scope_command_args_and_env_from_get() {
let entry = parse_get(&ours()).unwrap();
assert_eq!(
entry,
Entry {
scope: Scope::User,
command: Some(BIN.to_string()),
args: vec![],
env: vec![("SECOND_BRAIN_API".to_string(), API.to_string())],
}
);
}
#[test]
fn parses_every_scope_label() {
let scope = |label: &str| parse_get(&get_output(label, BIN, "A=b")).unwrap().scope;
assert_eq!(scope(USER_LABEL), Scope::User);
assert_eq!(scope(LOCAL_LABEL), Scope::Local);
assert_eq!(scope(PROJECT_LABEL), Scope::Project);
assert_eq!(
scope(ENTERPRISE_LABEL),
Scope::Other(ENTERPRISE_LABEL.to_string())
);
}
#[test]
fn parses_args_and_several_env_lines() {
let out = "second-brain:\n Scope: User config (available in all your projects)\n \
Status: \u{2717} Failed to connect\n Type: stdio\n Command: /bin/x\n \
Args: --flag value\n Environment:\n A=1\n B=two=2\n";
let entry = parse_get(out).unwrap();
assert_eq!(entry.args, ["--flag", "value"]);
assert_eq!(
entry.env,
[
("A".to_string(), "1".to_string()),
("B".to_string(), "two=2".to_string())
]
);
}
#[test]
fn output_without_a_scope_line_is_not_an_entry() {
assert_eq!(parse_get(""), None);
assert_eq!(
parse_get("No MCP server found with name: second-brain"),
None
);
}
#[test]
fn fresh_install_only_adds() {
let mut exec = FakeExec::new(|argv, _| match argv[2].as_str() {
"get" => not_found(),
"add" => output(0, "Added stdio MCP server second-brain\n", ""),
other => panic!("unexpected {other}"),
});
let outcome = register_with(&mut exec).unwrap();
assert_eq!(outcome, Outcome::Registered { shadowed_by: None });
assert_eq!(exec.subcommands(), ["get", "add"]);
assert_eq!(exec.calls[1], argv(&add_command(Path::new(BIN))));
assert_eq!(exec.dirs[0], None);
}
#[test]
fn matching_user_entry_changes_nothing() {
let mut exec = FakeExec::new(|_, _| output(0, &ours(), ""));
let outcome = register_with(&mut exec).unwrap();
assert_eq!(outcome, Outcome::Unchanged { shadowed_by: None });
assert_eq!(exec.subcommands(), ["get"]);
}
#[test]
fn stale_user_entry_is_replaced() {
let stale = [
stale(),
get_output(USER_LABEL, BIN, "SECOND_BRAIN_API=http://127.0.0.1:9999"),
get_output(
USER_LABEL,
BIN,
&format!("SECOND_BRAIN_API={API}\n EXTRA=1"),
),
];
for listing in stale {
let mut exec = FakeExec::new(move |argv, _| match argv[2].as_str() {
"get" => output(0, &listing, ""),
_ => output(0, "", ""),
});
let outcome = register_with(&mut exec).unwrap();
assert_eq!(outcome, Outcome::Registered { shadowed_by: None });
assert_eq!(exec.subcommands(), ["get", "remove", "add"]);
assert_eq!(exec.calls[1], argv(&remove_command()));
}
}
#[test]
fn failed_remove_of_a_known_user_entry_is_an_error() {
let mut exec = FakeExec::new(|argv, _| match argv[2].as_str() {
"get" => output(0, &stale(), ""),
_ => output(1, "", "config file is read-only\n"),
});
let err = register_with(&mut exec).unwrap_err().to_string();
assert!(err.contains("config file is read-only"), "{err}");
assert_eq!(exec.subcommands(), ["get", "remove"]);
}
#[test]
fn add_failing_after_remove_prints_the_restore_command() {
let mut exec = FakeExec::new(|argv, _| match argv[2].as_str() {
"get" => output(0, &stale(), ""),
"remove" => output(0, "", ""),
_ => output(1, "", "disk full\n"),
});
let err = register_with(&mut exec).unwrap_err().to_string();
assert!(
err.contains(&format!("restore it with `{}`", add_line())),
"{err}"
);
assert!(err.contains("removed"), "{err}");
assert!(err.contains("disk full"), "{err}");
}
#[test]
fn add_failing_without_a_removal_prints_the_command() {
let mut exec = FakeExec::new(|argv, _| match argv[2].as_str() {
"get" => not_found(),
_ => output(1, "", "boom\n"),
});
let err = register_with(&mut exec).unwrap_err().to_string();
assert!(
err.contains(&format!("register the MCP server with `{}`", add_line())),
"{err}"
);
assert!(!err.contains("removed"), "{err}");
assert!(err.contains("boom"), "{err}");
assert_eq!(exec.subcommands(), ["get", "add"]);
}
fn shadowed(label: &'static str, user_view: fn() -> Result<Output>) -> FakeExec {
let shadow = get_output(label, BIN, &format!("SECOND_BRAIN_API={API}"));
FakeExec::new(move |argv, dir| match (argv[2].as_str(), dir) {
("get", None) => output(0, &shadow, ""),
("get", Some(_)) => user_view(),
_ => output(0, "", ""),
})
}
#[test]
fn shadowing_entry_is_left_alone_and_named() {
for (label, scope, name) in [
(LOCAL_LABEL, Scope::Local, "local"),
(PROJECT_LABEL, Scope::Project, "project"),
] {
let mut exec = shadowed(label, not_found);
let outcome = register_with(&mut exec).unwrap();
assert_eq!(
outcome,
Outcome::Registered {
shadowed_by: Some(scope)
}
);
assert_eq!(exec.subcommands(), ["get", "get", "add"]);
assert_eq!(exec.dirs[0], None);
assert!(exec.dirs[1].is_some());
let report = outcome.report();
assert!(
report.contains(&format!("a {name} scope entry")),
"{report}"
);
assert!(report.contains("shadows"), "{report}");
}
}
#[test]
fn shadowed_matching_user_entry_changes_nothing() {
let mut exec = shadowed(LOCAL_LABEL, || output(0, &ours(), ""));
let outcome = register_with(&mut exec).unwrap();
assert_eq!(
outcome,
Outcome::Unchanged {
shadowed_by: Some(Scope::Local)
}
);
assert_eq!(exec.subcommands(), ["get", "get"]);
let report = outcome.report();
assert!(report.contains("already registered"), "{report}");
assert!(report.contains("shadows"), "{report}");
}
#[test]
fn shadowed_stale_user_entry_is_replaced() {
let mut exec = shadowed(PROJECT_LABEL, || output(0, &stale(), ""));
let outcome = register_with(&mut exec).unwrap();
assert_eq!(
outcome,
Outcome::Registered {
shadowed_by: Some(Scope::Project)
}
);
assert_eq!(exec.subcommands(), ["get", "get", "remove", "add"]);
}
#[test]
fn hidden_user_view_names_a_failed_remove_when_add_fails() {
let managed = get_output(ENTERPRISE_LABEL, BIN, &format!("SECOND_BRAIN_API={API}"));
let mut exec = FakeExec::new(move |argv, _| match argv[2].as_str() {
"get" => output(0, &managed, ""),
"remove" => output(1, "", "config file is read-only\n"),
_ => output(1, "", "already exists in user config\n"),
});
let err = register_with(&mut exec).unwrap_err().to_string();
assert_eq!(exec.subcommands(), ["get", "get", "remove", "add"]);
assert!(err.contains("already exists in user config"), "{err}");
assert!(err.contains("config file is read-only"), "{err}");
assert!(err.contains(&render(&remove_command())), "{err}");
}
#[test]
fn add_failing_after_a_quiet_remove_prints_the_restore_command() {
let mut exec = FakeExec::new(|argv, _| match argv[2].as_str() {
"get" => output(0, "something new\n", ""),
"remove" => output(0, "", ""),
_ => output(1, "", "disk full\n"),
});
let err = register_with(&mut exec).unwrap_err().to_string();
assert!(
err.contains(&format!("restore it with `{}`", add_line())),
"{err}"
);
}
#[test]
fn failed_empty_dir_lookup_prints_the_command() {
let shadow = get_output(LOCAL_LABEL, BIN, &format!("SECOND_BRAIN_API={API}"));
let mut exec = FakeExec::new(move |_, dir| match dir {
None => output(0, &shadow, ""),
Some(_) => Err(anyhow::anyhow!("claude crashed")),
});
let err = register_with(&mut exec).unwrap_err().to_string();
assert!(err.contains("claude crashed"), "{err}");
assert!(
err.contains(&format!("register the MCP server with `{}`", add_line())),
"{err}"
);
assert_eq!(exec.subcommands(), ["get", "get"]);
}
#[test]
fn unreadable_user_view_removes_quietly_then_adds() {
let mut exec = FakeExec::new(|argv, _| match argv[2].as_str() {
"get" => output(0, "something new\n", ""),
"remove" => output(1, "", "No user-scoped MCP server found\n"),
_ => output(0, "", ""),
});
let outcome = register_with(&mut exec).unwrap();
assert_eq!(outcome, Outcome::Registered { shadowed_by: None });
assert_eq!(exec.subcommands(), ["get", "remove", "add"]);
}
#[test]
fn other_scope_report_names_its_source() {
let report = Outcome::Registered {
shadowed_by: Some(Scope::Other(ENTERPRISE_LABEL.to_string())),
}
.report();
assert!(
report.contains(&format!(
"an entry named second-brain from {ENTERPRISE_LABEL} takes precedence over it \
in every directory"
)),
"{report}"
);
assert!(!report.contains("in this directory"), "{report}");
}
#[test]
fn missing_claude_prints_the_exact_command() {
let mut exec = FakeExec::new(|_, _| no_claude());
let outcome = register_with(&mut exec).unwrap();
assert_eq!(
outcome,
Outcome::NoClaude {
command: add_line()
}
);
assert_eq!(exec.subcommands(), ["get"]);
let report = outcome.report();
assert!(report.contains("`claude` is not on PATH"), "{report}");
assert!(report.contains(&add_line()), "{report}");
}
#[test]
fn other_spawn_failures_are_errors_with_the_command() {
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 err = format!("{:#}", register_with(&mut exec).unwrap_err());
assert!(err.contains(&add_line()), "{err}");
}
#[test]
fn scope_names_are_the_ones_claude_mcp_remove_takes() {
assert_eq!(Scope::User.name(), "user");
assert_eq!(Scope::Local.name(), "local");
assert_eq!(Scope::Project.name(), "project");
assert_eq!(
Scope::Other(ENTERPRISE_LABEL.to_string()).name(),
ENTERPRISE_LABEL
);
}
#[test]
fn resolve_takes_a_winning_user_entry_without_a_second_lookup() {
let mut exec = FakeExec::new(|_, _| output(0, &ours(), ""));
let resolved = resolve(&mut exec).unwrap();
assert_eq!(resolved.shadow, None);
assert_eq!(resolved.user, Lookup::Found(parse_get(&ours()).unwrap()));
assert_eq!(exec.subcommands(), ["get"]);
assert_eq!(exec.dirs, [None::<PathBuf>]);
}
#[test]
fn resolve_reads_the_user_view_from_an_empty_dir_when_another_scope_wins() {
for (label, scope) in [
(LOCAL_LABEL, Scope::Local),
(PROJECT_LABEL, Scope::Project),
(ENTERPRISE_LABEL, Scope::Other(ENTERPRISE_LABEL.to_string())),
] {
let mut exec = shadowed(label, || output(0, &stale(), ""));
let resolved = resolve(&mut exec).unwrap();
assert_eq!(
resolved.shadow,
parse_get(&get_output(label, BIN, &format!("SECOND_BRAIN_API={API}"))),
"{label}"
);
assert_eq!(resolved.shadow.map(|e| e.scope), Some(scope));
assert_eq!(resolved.user, Lookup::Found(parse_get(&stale()).unwrap()));
assert_eq!(exec.subcommands(), ["get", "get"]);
assert_eq!(exec.dirs[0], None);
assert!(exec.dirs[1].is_some());
}
}
#[test]
fn resolve_passes_an_absent_or_unreadable_view_through_after_one_lookup() {
type Listing = fn() -> Result<Output>;
let cases: [(Listing, Lookup); 2] = [
(not_found, Lookup::Absent),
(|| output(0, "something new\n", ""), Lookup::Unreadable),
];
for (listing, expected) in cases {
let mut exec = FakeExec::new(move |_, _| listing());
let resolved = resolve(&mut exec).unwrap();
assert_eq!(resolved.shadow, None);
assert_eq!(resolved.user, expected);
assert_eq!(exec.subcommands(), ["get"]);
}
}
#[test]
fn resolve_returns_the_error_of_either_lookup() {
let mut exec = FakeExec::new(|_, _| no_claude());
let err = resolve(&mut exec).unwrap_err();
assert!(daemon::is_not_found(&err), "{err:#}");
let shadow = get_output(LOCAL_LABEL, BIN, &format!("SECOND_BRAIN_API={API}"));
let mut exec = FakeExec::new(move |_, dir| match dir {
None => output(0, &shadow, ""),
Some(_) => Err(anyhow::anyhow!("claude crashed")),
});
let err = resolve(&mut exec).unwrap_err();
assert!(format!("{err:#}").contains("claude crashed"), "{err:#}");
assert_eq!(exec.subcommands(), ["get", "get"]);
}
#[test]
fn a_missing_file_in_the_user_scope_lookup_does_not_read_as_no_claude() {
let shadow = get_output(LOCAL_LABEL, BIN, &format!("SECOND_BRAIN_API={API}"));
let mut exec = FakeExec::new(move |_, dir| match dir {
None => output(0, &shadow, ""),
Some(_) => no_claude(),
});
let err = resolve(&mut exec).unwrap_err();
assert!(!daemon::is_not_found(&err), "{err:#}");
}
#[test]
fn reports_name_the_user_scope() {
let unchanged = Outcome::Unchanged { shadowed_by: None }.report();
assert!(unchanged.contains("already registered"), "{unchanged}");
assert!(!unchanged.contains("shadows"), "{unchanged}");
assert!(
Outcome::Registered { shadowed_by: None }
.report()
.contains("user scope")
);
}
}