second-brain-cli 0.13.3

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::time::Duration;

use anyhow::{Context, Result};
use second_brain_core::{api_token, machine, model_cache};

use crate::{api, claude_code, daemon, launchd};

mod claude;
mod daemon_checks;
mod fixes;
mod host;
mod report;
mod service;

use daemon_checks::Api;

pub(crate) fn cmd_status() -> Result<()> {
    let api = api::base_url();
    let client = api::open_client(std::time::Duration::from_secs(5))?;

    let resp = client.get(format!("{api}/v1/status")).send();

    match resp {
        Ok(r) => {
            let body: serde_json::Value = api::daemon_ok(r)?.json()?;
            println!("memories: {}", body["memory_count"]);
            println!("ingested files: {}", body["ingested_file_count"]);
            println!("version: {}", body["version"]);
            println!("embedder: {}", body["embedder_available"]);
            let c = &body["consolidation"];
            if c.is_object() {
                println!(
                    "consolidation: {} distilled, {} raw pending, {} retired, {} awaiting retirement",
                    c["distilled_live"],
                    c["raw_pending"],
                    c["raw_retired"],
                    c["raw_retire_pending"]
                );
            }
            match &body["maintenance"] {
                m if m.is_object() => {
                    println!("last repair: {}", m["ran_at"].as_str().unwrap_or("?"));
                    for (name, value) in drift_fields(&m["report_after"]) {
                        println!("WARN {name}: {value}");
                    }
                }
                _ => println!("last repair: none since the daemon started"),
            }
            if let Some(diag) = body["diagnostic"].as_str()
                && !diag.is_empty()
            {
                println!("\n{diag}");
            }
        }
        Err(_) => anyhow::bail!("daemon not reachable at {api} — is it running?"),
    }
    Ok(())
}

pub(crate) fn cmd_whoami() -> Result<()> {
    let api = api::base_url();
    let client = api::open_client(std::time::Duration::from_secs(5))?;
    let body: serde_json::Value = api::daemon_ok(
        client
            .get(format!("{api}/health"))
            .send()
            .context("daemon not reachable")?,
    )?
    .json()?;
    if let Some(reason) = api::starting_reason(&body) {
        anyhow::bail!("the daemon is starting: {reason}");
    }
    let id = body["machine_id"]
        .as_str()
        .context("daemon response missing machine_id")?;
    println!("{id}");
    Ok(())
}

/// The report fields a repair is expected to zero, mirroring
/// `IntegrityReport::drift` so status and doctor warn about the same things.
fn drift_fields(report: &serde_json::Value) -> Vec<(&'static str, u64)> {
    let mut out = Vec::new();
    for name in [
        "raw_retire_pending",
        "duplicate_hot_groups",
        "orphaned_distillation_markers",
        "dead_vec_keys",
        "dangling_relations",
        "sync_log_reclaimable_rows",
        "stale_peer_cursors",
        "missing_embeddings",
    ] {
        let value = report[name].as_u64().unwrap_or(0);
        if value > 0 {
            out.push((name, value));
        }
    }
    if report["index_consistent"] == serde_json::Value::Bool(false) {
        out.push(("index_inconsistent", 1));
    }
    out
}

fn print_report(report: &serde_json::Value) {
    let Some(map) = report.as_object() else {
        println!("{report}");
        return;
    };
    let width = map.keys().map(|k| k.len()).max().unwrap_or(0);
    for (key, value) in map {
        let shown = match value {
            serde_json::Value::Null => "n/a".to_string(),
            v => v.to_string(),
        };
        println!("{key:width$}  {shown}");
    }
    let drift = drift_fields(report);
    if drift.is_empty() {
        println!("\nno drift");
    } else {
        for (name, value) in drift {
            println!("WARN {name}: {value}");
        }
    }
}

pub(crate) fn cmd_doctor(repair: bool, dry_run: bool) -> Result<()> {
    if !repair {
        return cmd_check();
    }
    let api = api::base_url();
    let client = api::client(std::time::Duration::from_secs(3600))?;

    let summary: serde_json::Value = api::daemon_ok(
        client
            .post(format!("{api}/v1/maintenance/repair"))
            .json(&serde_json::json!({"dry_run": dry_run}))
            .send()
            .context("calling repair on daemon")?,
    )?
    .json()?;
    println!(
        "{}",
        if dry_run {
            "repair (dry run):"
        } else {
            "repair:"
        }
    );
    if let Some(stats) = summary["stats"].as_object() {
        for (key, value) in stats {
            if key != "dry_run" {
                println!("  {key}: {value}");
            }
        }
    }
    println!("\nreport after:");
    print_report(&summary["report_after"]);
    Ok(())
}

