second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Output};

use second_brain_sync::peers;
use second_brain_sync::protocol::{Hello, SyncHeader};

fn hello(machine_id: &str) -> Hello {
    Hello {
        machine_id: machine_id.to_string(),
        wall_micros: chrono::Utc::now().timestamp_micros(),
        synced: true,
        cursor: None,
        held_origin_seq: None,
        keys: None,
        peer_in: None,
        log_floor: 0,
        head: 0,
        applied: None,
        merging: None,
    }
}

/// Answers the daemon routes `sb sync` calls as for a store with nothing
/// to send, until the test process exits.
fn fake_daemon() -> String {
    let listener = TcpListener::bind("127.0.0.1:0").unwrap();
    let addr = listener.local_addr().unwrap();
    let version = serde_json::to_string(&SyncHeader::local()).unwrap();
    let own_hello = serde_json::to_string(&hello("this-machine")).unwrap();
    std::thread::spawn(move || {
        for stream in listener.incoming() {
            let mut stream = stream.unwrap();
            let mut reader = BufReader::new(stream.try_clone().unwrap());
            let mut request_line = String::new();
            reader.read_line(&mut request_line).unwrap();
            let mut length = 0usize;
            loop {
                let mut line = String::new();
                reader.read_line(&mut line).unwrap();
                if line == "\r\n" || line.is_empty() {
                    break;
                }
                if let Some(v) = line.to_ascii_lowercase().strip_prefix("content-length:") {
                    length = v.trim().parse().unwrap();
                }
            }
            let mut body = vec![0u8; length];
            reader.read_exact(&mut body).unwrap();
            let reply = if request_line.contains("/v1/sync/version") {
                version.as_str()
            } else if request_line.contains("/v1/sync/status") {
                r#"{"peers":[]}"#
            } else if request_line.contains("/v1/sync/export") {
                r#"{"lines":[],"max_seq":0}"#
            } else if request_line.contains("/v1/sync/hello") {
                own_hello.as_str()
            } else {
                "{}"
            };
            write!(
                stream,
                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}",
                reply.len()
            )
            .unwrap();
        }
    });
    format!("http://{addr}")
}

/// An `ssh` that plays a peer with nothing to send; `import_exit` is the
/// peer's exit status for the push. Its export answers only a pull that
/// passes `--hello`, with a header carrying the peer's own.
fn fake_ssh(bin: &Path, import_exit: u8) {
    let header = SyncHeader {
        hello: Some(hello("6f1c1d1e-0000-4000-8000-000000000001")),
        ..SyncHeader::local()
    }
    .to_line();
    let script = format!(
        "#!/bin/sh\n\
         for arg in \"$@\"; do last=\"$arg\"; case \"$arg\" in\n\
           whoami) echo 6f1c1d1e-0000-4000-8000-000000000001; exit 0 ;;\n\
           sync-export) case \" $* \" in *\" --hello \"*) echo '{header}'; exit 0 ;; esac; exit 3 ;;\n\
           sync-import) read -r _; echo '{header}'; cat >/dev/null; echo '{{\"applied\":0}}'; exit {import_exit} ;;\n\
         esac; done\n\
         exit 2\n"
    );
    let path = bin.join("ssh");
    std::fs::write(&path, script).unwrap();
    std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap();
}

fn sync(import_exit: u8) -> (Output, tempfile::TempDir) {
    let home = tempfile::tempdir().unwrap();
    let data_dir = home.path().join(".second-brain");
    std::fs::create_dir_all(&data_dir).unwrap();
    second_brain_core::api_token::ensure(&data_dir).unwrap();
    let bin = home.path().join("bin");
    std::fs::create_dir_all(&bin).unwrap();
    fake_ssh(&bin, import_exit);
    let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap());
    let output = Command::new(env!("CARGO_BIN_EXE_sb"))
        .args(["sync", "user@peer.invalid"])
        .env("HOME", home.path())
        .env("PATH", path)
        .env("SECOND_BRAIN_API", fake_daemon())
        .output()
        .unwrap();
    (output, home)
}

#[test]
fn a_completed_sync_stamps_its_success() {
    let before = chrono::Utc::now();
    let (output, home) = sync(0);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(output.status.success(), "{stderr}");
    let stamped = peers::last_success(&home.path().join(".second-brain"))
        .unwrap()
        .expect("a stamp after a completed sync");
    assert!(stamped >= before, "{stamped} is older than the sync");
    let data_dir = home.path().join(".second-brain");
    for key_file in ["sync.key", "device.key"] {
        assert!(
            !data_dir.join(key_file).exists(),
            "sb sync wrote {key_file}; only the daemon holds keys"
        );
    }
}

#[test]
fn a_sync_whose_push_fails_stamps_nothing() {
    let (output, home) = sync(1);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(!output.status.success(), "{stderr}");
    assert!(stderr.contains("ssh push"), "{stderr}");
    assert_eq!(
        peers::last_success(&home.path().join(".second-brain")).unwrap(),
        None
    );
}