second-brain-cli 0.13.4

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

use anyhow::{Context, Result};
use reqwest::StatusCode;
use reqwest::blocking::{Client, Response};
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue};
use second_brain_core::{api_token, machine};
use second_brain_sync::protocol::{SyncHeader, VersionError};

/// Only for commands that move sync records: the daemon applies them, so a
/// daemon on other sync versions than this binary must be refused up front.
pub fn sync_client(timeout: Duration) -> Result<Client> {
    let client = client(timeout)?;
    ensure_daemon_sync_version(&client, &base_url())?;
    Ok(client)
}

fn ensure_daemon_sync_version(client: &Client, base: &str) -> Result<()> {
    let resp = client
        .get(format!("{base}/v1/sync/version"))
        .send()
        .context("asking the local daemon for its sync version")?;
    if resp.status() == StatusCode::NOT_FOUND {
        return Err(VersionError::UnversionedDaemon.into());
    }
    let daemon: SyncHeader = daemon_ok(resp)?
        .json()
        .context("reading the local daemon's sync version")?;
    SyncHeader::local().ensure_matches("this sb", &daemon, "the local daemon")?;
    Ok(())
}

/// Surfaces a daemon's sync refusal (409) as its own message, names the token
/// file this process read when the daemon rejects it (401), and carries the
/// daemon's error text for any other error status.
pub fn daemon_ok(resp: Response) -> Result<Response> {
    daemon_ok_against(resp, || Ok(api_token::path(&machine::data_dir()?)))
}

fn daemon_ok_against(
    resp: Response,
    token_path: impl FnOnce() -> Result<PathBuf>,
) -> Result<Response> {
    if resp.status() == StatusCode::UNAUTHORIZED {
        anyhow::bail!(
            "the daemon rejected the API token in {}; run as the user the daemon runs as, \
             or restart the daemon if that file was replaced",
            token_path()?.display()
        );
    }
    if resp.status() == StatusCode::CONFLICT {
        let body = resp.text().context("reading the daemon's sync refusal")?;
        anyhow::bail!("{}", error_message(&body));
    }
    let status = resp.status();
    if !status.is_client_error() && !status.is_server_error() {
        return Ok(resp);
    }
    let message = match resp.text() {
        Ok(body) => error_message(&body),
        Err(e) => format!("reading its answer failed: {e}"),
    };
    if message.is_empty() {
        anyhow::bail!("the daemon answered {status}");
    }
    anyhow::bail!("the daemon answered {status}: {message}")
}

/// The `error` field of a daemon's JSON refusal, or the body as sent when it
/// is not one.
pub fn error_message(body: &str) -> String {
    serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| v["error"].as_str().map(str::to_string))
        .unwrap_or_else(|| body.trim().to_string())
}

/// What a `/health` answer says the daemon is doing while it starts, None
/// once it serves, whatever its state then.
pub fn starting_reason(health: &serde_json::Value) -> Option<&str> {
    let starting = health["status"] == "starting"
        || health["state"] == "starting"
        || health["serving"]["state"] == "starting";
    starting.then(|| {
        health["reason"]
            .as_str()
            .or_else(|| health["serving"]["reason"].as_str())
            .unwrap_or("no reason given")
    })
}

pub fn base_url() -> String {
    std::env::var("SECOND_BRAIN_API").unwrap_or_else(|_| "http://127.0.0.1:7200".to_string())
}

pub fn client(timeout: Duration) -> Result<Client> {
    let token = api_token::read(&machine::data_dir()?)?;
    build(timeout, Some(&token))
}

/// For `GET /health` and `GET /v1/status`, the only routes the daemon serves
/// without a token, so they work before the daemon has created one.
pub fn open_client(timeout: Duration) -> Result<Client> {
    build(timeout, None)
}

fn build(timeout: Duration, token: Option<&str>) -> Result<Client> {
    Client::builder()
        .timeout(timeout)
        .default_headers(default_headers(token)?)
        .build()
        .context("building the daemon API client")
}

fn default_headers(token: Option<&str>) -> Result<HeaderMap> {
    let mut headers = HeaderMap::new();
    if let Some(token) = token {
        let mut auth = HeaderValue::from_str(&format!("Bearer {token}"))
            .context("the daemon API token is not a valid header value")?;
        auth.set_sensitive(true);
        headers.insert(AUTHORIZATION, auth);
    }
    Ok(headers)
}

#[cfg(test)]
mod tests {
    use std::io::{BufRead, BufReader, Write};
    use std::net::TcpListener;

    use second_brain_sync::protocol::SYNC_PROTOCOL_VERSION;

    use super::*;

    #[test]
    fn default_headers_carry_the_bearer_token_as_sensitive() {
        let headers = default_headers(Some("abc123")).unwrap();
        let auth = &headers[AUTHORIZATION];
        assert_eq!(auth, "Bearer abc123");
        assert!(auth.is_sensitive());
    }

    #[test]
    fn open_client_headers_carry_no_token() {
        assert!(!default_headers(None).unwrap().contains_key(AUTHORIZATION));
    }

