second-brain-cli 0.13.3

Memory layer for AI coding agents: ingest, recall, and sync across machines
#![allow(dead_code)]

use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::process::{Command, Output, Stdio};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

/// Bounds a hook against a hung daemon (60 s without its timeout), not the 1.5 s product budget.
pub const LIMIT: Duration = Duration::from_millis(2500);

pub enum Answer {
    Json(String),
    Status(u16, String),
    /// Called with the request path, without the query.
    Routed(fn(&str) -> (u16, String)),
    Never,
}

#[derive(Clone, Debug)]
pub struct Request {
    /// The request line and headers, lowercased.
    pub head: String,
    pub target: String,
    pub body: String,
}

pub struct Daemon {
    pub base: String,
    requests: Arc<Mutex<Vec<Request>>>,
}

impl Daemon {
    pub fn requests(&self) -> Vec<Request> {
        self.requests.lock().unwrap().clone()
    }
}

pub fn daemon(answer: Answer) -> Daemon {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let base = format!("http://{}", listener.local_addr().unwrap());
    let requests = Arc::new(Mutex::new(Vec::new()));
    let kept = requests.clone();
    let answer = Arc::new(answer);
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let Ok(stream) = stream else { continue };
            let (kept, answer) = (kept.clone(), answer.clone());
            std::thread::spawn(move || serve(stream, &kept, &answer));
        }
    });
    Daemon { base, requests }
}

fn serve(mut stream: TcpStream, kept: &Mutex<Vec<Request>>, answer: &Answer) {
    let mut raw = Vec::new();
    let mut buf = [0u8; 4096];
    let end = loop {
        if let Some(at) = raw.windows(4).position(|w| w == b"\r\n\r\n") {
            break at + 4;
        }
        match stream.read(&mut buf) {
            Ok(0) | Err(_) => return,
            Ok(n) => raw.extend_from_slice(&buf[..n]),
        }
    };
    let head = String::from_utf8_lossy(&raw[..end]).to_string();
    let length = head
        .lines()
        .filter_map(|line| line.split_once(':'))
        .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
        .and_then(|(_, value)| value.trim().parse::<usize>().ok())
        .unwrap_or(0);
    while raw.len() < end + length {
        match stream.read(&mut buf) {
            Ok(0) | Err(_) => break,
            Ok(n) => raw.extend_from_slice(&buf[..n]),
        }
    }
    kept.lock().unwrap().push(Request {
        target: head.lines().next().unwrap_or_default().to_string(),
        head: head.to_ascii_lowercase(),
        body: String::from_utf8_lossy(&raw[end..]).to_string(),
    });
    let (status, body) = match answer {
        Answer::Json(body) => (200, body.clone()),
        Answer::Status(status, body) => (*status, body.clone()),
        Answer::Routed(route) => {
            let target = head.split_whitespace().nth(1).unwrap_or_default();
            route(target.split('?').next().unwrap_or_default())
        }
        Answer::Never => {
            std::thread::sleep(Duration::from_secs(60));
            return;
        }
    };
    let response = format!(
        "HTTP/1.1 {status} X\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
        body.len()
    );
    stream.write_all(response.as_bytes()).ok();
}

pub const STARTING_REASON: &str = "rebuilding search indexes for 23594 memories, 212s so far";

/// The daemon's answers while it starts: `/health` says so, every other
/// route refuses with 503.
pub fn starting(path: &str) -> (u16, String) {
    if path == "/health" {
        let health = serde_json::json!({
            "status": "starting",
            "version": "0.12.0",
            "state": "starting",
            "reason": STARTING_REASON,
            "since": "2026-11-02T08:00:00Z",
            "serving": {"state": "starting", "reason": STARTING_REASON}
        });
        return (200, health.to_string());
    }
    let refusal =
        serde_json::json!({"error": format!("the daemon is starting: {STARTING_REASON}")});
    (503, refusal.to_string())
}

pub fn closed_port() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    format!("http://{}", listener.local_addr().unwrap())
}

pub struct Home {
    dir: tempfile::TempDir,
}

impl Home {
    pub fn new() -> Self {
        let dir = tempfile::tempdir().unwrap();
        let data = dir.path().join(".second-brain");
        std::fs::create_dir_all(&data).unwrap();
        let token = "t".repeat(32);
        std::fs::write(data.join("api.token"), format!("{token}\n")).unwrap();
        Home { dir }
    }

    pub fn path(&self) -> &Path {
        self.dir.path()
    }
}

pub fn run_hook(home: &Home, api: &str, hook: &str, stdin: &str) -> (Output, Duration) {
    let started = Instant::now();
    let mut child = Command::new(env!("CARGO_BIN_EXE_sb"))
        .args(["hook", hook])
        .env("HOME", home.path())
        .env("SECOND_BRAIN_API", api)
        .env("SECOND_BRAIN_BIND", "127.0.0.1:9")
        .env_remove("CLAUDE_CONFIG_DIR")
        .env_remove("RUST_LOG")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    let output = child.wait_with_output().unwrap();
    (output, started.elapsed())
}

pub fn assert_silent(output: &Output) {
    assert_eq!(output.status.code(), Some(0), "{output:?}");
    assert_eq!(String::from_utf8_lossy(&output.stdout), "", "{output:?}");
}