fn cmd_check() -> Result<()> {
    let ctx = current_context()?;
    if let Err(refusal) = refuse_borrowed_home(fixes::current_uid(), &ctx.home) {
        anyhow::bail!(refusal);
    }
    let api = HttpApi::new(api::base_url(), Duration::from_secs(5))?;
    let mut checks = daemon_checks::checks(&ctx, &api);
    checks.push(service::check(
        &ctx,
        &mut daemon::SystemExec,
        &mut launchd::System,
    ));
    checks.extend(claude::checks(&ctx, &mut daemon::SystemExec));
    checks.extend(host::checks(&ctx, &host::free_bytes));
    print!("{}", report::render(&checks));

    if daemon_checks::daemon_answered(&checks) {
        print_integrity(&ctx);
    }

    match report::failures(&checks) {
        0 => Ok(()),
        1 => anyhow::bail!("1 check failed"),
        n => anyhow::bail!("{n} checks failed"),
    }
}

fn print_integrity(ctx: &report::Context) {
    println!("\nstore integrity:");
    let fetched = api_token::read(&ctx.data_dir)
        .map_err(|e| format!("{e:#}"))
        .and_then(|token| {
            HttpApi::new(api::base_url(), INTEGRITY_TIMEOUT)
                .map_err(|e| format!("{e:#}"))?
                .get("/v1/health", Some(&token))
        });
    match fetched {
        Ok((200, body)) => print_report(&body),
        Ok((status, body)) => match body["error"].as_str() {
            Some(error) => println!("could not be read: the daemon answered {status}: {error}"),
            None => println!("could not be read: the daemon answered {status}"),
        },
        Err(e) => println!("could not be read: {e}"),
    }
}

const INTEGRITY_TIMEOUT: Duration = Duration::from_secs(600);

fn current_context() -> Result<report::Context> {
    let home = std::path::PathBuf::from(std::env::var_os("HOME").context("HOME not set")?);
    let exe = std::env::current_exe().context("cannot determine own binary path")?;
    let bin_dir = exe
        .parent()
        .context("own binary path has no parent")?
        .to_path_buf();
    let os = daemon::Os::current();
    Ok(report::Context {
        os,
        data_dir: machine::data_dir()?,
        mcp_bin: crate::bins::locate_beside(&bin_dir, "second-brain-mcp")
            .map_err(|e| format!("{e:#}")),
        sb_bin: exe,
        claude_config_dir: claude_code::config_dir(std::env::var_os("CLAUDE_CONFIG_DIR")),
        search_path: std::env::var_os("PATH"),
        model_cache: model_cache::model_cache_dir_in(&daemon_user_cache(os, &home)),
        home,
    })
}

/// Root with another user's HOME (sudo keeps HOME on macOS) would judge that
/// user's files against root and suggest handing them to root.
fn refuse_borrowed_home(uid: u32, home: &std::path::Path) -> Result<(), String> {
    use std::os::unix::fs::MetadataExt;
    let owner = std::fs::metadata(home).map(|meta| meta.uid());
    match owner {
        Ok(owner) if uid == 0 && owner != 0 => Err(format!(
            "{} belongs to uid {owner}, not root; run `sb doctor` without sudo, as the user the daemon runs as",
            home.display()
        )),
        _ => Ok(()),
    }
}

/// The user cache dir under the service setup installs, whose environment
/// sets no `XDG_CACHE_HOME`.
fn daemon_user_cache(os: daemon::Os, home: &std::path::Path) -> std::path::PathBuf {
    match os {
        daemon::Os::Linux => home.join(".cache"),
        daemon::Os::MacOs => home.join("Library/Caches"),
    }
}

struct HttpApi {
    base: String,
    client: reqwest::blocking::Client,
}

impl HttpApi {
    fn new(base: String, timeout: Duration) -> Result<Self> {
        Ok(HttpApi {
            base,
            client: api::open_client(timeout)?,
        })
    }
}

impl Api for HttpApi {
    fn get(&self, path: &str, token: Option<&str>) -> Result<(u16, serde_json::Value), String> {
        let mut req = self.client.get(format!("{}{path}", self.base));
        if let Some(token) = token {
            req = req.bearer_auth(token);
        }
        let resp = req.send().map_err(|e| e.to_string())?;
        let status = resp.status().as_u16();
        let body = resp.json().unwrap_or(serde_json::Value::Null);
        Ok((status, body))
    }
}

#[cfg(test)]
mod tests {
    use std::os::unix::fs::MetadataExt;

    use super::*;

    #[test]
    fn root_with_another_users_home_is_refused() {
        let home = tempfile::tempdir().unwrap();
        let owner = std::fs::metadata(home.path()).unwrap().uid();
        if owner == 0 {
            return;
        }
        let refusal = refuse_borrowed_home(0, home.path()).unwrap_err();
        assert!(refusal.contains("without sudo"), "{refusal}");
        assert!(refuse_borrowed_home(owner, home.path()).is_ok());
    }

    #[test]
    fn root_with_its_own_home_is_checked() {
        assert!(refuse_borrowed_home(0, std::path::Path::new("/")).is_ok());
    }
}