    #[test]
    fn every_request_sends_the_token() {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let server = std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            let mut head = Vec::new();
            loop {
                let mut line = String::new();
                reader.read_line(&mut line).unwrap();
                if line == "\r\n" || line.is_empty() {
                    break;
                }
                head.push(line.trim_end().to_ascii_lowercase());
            }
            (&stream)
                .write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 0\r\nconnection: close\r\n\r\n")
                .unwrap();
            head
        });

        let client = build(Duration::from_secs(5), Some("tok")).unwrap();
        client.get(format!("http://{addr}/v1/x")).send().unwrap();
        let head = server.join().unwrap();
        assert!(
            head.iter().any(|l| l == "authorization: bearer tok"),
            "{head:?}"
        );
    }

    fn daemon_answering(status: &'static str, body: String) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        std::thread::spawn(move || {
            let (stream, _) = listener.accept().unwrap();
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            loop {
                let mut line = String::new();
                reader.read_line(&mut line).unwrap();
                if line == "\r\n" || line.is_empty() {
                    break;
                }
            }
            let response = format!(
                "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
                body.len()
            );
            (&stream).write_all(response.as_bytes()).unwrap();
        });
        format!("http://{addr}")
    }

    fn check(status: &'static str, body: String) -> Result<()> {
        let base = daemon_answering(status, body);
        ensure_daemon_sync_version(&build(Duration::from_secs(5), None).unwrap(), &base)
    }

    fn json(header: &SyncHeader) -> String {
        serde_json::to_string(header).unwrap()
    }

    #[test]
    fn a_daemon_refusal_carries_its_reason() {
        let body = r#"{"error":"upgrade this daemon's binary"}"#.to_string();
        let err = check("409 Conflict", body).unwrap_err();
        assert!(
            err.to_string().contains("upgrade this daemon's binary"),
            "{err:#}"
        );
    }

    #[test]
    fn a_daemon_on_this_binarys_versions_passes() {
        check("200 OK", json(&SyncHeader::local())).unwrap();
    }

    #[test]
    fn a_daemon_without_the_version_route_is_refused() {
        let err = check("404 Not Found", String::new()).unwrap_err();
        assert!(err.to_string().contains("protocol 1"), "{err:#}");
        assert!(
            err.to_string().contains("upgrade the local daemon"),
            "{err:#}"
        );
    }

    #[test]
    fn a_daemon_on_another_protocol_is_refused() {
        let daemon = SyncHeader {
            sync_protocol: SYNC_PROTOCOL_VERSION + 1,
            ..SyncHeader::local()
        };
        let err = check("200 OK", json(&daemon)).unwrap_err();
        assert!(err.to_string().contains("upgrade this sb"), "{err:#}");
    }

    #[test]
    fn a_daemon_on_another_schema_is_refused() {
        let local = SyncHeader::local();
        let daemon = SyncHeader {
            schema_version: local.schema_version - 1,
            ..local
        };
        let err = check("200 OK", json(&daemon)).unwrap_err();
        assert!(
            err.to_string().contains("upgrade the local daemon"),
            "{err:#}"
        );
    }

    fn answer(status: &'static str) -> Response {
        let base = daemon_answering(status, String::new());
        build(Duration::from_secs(5), Some("tok"))
            .unwrap()
            .get(format!("{base}/v1/sync/export"))
            .send()
            .unwrap()
    }

    #[test]
    fn a_rejected_token_names_the_token_file() {
        let token_path = || Ok(PathBuf::from("/somewhere/.second-brain/api.token"));
        let err = daemon_ok_against(answer("401 Unauthorized"), token_path).unwrap_err();
        assert!(
            format!("{err:#}").contains("/somewhere/.second-brain/api.token"),
            "{err:#}"
        );
    }

    #[test]
    fn other_statuses_do_not_resolve_the_token_path() {
        let token_path = || -> Result<PathBuf> { panic!("token path resolved for a non-401") };
        assert!(daemon_ok_against(answer("200 OK"), token_path).is_ok());
        let err = daemon_ok_against(answer("500 Internal Server Error"), token_path).unwrap_err();
        assert!(format!("{err:#}").contains("500"), "{err:#}");
    }

    fn answer_with(status: &'static str, body: &str) -> Response {
        let base = daemon_answering(status, body.to_string());
        build(Duration::from_secs(5), Some("tok"))
            .unwrap()
            .get(format!("{base}/v1/recall"))
            .send()
            .unwrap()
    }

    #[test]
    fn an_error_status_carries_the_daemons_error_text() {
        let token_path = || -> Result<PathBuf> { panic!("token path resolved for a non-401") };
        let cases = [
            (
                "503 Service Unavailable",
                r#"{"error":"the daemon is starting: opening the database"}"#,
                "503 Service Unavailable: the daemon is starting: opening the database",
            ),
            (
                "502 Bad Gateway",
                "upstream down\n",
                "502 Bad Gateway: upstream down",
            ),
            ("500 Internal Server Error", "", "500 Internal Server Error"),
        ];
        for (status, body, expected) in cases {
            let err = daemon_ok_against(answer_with(status, body), token_path).unwrap_err();
            assert_eq!(
                format!("{err:#}"),
                format!("the daemon answered {expected}")
            );
        }
    }

    #[test]
    fn a_starting_health_answer_gives_its_reason_and_a_serving_one_none() {
        let reason = "rebuilding search indexes for 23594 memories, 212s so far";
        let cases = [
            (
                serde_json::json!({
                    "status": "starting",
                    "version": "0.12.0",
                    "state": "starting",
                    "reason": reason,
                    "since": "2026-11-02T08:00:00Z",
                    "serving": {"state": "starting", "reason": reason}
                }),
                Some(reason),
            ),
            (
                serde_json::json!({"status": "starting", "serving": {"state": "starting", "reason": "loading models"}}),
                Some("loading models"),
            ),
            (
                serde_json::json!({"state": "starting"}),
                Some("no reason given"),
            ),
            (
                serde_json::json!({"status": "ok", "state": "ok", "serving": {"state": "ok"}}),
                None,
            ),
            (
                serde_json::json!({"status": "ok", "state": "degraded", "reason": "capture is 2h behind"}),
                None,
            ),
            (serde_json::Value::Null, None),
        ];
        for (health, expected) in cases {
            assert_eq!(starting_reason(&health), expected, "{health}");
        }
    }
}