second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
mod common;

use std::net::TcpListener;
use std::process::Output;
use std::sync::{Arc, Barrier, RwLock};
use std::time::{Duration, Instant};

use common::{Home, assert_silent, run_hook};
use second_brain_api::health::Health;
use second_brain_api::write_gate::WriteGate;
use second_brain_api::{AppState, routes};
use second_brain_core::machine::MachineIdentity;
use second_brain_core::retrieval::RetrievalTunables;
use second_brain_core::schema::{AGENT_NOTE_SOURCE, Memory};
use second_brain_core::sqlite_store::{AgentNote, NoteKind, SqliteStore};
use second_brain_core::store::StoreAdmin;
use serde_json::{Value, json};

const CWD: &str = "/home/dev/my_app";
const PROJECT: &str = "-home-dev-my-app";
const SESSION_A: &str = "a1b2c3d4-0000-4000-8000-00000000000a";
const SESSION_B: &str = "b1b2c3d4-0000-4000-8000-00000000000b";
const ID_LINE: &str = "This session's id for second-brain notes:";
const MAX_CONTEXT_CHARS: usize = 1500;
const DELIVERY: Duration = Duration::from_secs(10);
const INTERVAL: Duration = Duration::from_secs(5);
const AFTER_INTERVAL: Duration = Duration::from_millis(5500);

struct Daemon {
    base: String,
    store: Arc<SqliteStore>,
}

fn daemon() -> Daemon {
    let store = SqliteStore::in_memory("sibling-machine".to_string()).unwrap();
    let machine = MachineIdentity {
        id: store.machine_id().to_string(),
        name: "sibling".to_string(),
    };
    store.register_machine(&machine).unwrap();
    let sqlite = Arc::new(store);
    let state = Arc::new(AppState {
        data_dir: std::env::temp_dir().join("second-brain-test-no-device-key"),
        pairing: Default::default(),
        bootstrap: Default::default(),
        device_access: Default::default(),
        gate: Arc::new(WriteGate::default()),
        clock: second_brain_api::clock_gate::ClockGate::open_for_tests(),
        store: sqlite.clone(),
        sqlite: sqlite.clone(),
        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 listener = TcpListener::bind("127.0.0.1:0").unwrap();
    listener.set_nonblocking(true).unwrap();
    let base = format!("http://{}", listener.local_addr().unwrap());
    let app = routes::router().with_state(state);
    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();
        });
    });
    Daemon {
        base,
        store: sqlite,
    }
}

fn write_note(daemon: &Daemon, session: &str, decision: &str) {
    let client = reqwest::blocking::Client::builder()
        .timeout(DELIVERY)
        .build()
        .unwrap();
    let reply: Value = client
        .post(format!("{}/v1/notes", daemon.base))
        .json(&json!({
            "session_id": session,
            "kind": "fact",
            "decision": decision,
            "reason": "the  config\nloader caches it",
            "dead_ends": ["restarting", "clearing the cache"],
            "project": PROJECT,
        }))
        .send()
        .unwrap()
        .error_for_status()
        .unwrap()
        .json()
        .unwrap();
    assert_eq!(reply["duplicate"], false, "{reply}");
}

fn input(event: &str, session: &str) -> Value {
    json!({
        "session_id": session,
        "transcript_path": "/tmp/transcript.jsonl",
        "cwd": CWD,
        "permission_mode": "default",
        "hook_event_name": event,
        "tool_name": "Bash",
        "tool_input": {"command": "ls"},
        "tool_response": {"stdout": ""},
    })
}

fn hook(home: &Home, daemon: &Daemon, name: &str, input: &Value) -> Output {
    run_hook(home, &daemon.base, name, &input.to_string()).0
}

fn tool_call(home: &Home, daemon: &Daemon, input: &Value) -> Output {
    hook(home, daemon, "post-tool-use", input)
}

