second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
mod common;
#[path = "common/devices.rs"]
mod devices;

use std::io::{BufRead, BufReader};
use std::net::TcpListener;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::Duration;

use common::Home;
use devices::Device;
use second_brain_core::keys::DeviceKeys;

const README: &str = include_str!("../../../README.md");
const WAIT: Duration = Duration::from_secs(60);

/// README's Sync block, in order, as this test runs it.
const DOCUMENTED: [&str; 5] = [
    "sb pair",
    "sb pair <code> --host <host>",
    "sb sync-status",
    "sb device list",
    "sb device remove <name>",
];
const STOP_WAITING: &str = "sb pair --stop-waiting";

fn sync_block() -> Vec<&'static str> {
    let section = README
        .split("### Sync")
        .nth(1)
        .expect("README has a Sync section");
    let block = section
        .split("```bash")
        .nth(1)
        .and_then(|rest| rest.split("```").next())
        .expect("the Sync section has a bash block");
    block
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .collect()
}

fn sb(device: &Device, command: &str) -> Command {
    let args = command
        .strip_prefix("sb ")
        .unwrap_or_else(|| panic!("{command:?} is not an sb command"));
    let mut sb = Command::new(env!("CARGO_BIN_EXE_sb"));
    sb.args(args.split_whitespace())
        .env("HOME", device.home.path())
        .env("SECOND_BRAIN_API", &device.base)
        .env("SECOND_BRAIN_BIND", "127.0.0.1:9")
        .env_remove("RUST_LOG");
    sb
}

fn run(device: &Device, command: &str) -> String {
    let output = sb(device, command).output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
    assert!(
        output.status.success(),
        "`{command}` failed: {}\n{stdout}",
        String::from_utf8_lossy(&output.stderr)
    );
    stdout
}

struct Killed(Child);

impl Drop for Killed {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

fn host_stderr(desk: &Device) -> PathBuf {
    desk.home.path().join("pair.stderr")
}

/// Every line the host's `sb pair` prints until it exits, which must be a success.
fn finish(desk: &Device, mut host: Killed, printed: &mpsc::Receiver<String>) -> Vec<String> {
    let mut shown = Vec::new();
    loop {
        match printed.recv_timeout(WAIT) {
            Ok(line) => shown.push(line),
            Err(RecvTimeoutError::Disconnected) => break,
            Err(RecvTimeoutError::Timeout) => panic!(
                "the host's `sb pair` never finished: {shown:?}\n{}",
                std::fs::read_to_string(host_stderr(desk)).unwrap_or_default()
            ),
        }
    }
    let status = host.0.wait().unwrap();
    assert!(
        status.success(),
        "the host's `sb pair` failed: {shown:?}\n{}",
        std::fs::read_to_string(host_stderr(desk)).unwrap_or_default()
    );
    shown
}

/// Runs the host's `sb pair` until it prints the join command, and returns
/// what it printed before it, the code it shows and the port it listens on.
fn show_code(desk: &Device) -> (Killed, mpsc::Receiver<String>, Vec<String>, String, u16) {
    let mut child = sb(desk, DOCUMENTED[0])
        .stdout(Stdio::piped())
        .stderr(std::fs::File::create(host_stderr(desk)).unwrap())
        .spawn()
        .unwrap();
    let stdout = child.stdout.take().unwrap();
    let host = Killed(child);
    let (lines, printed) = mpsc::channel();
    std::thread::spawn(move || {
        for line in BufReader::new(stdout).lines() {
            if lines.send(line.unwrap_or_default()).is_err() {
                break;
            }
        }
    });
    let mut before = Vec::new();
    loop {
        let line = match printed.recv_timeout(WAIT) {
            Ok(line) => line,
            Err(e) => panic!(
                "`sb pair` never printed a join command ({e}): {before:?}\n{}",
                std::fs::read_to_string(host_stderr(desk)).unwrap_or_default()
            ),
        };
        let Some(join) = line.trim().strip_prefix("sb pair ") else {
            before.push(line);
            continue;
        };
        let (code, target) = join
            .split_once(" --host ")
            .unwrap_or_else(|| panic!("the join command names no host: {line}"));
        let port = target
            .rsplit_once(':')
            .and_then(|(_, port)| port.parse().ok())
            .unwrap_or_else(|| panic!("the join command names no port: {line}"));
        return (host, printed, before, code.to_string(), port);
    }
}

#[test]
fn readme_sync_commands_run_as_written_between_two_devices() {
    assert_eq!(sync_block(), DOCUMENTED, "README's Sync block changed");
    let host_keys = tempfile::tempdir().unwrap();
    std::fs::write(
        host_keys.path().join("ssh_host_ed25519_key.pub"),
        format!(
            "{} root@desk\n",
            DeviceKeys::generate().unwrap().ssh_public_key()
        ),
    )
    .unwrap();
    let sshd = TcpListener::bind("127.0.0.1:0").unwrap();
    let desk = Device::new(
        "desk",
        Home::new(),
        Some((host_keys.path(), sshd.local_addr().unwrap().port())),
        |_, _| PathBuf::from("sb"),
    );
    let laptop = Device::new("laptop", Home::new(), None, |_, _| PathBuf::from("sb"));

    let (host, printed, before, code, port) = show_code(&desk);
    assert!(
        before.iter().any(|line| line.contains("Recovery phrase")),
        "the first `sb pair` shows no recovery phrase: {before:?}"
    );
    // The pairing listener here binds loopback, not the address it prints.
    let joined = run(
        &laptop,
        &DOCUMENTED[1]
            .replace("<code>", &code)
            .replace("<host>", &format!("127.0.0.1:{port}")),
    );
    assert!(joined.contains("desk"), "{joined}");
    let shown = finish(&desk, host, &printed);
    assert!(
        shown.iter().any(|line| line.contains("Paired laptop")),
        "{shown:?}"
    );

    run(&desk, DOCUMENTED[2]);
    let listed = run(&desk, DOCUMENTED[3]);
    assert!(
        listed.contains("desk") && listed.contains("laptop"),
        "{listed}"
    );
    assert!(README.contains(&format!("`{STOP_WAITING}`")));
    let waiting = sb(&laptop, STOP_WAITING).output().unwrap();
    assert!(waiting.status.success(), "{waiting:?}");
    assert!(
        String::from_utf8_lossy(&waiting.stderr).contains("no longer waits"),
        "{waiting:?}"
    );
    let removed = run(&desk, &DOCUMENTED[4].replace("<name>", "laptop"));
    assert!(removed.contains("removed laptop"), "{removed}");
}