second-brain-cli 0.13.4

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

use std::net::{IpAddr, Ipv4Addr, TcpListener};
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;

use second_brain_api::bootstrap::Bootstrap;
use second_brain_api::clock_gate::ClockGate;
use second_brain_api::device_access::DeviceAccess;
use second_brain_api::health::Health;
use second_brain_api::pairing::{Pairing, PairingConfig};
use second_brain_api::sync_loop::SyncLoop;
use second_brain_api::write_gate::WriteGate;
use second_brain_api::{AppState, routes};
use second_brain_core::keys::ensure_device_keys;
use second_brain_core::machine::MachineIdentity;
use second_brain_core::retrieval::RetrievalTunables;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::StoreAdmin;
use serde_json::Value;

use crate::common::Home;

pub struct Device {
    pub home: Home,
    pub base: String,
    pub state: Arc<AppState>,
}

impl Device {
    /// `sb` names the forced command's binary from this device's HOME and
    /// daemon address.
    pub fn new(
        id: &str,
        home: Home,
        ssh: Option<(&Path, u16)>,
        sb: impl FnOnce(&Path, &str) -> PathBuf,
    ) -> Self {
        let data_dir = home.path().join(".second-brain");
        let store = SqliteStore::in_memory(id.to_string()).unwrap();
        let machine = MachineIdentity {
            id: id.to_string(),
            name: id.to_string(),
        };
        store.register_machine(&machine).unwrap();
        ensure_device_keys(&store, &data_dir).unwrap();
        let sqlite = Arc::new(store);
        let (ssh_host_key_dir, ssh_port) = match ssh {
            Some((dir, port)) => (dir.to_path_buf(), port),
            None => (home.path().join("no-sshd"), 1),
        };
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let sb = sb(home.path(), &base);
        let authorized_keys = home.path().join(".ssh/authorized_keys");
        let state = Arc::new(AppState {
            data_dir,
            pairing: Arc::new(Pairing::new(PairingConfig {
                listen_ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
                port: 0,
                ssh_host_key_dir,
                ssh_port,
                discovery: None,
            })),
            bootstrap: Arc::new(Bootstrap::load(&sqlite).unwrap()),
            device_access: Arc::new(DeviceAccess::with_authorized_keys(authorized_keys, sb)),
            gate: Arc::new(WriteGate::default()),
            clock: ClockGate::open_for_tests(),
            store: sqlite.clone(),
            sqlite,
            indexes: None,
            raw_index: None,
            raw_coverage: None,
            archive: None,
            reranker: None,
            tunables: RetrievalTunables::default(),
            embedder: None,
            machine,
            maintenance: Arc::new(RwLock::new(None)),
            repair_tx: None,
            near_duplicate_threshold: 0.97,
            near_duplicates: Arc::new(RwLock::new(None)),
            health: Arc::new(Health::new(chrono::Utc::now(), None)),
        });
        let app = routes::router().with_state(state.clone());
        std::thread::spawn(move || {
            let runtime = tokio::runtime::Builder::new_multi_thread()
                .worker_threads(2)
                .enable_all()
                .build()
                .unwrap();
            runtime.block_on(async move {
                let listener = tokio::net::TcpListener::from_std(listener).unwrap();
                axum::serve(listener, app).await.unwrap();
            });
        });
        Self { home, base, state }
    }

    pub fn data_dir(&self) -> &Path {
        &self.state.data_dir
    }

    pub fn post(&self, path: &str, body: Value) -> Value {
        let response = reqwest::blocking::Client::builder()
            .timeout(Duration::from_secs(30))
            .build()
            .unwrap()
            .post(format!("{}{path}", self.base))
            .json(&body)
            .send()
            .unwrap();
        let status = response.status();
        let body: Value = response.json().unwrap();
        assert!(status.is_success(), "{path} answered {status}: {body}");
        body
    }

    pub fn get(&self, path: &str) -> Value {
        reqwest::blocking::get(format!("{}{path}", self.base))
            .unwrap()
            .json()
            .unwrap()
    }

    pub fn sync_loop(&self) -> SyncLoop {
        SyncLoop::over_ssh(
            self.state.data_dir.clone(),
            self.state.sqlite.clone(),
            self.state.gate.clone(),
            self.state.clock.clone(),
            self.state.health.clone(),
            self.state.device_access.clone(),
            self.state.bootstrap.clone(),
        )
    }
}