fn context(output: &Output, event: &str) -> String {
    assert_eq!(output.status.code(), Some(0), "{output:?}");
    let reply: Value = serde_json::from_slice(&output.stdout).unwrap_or_else(|e| {
        panic!("{e}: {}", String::from_utf8_lossy(&output.stdout));
    });
    assert_eq!(
        reply["hookSpecificOutput"]["hookEventName"], event,
        "{reply}"
    );
    let text = reply["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_else(|| panic!("{reply}"))
        .to_string();
    assert!(text.chars().count() <= MAX_CONTEXT_CHARS, "{text}");
    text
}

fn injected(output: &Output) -> String {
    context(output, "PostToolUse")
}

#[test]
fn a_sibling_note_reaches_the_next_tool_call_and_own_notes_never_do() {
    let home = Home::new();
    let daemon = daemon();
    write_note(&daemon, SESSION_B, "B kept its own parser");
    write_note(&daemon, SESSION_A, "A found the port is fixed");
    let written = Instant::now();

    let text = injected(&tool_call(&home, &daemon, &input("PostToolUse", SESSION_B)));
    assert!(written.elapsed() < DELIVERY, "{:?}", written.elapsed());
    let lines: Vec<&str> = text.lines().collect();
    assert!(lines[0].contains("other sessions"), "{text}");
    assert_eq!(
        lines[1..],
        [format!(
            "- [fact, session {}] A found the port is fixed Why: the config loader caches it \
             Dead ends: restarting; clearing the cache",
            &SESSION_A[..8]
        )],
        "{text}"
    );
    assert!(!text.contains("B kept"), "{text}");
}

#[test]
fn nothing_is_injected_twice_and_a_later_note_still_arrives() {
    let home = Home::new();
    let daemon = daemon();
    write_note(&daemon, SESSION_A, "first finding");
    let b = input("PostToolUse", SESSION_B);
    assert!(injected(&tool_call(&home, &daemon, &b)).contains("first finding"));

    std::thread::sleep(AFTER_INTERVAL);
    assert_silent(&tool_call(&home, &daemon, &b));

    write_note(&daemon, SESSION_A, "second finding");
    std::thread::sleep(AFTER_INTERVAL);
    let text = injected(&tool_call(&home, &daemon, &b));
    assert!(text.contains("second finding"), "{text}");
    assert!(!text.contains("first finding"), "{text}");
}

#[test]
fn a_note_inside_the_interval_waits_for_the_first_run_after_it() {
    let home = Home::new();
    let daemon = daemon();
    write_note(&daemon, SESSION_A, "first finding");
    let b = input("PostToolUse", SESSION_B);
    let first = Instant::now();
    assert!(injected(&tool_call(&home, &daemon, &b)).contains("first finding"));
    let returned = Instant::now();

    write_note(&daemon, SESSION_A, "second finding");
    let held = tool_call(&home, &daemon, &b);
    if first.elapsed() >= INTERVAL && !held.stdout.is_empty() {
        eprintln!("skipped the hold check: the host took over {INTERVAL:?} between runs");
        assert!(injected(&held).contains("second finding"));
        return;
    }
    assert_silent(&held);

    std::thread::sleep(AFTER_INTERVAL.saturating_sub(returned.elapsed()));
    let text = injected(&tool_call(&home, &daemon, &b));
    assert!(text.contains("second finding"), "{text}");
    assert!(!text.contains("first finding"), "{text}");
}

#[test]
fn session_start_names_the_session_and_shows_siblings_once() {
    let home = Home::new();
    let daemon = daemon();
    write_note(&daemon, SESSION_A, "first finding");
    let mut start = input("SessionStart", SESSION_B);
    start["source"] = json!("startup");

    let text = context(
        &hook(&home, &daemon, "session-start", &start),
        "SessionStart",
    );
    let lines: Vec<&str> = text.lines().collect();
    assert_eq!(lines[0], format!("{ID_LINE} {SESSION_B}"), "{text}");
    assert!(lines[1].contains("other sessions"), "{text}");
    assert!(lines[2].contains("first finding"), "{text}");

    std::thread::sleep(AFTER_INTERVAL);
    write_note(&daemon, SESSION_A, "second finding");
    let text = injected(&tool_call(&home, &daemon, &input("PostToolUse", SESSION_B)));
    assert!(text.contains("second finding"), "{text}");
    assert!(!text.contains("first finding"), "{text}");
}

#[test]
fn a_subagent_keeps_its_own_record_of_what_it_was_shown() {
    let home = Home::new();
    let daemon = daemon();
    write_note(&daemon, SESSION_A, "first finding");
    let parent = input("PostToolUse", SESSION_B);
    let mut subagent = parent.clone();
    subagent["agent_id"] = json!("agent-7");
    subagent["agent_type"] = json!("Explore");

    assert!(injected(&tool_call(&home, &daemon, &parent)).contains("first finding"));
    assert!(injected(&tool_call(&home, &daemon, &subagent)).contains("first finding"));
}

#[test]
fn parallel_runs_of_one_session_inject_a_note_once() {
    let home = Arc::new(Home::new());
    let daemon = Arc::new(daemon());
    write_note(&daemon, SESSION_A, "first finding");
    let start = Arc::new(Barrier::new(2));
    let (sent, received) = std::sync::mpsc::channel();
    for _ in 0..2 {
        let (home, daemon, start, sent) =
            (home.clone(), daemon.clone(), start.clone(), sent.clone());
        std::thread::spawn(move || {
            start.wait();
            let output = tool_call(&home, &daemon, &input("PostToolUse", SESSION_B));
            sent.send(output).unwrap();
        });
    }
    let outputs: Vec<Output> = (0..2)
        .map(|_| received.recv_timeout(DELIVERY).unwrap())
        .collect();
    let shown = outputs
        .iter()
        .filter(|output| !output.stdout.is_empty())
        .filter(|output| injected(output).contains("first finding"))
        .count();
    assert_eq!(shown, 1, "{outputs:?}");
}

#[test]
fn a_note_older_than_the_window_is_not_shown() {
    let home = Home::new();
    let daemon = daemon();
    let mut old = Memory::new(
        AgentNote::new(NoteKind::Fact, "an old finding").render(),
        NoteKind::Fact.memory_type(),
        AGENT_NOTE_SOURCE.to_string(),
        SESSION_A.to_string(),
    )
    .with_project_path(Some(PROJECT.to_string()))
    .with_machine_id(daemon.store.machine_id().to_string());
    old.created_at = chrono::Utc::now() - chrono::Duration::minutes(121);
    assert!(daemon.store.store_memory_if_absent(&old).unwrap());
    write_note(&daemon, SESSION_A, "a new finding");

    let text = injected(&tool_call(&home, &daemon, &input("PostToolUse", SESSION_B)));
    assert!(text.contains("a new finding"), "{text}");
    assert!(!text.contains("an old finding"), "{text}");
}

#[test]
fn a_down_daemon_or_no_session_injects_nothing() {
    let home = Home::new();
    let daemon = daemon();
    write_note(&daemon, SESSION_A, "first finding");
    let mut anonymous = input("PostToolUse", SESSION_B);
    anonymous.as_object_mut().unwrap().remove("session_id");
    assert_silent(&tool_call(&home, &daemon, &anonymous));
    let (output, took) = run_hook(
        &Home::new(),
        &common::closed_port(),
        "post-tool-use",
        &input("PostToolUse", SESSION_B).to_string(),
    );
    assert_silent(&output);
    assert!(took < common::LIMIT, "{took:?}");
    assert!(
        injected(&tool_call(&home, &daemon, &input("PostToolUse", SESSION_B)))
            .contains("first finding")
    );
}

#[test]
fn a_hung_daemon_is_asked_once_per_interval_not_on_every_tool_call() {
    let home = Home::new();
    let hung = common::daemon(common::Answer::Never);
    let b = input("PostToolUse", SESSION_B).to_string();
    let first = Instant::now();
    for _ in 0..2 {
        let (output, took) = run_hook(&home, &hung.base, "post-tool-use", &b);
        assert_silent(&output);
        assert!(took < common::LIMIT, "{took:?}");
    }
    let asked = hung.requests().len();
    if first.elapsed() < INTERVAL {
        assert_eq!(asked, 1, "{:?}", hung.requests());
    } else {
        eprintln!("skipped the count check: the host took over {INTERVAL:?} for two runs");
    }
}