use std::io::IsTerminal;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use second_brain_sync::pairing::JOIN_PENDING_FILE;
use zeroize::{Zeroize, Zeroizing};
use super::ingest::not_run;
use super::pair;
use super::recovery::RecoveryState;
use crate::{api, bins, claude_code, claude_hooks, claude_mcp, daemon, launchd};
pub(crate) fn cmd_setup() -> Result<()> {
let os = daemon::Os::current();
let caller = daemon::Caller::current();
daemon::check_setup_caller(os, caller.uid)?;
let account = match os {
daemon::Os::MacOs => Some(launchd::Account::from_uid(caller.uid)?),
daemon::Os::Linux => None,
};
let home = match &account {
Some(account) => account.home.clone(),
None => PathBuf::from(std::env::var("HOME").context("HOME not set")?),
};
let unit_active =
os == daemon::Os::Linux && daemon::user_unit_active(&caller, &mut daemon::SystemExec);
daemon::check_bind_free(
daemon::DEFAULT_BIND,
|| match os {
daemon::Os::Linux => Ok(unit_active),
daemon::Os::MacOs => launchd::is_loaded(
&launchd::Daemon::new(launchd::DEFAULT_LABEL),
&mut launchd::System,
),
},
|port| daemon::port_holder(port, &mut daemon::SystemExec),
)?;
eprintln!("=== second-brain setup ===\n");
let db_dir = home.join(".second-brain");
std::fs::create_dir_all(&db_dir)?;
eprintln!("[1/6] data dir: {}", db_dir.display());
let (api_bin, mcp_bin, cli_bin) = bins::locate_binaries()?;
eprintln!("[2/6] binaries:");
eprintln!(" api: {}", api_bin.display());
eprintln!(" mcp: {}", mcp_bin.display());
eprintln!(" cli: {}", cli_bin.display());
let db_path = db_dir.join("brain.db");
let interactive = std::io::stdin().is_terminal() && std::io::stderr().is_terminal();
let asked = if ask_before_start(fresh_install(&db_path), interactive) {
let choice = ask_identity()?;
record_identity_choice(&db_dir, &choice)?;
Some(choice)
} else {
None
};
let record = match &account {
Some(account) => install_launchd(account, &api_bin, &db_path, &db_dir, &caller)?,
None => install_systemd(&home, &api_bin, &db_path, unit_active, &caller)?,
};
let config_dir = claude_code::config_dir(std::env::var_os("CLAUDE_CONFIG_DIR"));
let settings = claude_hooks::settings_path(config_dir.as_deref().map(Path::as_os_str), &home);
let claude = claude_code::Claude::current(
std::env::var_os("PATH").as_deref(),
&home,
config_dir.as_deref(),
);
let mcp = claude_mcp::register(&mcp_bin, &claude, &mut daemon::SystemExec)?;
eprintln!("[4/6] claude code MCP: {}", mcp.report());
match claude_hooks::register(&settings, &cli_bin) {
Ok(hooks) => eprintln!("[5/6] claude code hooks: {}", hooks.report()),
Err(e) => eprintln!("[5/6] claude code hooks: warning: {e:#}"),
}
eprintln!("[6/6] running first ingest...");
if !daemon_ready()? {
eprintln!(
" the daemon is still starting after {}s; check it with `sb status` and run `sb ingest` once it is up",
READY_LIMIT.as_secs()
);
if asked == Some(IdentityChoice::Join) {
eprintln!("{JOIN_WAITING}");
}
return Ok(());
}
offer_pairing(asked.as_ref(), interactive);
let client = api::client(std::time::Duration::from_secs(600))?;
match client
.post(format!("{}/v1/ingest", api::base_url()))
.json(&serde_json::json!({}))
.send()
{
Ok(resp) if resp.status().is_success() => {
let body: serde_json::Value = resp.json().unwrap_or_default();
if let Some(held) = not_run(&body) {
eprintln!(" {held}");
} else {
eprintln!(
" ingested: {} memories, {} conversations",
body["new_memories"], body["new_conversations"]
);
}
}
Ok(resp) => eprintln!(" ingest warning: {}", resp.status()),
Err(e) => eprintln!(" ingest warning: {e}"),
}
if let Err(e) = crate::commands::recovery::offer_once() {
eprintln!(" recovery phrase warning: {e:#}");
}
eprintln!("\n=== setup complete ===");
eprintln!("daemon: {}", daemon::status_hint(&record));
eprintln!("recall: sb recall \"your query\"");
eprintln!("status: sb status");
Ok(())
}
fn install_systemd(
home: &Path,
api_bin: &Path,
db_path: &Path,
unit_active: bool,
caller: &daemon::Caller,
) -> Result<daemon::ServiceRecord> {
let systemd_dir = daemon::user_unit_dir(home);
std::fs::create_dir_all(&systemd_dir)?;
let service_path = systemd_dir.join(daemon::DEFAULT_UNIT);
let service_content = daemon::unit_file(api_bin, db_path);
std::fs::write(&service_path, &service_content)?;
let record = daemon::ServiceRecord::user_default();
daemon::save_record(&daemon::record_path()?, &record)?;
eprintln!("[3/6] systemd service: {}", service_path.display());
let mut exec = daemon::SystemExec;
match daemon::start_user_unit(unit_active, caller, &mut exec) {
daemon::Start::Started => eprintln!(" enabled and started"),
daemon::Start::Restarted => eprintln!(" enabled and restarted on the new binary"),
daemon::Start::Failed { command, detail } => eprintln!(
" warning: `{command}` failed ({detail}); start the daemon manually: {}",
api_bin.display()
),
}
let user = launchd::Account::from_uid(caller.uid)
.map(|account| account.name)
.unwrap_or_else(|_| caller.uid.to_string());
match daemon::ensure_linger(&user, &mut exec) {
daemon::Linger::AlreadyOn => {}
daemon::Linger::Enabled => {
eprintln!(" linger enabled, so the daemon keeps running after logout")
}
daemon::Linger::Failed(warning) => eprintln!(" warning: {warning}"),
}
Ok(record)
}
const READY_LIMIT: std::time::Duration = std::time::Duration::from_secs(300);
const READY_PROGRESS: std::time::Duration = std::time::Duration::from_secs(15);
const READY_POLL: std::time::Duration = std::time::Duration::from_millis(500);
#[derive(Debug, PartialEq, Eq)]
enum Readiness {
Ready,
Starting(String),
Down,
}
fn readiness(answered: Option<(u16, serde_json::Value)>) -> Readiness {
match answered {
Some((200, health)) => match api::starting_reason(&health) {
Some(reason) => Readiness::Starting(reason.to_string()),
None => Readiness::Ready,
},
_ => Readiness::Down,
}
}
pub(crate) fn daemon_ready() -> Result<bool> {
let api = api::base_url();
let probe = api::open_client(std::time::Duration::from_secs(2))?;
let started = std::time::Instant::now();
Ok(wait_for_daemon(
|| started.elapsed(),
|| {
readiness(
probe
.get(format!("{api}/health"))
.send()
.ok()
.map(|r| (r.status().as_u16(), r.json().unwrap_or_default())),
)
},
std::thread::sleep,
|waited, reason| match reason {
Some(reason) => eprintln!(
" waiting for the daemon to finish starting ({}s): {reason}",
waited.as_secs()
),
None => eprintln!(
" waiting for the daemon to finish starting ({}s)",
waited.as_secs()
),
},
))
}
fn wait_for_daemon(
mut elapsed: impl FnMut() -> std::time::Duration,
mut probe: impl FnMut() -> Readiness,
mut pause: impl FnMut(std::time::Duration),
mut progress: impl FnMut(std::time::Duration, Option<&str>),
) -> bool {
let mut next_report = READY_PROGRESS;
loop {
let reason = match probe() {
Readiness::Ready => return true,
Readiness::Starting(reason) => Some(reason),
Readiness::Down => None,
};
let waited = elapsed();
if waited >= READY_LIMIT {
return false;
}
if waited >= next_report {
progress(next_report, reason.as_deref());
next_report += READY_PROGRESS;
}
pause(READY_POLL);
}
}
fn install_launchd(
account: &launchd::Account,
api_bin: &Path,
db_path: &Path,
data_dir: &Path,
caller: &daemon::Caller,
) -> Result<daemon::ServiceRecord> {
let target = launchd::Daemon::new(launchd::DEFAULT_LABEL);
let plist = launchd::render_plist(&launchd::PlistSpec {
label: &target.label,
program: api_bin,
account,
db: db_path,
bind: daemon::DEFAULT_BIND,
})?;
eprintln!(
"[3/6] launchd daemon: {} (sudo asks for your password)",
target.plist.display()
);
launchd::install(
&launchd::Install {
daemon: &target,
plist: &plist,
staged: &data_dir.join(format!("{}.plist", target.label)),
backup: &data_dir.join(format!("{}.plist.previous", target.label)),
log_dir: &account.log_dir(),
record_path: &daemon::record_path()?,
},
caller,
&mut launchd::System,
)?;
eprintln!(" loaded, logs in {}", account.log_dir().display());
Ok(target.record())
}
const PAIR_HINT: &str = " to join a sync identity another device already runs instead of starting a new one, \
run `sb pair <code> --host <host>` with the code `sb pair` shows there";
const JOIN_WAITING: &str = " this device waits to join a sync identity, and nothing is ingested until it does: \
join with `sb pair <code> --host <host>` and the code `sb pair` shows on the other device, \
or run `sb pair --stop-waiting` to start alone";
fn offer_pairing(asked: Option<&IdentityChoice>, interactive: bool) {
let has_identity = if asked == Some(&IdentityChoice::New) {
None
} else {
match has_sync_identity() {
Ok(has) => Some(has),
Err(e) => {
eprintln!(" pairing: cannot tell whether this device has a sync identity: {e:#}");
None
}
}
};
match offer_after_ready(asked, has_identity, interactive) {
IdentityOffer::Skip => {}
IdentityOffer::Hint => eprintln!("{PAIR_HINT}"),
IdentityOffer::Join => {
if let Err(e) = join_from_prompt() {
eprintln!(" pairing failed: {e:#}\n{JOIN_WAITING}");
}
}
IdentityOffer::Ask => {
if let Err(e) = ask_and_join() {
eprintln!(
" pairing: {e:#}\n join later with `sb pair <code> --host <host>`, or run \
`sb pair --stop-waiting` if this device waits to join one"
);
}
}
}
}
fn has_sync_identity() -> Result<bool> {
let client = api::client(std::time::Duration::from_secs(30))?;
let state: RecoveryState = api::daemon_ok(
client
.get(format!("{}/v1/keys/recovery", api::base_url()))
.send()
.context("asking the daemon for its sync identity")?,
)?
.json()
.context("reading the daemon's sync identity")?;
Ok(state.identity.is_some())
}
fn ask_and_join() -> Result<()> {
match ask_identity()? {
IdentityChoice::New => start_alone(),
IdentityChoice::Join => join_from_prompt(),
}
}
fn start_alone() -> Result<()> {
if pair::stop_waiting()? {
eprintln!(" this device no longer waits to join an identity");
}
Ok(())
}
fn ask_identity() -> Result<IdentityChoice> {
eprint!(
" does this device start a new sync identity, or join one your other device runs?\n \
1) start a new identity (`sb pair` here later adds devices)\n \
2) join an existing device\n choice [1]: "
);
loop {
let answer = read_answer()?;
match identity_choice(&answer) {
Some(choice) => return Ok(choice),
None => eprint!(" answer 1 or 2: "),
}
}
}
fn join_from_prompt() -> Result<()> {
eprint!(" the code `sb pair` shows on the other device: ");
let code = Zeroizing::new(read_answer()?);
eprint!(" that device's host, as shown after --host (Enter for none): ");
let host = read_answer()?;
let mut args = join_args(&code, &host).context("no code entered")?;
let joined = pair::cmd_pair(&args);
args.zeroize();
joined
}
fn read_answer() -> Result<String> {
let mut answer = String::new();
std::io::stdin()
.read_line(&mut answer)
.context("reading the answer")?;
Ok(answer)
}
#[derive(Debug, PartialEq, Eq)]
enum IdentityOffer {
Skip,
Ask,
Hint,
Join,
}
fn fresh_install(db_path: &Path) -> bool {
matches!(db_path.try_exists(), Ok(false))
}
fn ask_before_start(fresh: bool, interactive: bool) -> bool {
fresh && interactive
}
fn record_identity_choice(db_dir: &Path, choice: &IdentityChoice) -> Result<()> {
let marker = db_dir.join(JOIN_PENDING_FILE);
match choice {
IdentityChoice::Join => {
std::fs::write(&marker, "").with_context(|| format!("writing {}", marker.display()))
}
IdentityChoice::New => match std::fs::remove_file(&marker) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => {
Err(e).with_context(|| format!("removing {}", marker.display()))
}
_ => Ok(()),
},
}
}
fn offer_after_ready(
asked: Option<&IdentityChoice>,
has_identity: Option<bool>,
interactive: bool,
) -> IdentityOffer {
match (asked, has_identity) {
(None, _) => identity_offer(has_identity, interactive),
(Some(IdentityChoice::Join), Some(true)) | (Some(IdentityChoice::New), _) => {
IdentityOffer::Skip
}
(Some(IdentityChoice::Join), _) => IdentityOffer::Join,
}
}
fn identity_offer(has_identity: Option<bool>, interactive: bool) -> IdentityOffer {
match (has_identity, interactive) {
(Some(true), _) => IdentityOffer::Skip,
(_, true) => IdentityOffer::Ask,
(_, false) => IdentityOffer::Hint,
}
}
#[derive(Debug, PartialEq, Eq)]
enum IdentityChoice {
New,
Join,
}
fn identity_choice(answer: &str) -> Option<IdentityChoice> {
match answer.trim().to_ascii_lowercase().as_str() {
"" | "1" | "n" | "new" => Some(IdentityChoice::New),
"2" | "j" | "join" => Some(IdentityChoice::Join),
_ => None,
}
}
fn join_args(code: &str, host: &str) -> Option<Vec<String>> {
let code = code.trim();
if code.is_empty() {
return None;
}
let mut args = vec![code.to_string()];
let host = host.trim();
if !host.is_empty() {
args.extend(["--host".to_string(), host.to_string()]);
}
Some(args)
}
#[cfg(test)]
mod wait_tests {
use std::cell::{Cell, RefCell};
use std::time::Duration;
use super::*;
fn simulate(
mut probe: impl FnMut(Duration) -> Readiness,
) -> (bool, Vec<(Duration, Option<String>)>, Duration) {
let clock = Cell::new(Duration::ZERO);
let reports = RefCell::new(Vec::new());
let ready = wait_for_daemon(
|| clock.get(),
|| probe(clock.get()),
|d| clock.set(clock.get() + d),
|at, reason| reports.borrow_mut().push((at, reason.map(str::to_string))),
);
(ready, reports.into_inner(), clock.get())
}
fn ready_at(at: Duration) -> impl FnMut(Duration) -> Readiness {
move |now| {
if now >= at {
Readiness::Ready
} else {
Readiness::Down
}
}
}
#[test]
fn a_cold_start_is_waited_out_for_five_minutes_with_progress_every_fifteen_seconds() {
let (ready, reports, stopped) = simulate(|_| Readiness::Down);
assert!(!ready);
assert!(stopped >= Duration::from_secs(300), "{stopped:?}");
assert!(stopped < Duration::from_secs(301), "{stopped:?}");
let expected: Vec<_> = (1..20)
.map(|n| (Duration::from_secs(15 * n), None))
.collect();
assert_eq!(reports, expected);
}
#[test]
fn a_daemon_that_comes_up_ends_the_wait() {
let (ready, reports, stopped) = simulate(ready_at(Duration::from_secs(40)));
assert!(ready);
assert_eq!(
reports,
[
(Duration::from_secs(15), None),
(Duration::from_secs(30), None)
]
);
assert!(stopped < Duration::from_secs(41), "{stopped:?}");
}
#[test]
fn a_starting_daemon_is_waited_for_with_its_reason_in_the_progress_line() {
let (ready, reports, stopped) = simulate(|now| {
if now >= Duration::from_secs(40) {
Readiness::Ready
} else {
Readiness::Starting(format!(
"rebuilding search indexes for 23594 memories, {}s so far",
now.as_secs()
))
}
});
assert!(ready);
assert!(stopped >= Duration::from_secs(40), "{stopped:?}");
assert!(stopped < Duration::from_secs(41), "{stopped:?}");
assert_eq!(
reports,
[
(
Duration::from_secs(15),
Some("rebuilding search indexes for 23594 memories, 15s so far".to_string())
),
(
Duration::from_secs(30),
Some("rebuilding search indexes for 23594 memories, 30s so far".to_string())
),
]
);
}
#[test]
fn a_daemon_still_starting_after_the_limit_is_not_ready() {
let (ready, _, stopped) =
simulate(|_| Readiness::Starting("opening the database".to_string()));
assert!(!ready);
assert!(stopped >= Duration::from_secs(300), "{stopped:?}");
}
#[test]
fn health_is_ready_only_when_it_answers_200_and_is_not_starting() {
let reason = "rebuilding search indexes for 23594 memories, 212s so far";
let starting = serde_json::json!({
"status": "starting",
"version": "0.12.0",
"state": "starting",
"reason": reason,
"since": "2026-11-02T08:00:00Z",
"serving": {"state": "starting", "reason": reason}
});
let ok = serde_json::json!({"status": "ok", "state": "ok", "serving": {"state": "ok"}});
let failing = serde_json::json!({"status": "ok", "state": "failing", "reason": "x"});
let cases = [
(
Some((200, starting)),
Readiness::Starting(reason.to_string()),
),
(Some((200, ok)), Readiness::Ready),
(Some((200, failing)), Readiness::Ready),
(Some((200, serde_json::Value::Null)), Readiness::Ready),
(
Some((
503,
serde_json::json!({"error": "the daemon is starting: x"}),
)),
Readiness::Down,
),
(None, Readiness::Down),
];
for (answered, expected) in cases {
assert_eq!(readiness(answered.clone()), expected, "{answered:?}");
}
}
}
#[cfg(test)]
mod pairing_offer_tests {
use super::super::pair::PairArgs;
use super::*;
#[test]
fn pairing_is_offered_only_to_a_device_without_an_identity() {
let cases = [
(Some(true), true, IdentityOffer::Skip),
(Some(true), false, IdentityOffer::Skip),
(Some(false), true, IdentityOffer::Ask),
(Some(false), false, IdentityOffer::Hint),
(None, true, IdentityOffer::Ask),
(None, false, IdentityOffer::Hint),
];
for (has_identity, interactive, expected) in cases {
assert_eq!(
identity_offer(has_identity, interactive),
expected,
"{has_identity:?} {interactive}"
);
}
}
#[test]
fn the_answer_picks_a_new_identity_by_default_or_joining() {
let cases = [
("", Some(IdentityChoice::New)),
("1\n", Some(IdentityChoice::New)),
(" New ", Some(IdentityChoice::New)),
("n", Some(IdentityChoice::New)),
("2", Some(IdentityChoice::Join)),
("join\n", Some(IdentityChoice::Join)),
("J", Some(IdentityChoice::Join)),
("3", None),
("maybe", None),
];
for (answer, expected) in cases {
assert_eq!(identity_choice(answer), expected, "{answer:?}");
}
}
#[test]
fn a_join_goes_through_the_same_arguments_as_sb_pair() {
let args = join_args(" alpha bravo charlie delta \n", " laptop.local\n").unwrap();
assert_eq!(
PairArgs::parse(&args).unwrap(),
PairArgs::Join {
code: "alpha bravo charlie delta".to_string(),
host: Some("laptop.local".to_string()),
discard_local: false,
}
);
let without_host = join_args("alpha bravo charlie delta", "\n").unwrap();
assert_eq!(
PairArgs::parse(&without_host).unwrap(),
PairArgs::Join {
code: "alpha bravo charlie delta".to_string(),
host: None,
discard_local: false,
}
);
assert_eq!(join_args(" \n", "laptop.local"), None);
}
#[test]
fn the_hint_names_the_join_command() {
assert!(PAIR_HINT.contains("sb pair <code> --host <host>"));
}
#[test]
fn only_a_fresh_interactive_install_is_asked_before_the_daemon_starts() {
let cases = [
(true, true, true),
(true, false, false),
(false, true, false),
(false, false, false),
];
for (fresh, interactive, expected) in cases {
assert_eq!(
ask_before_start(fresh, interactive),
expected,
"{fresh} {interactive}"
);
}
}
#[test]
fn an_answer_given_before_the_daemon_started_decides_the_offer_after_it() {
let cases = [
(Some(IdentityChoice::New), None, IdentityOffer::Skip),
(Some(IdentityChoice::New), Some(false), IdentityOffer::Skip),
(Some(IdentityChoice::Join), Some(false), IdentityOffer::Join),
(Some(IdentityChoice::Join), None, IdentityOffer::Join),
(Some(IdentityChoice::Join), Some(true), IdentityOffer::Skip),
];
for interactive in [true, false] {
for (asked, has_identity, expected) in &cases {
assert_eq!(
offer_after_ready(asked.as_ref(), *has_identity, interactive),
*expected,
"{asked:?} {has_identity:?} {interactive}"
);
}
}
for has_identity in [Some(true), Some(false), None] {
for interactive in [true, false] {
assert_eq!(
offer_after_ready(None, has_identity, interactive),
identity_offer(has_identity, interactive),
"{has_identity:?} {interactive}"
);
}
}
}
#[test]
fn a_fresh_install_is_one_without_a_store() {
let dir = tempfile::tempdir().unwrap();
let db = dir.path().join("brain.db");
assert!(fresh_install(&db));
std::fs::write(&db, "").unwrap();
assert!(!fresh_install(&db));
}
#[test]
fn choosing_to_join_marks_the_data_dir_for_the_daemon_and_a_new_identity_clears_it() {
let dir = tempfile::tempdir().unwrap();
let marker = dir.path().join(JOIN_PENDING_FILE);
record_identity_choice(dir.path(), &IdentityChoice::New).unwrap();
assert!(!marker.exists());
record_identity_choice(dir.path(), &IdentityChoice::Join).unwrap();
assert!(marker.is_file());
record_identity_choice(dir.path(), &IdentityChoice::New).unwrap();
assert!(!marker.exists());
}
#[test]
fn a_failed_join_says_nothing_is_ingested_and_names_both_ways_out() {
assert!(
JOIN_WAITING.contains("nothing is ingested"),
"{JOIN_WAITING}"
);
assert!(
JOIN_WAITING.contains("`sb pair <code> --host <host>`"),
"{JOIN_WAITING}"
);
assert!(JOIN_WAITING.contains("`sb pair`"), "{JOIN_WAITING}");
assert!(
JOIN_WAITING.contains("`sb pair --stop-waiting`"),
"{JOIN_WAITING}"
);
}
}