second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::path::Path;
use std::process::{Command, Output};

const HELP: &str = "second-brain CLI

Usage: sb <command> [args]

Commands:
  ingest [source]     Ingest conversation history (claude-code, cursor, all)
  recall <query>      Search the brain
  remember <text>     Store new knowledge
  setup               One-command install: systemd service, MCP config, first ingest
  start               Start the daemon
  stop                Stop the daemon
  restart             Restart the daemon
  status              Show brain stats
  sync <peer>         Bidirectional sync with a peer
  sync-status         Show sync state for all peers
  sync-key            Retired: the daemon keeps sync keys; pair devices instead
  backfill-session-dates  Date memories from this machine's transcripts (--dry-run, --reemit)
  sync-compact        Collapse duplicate sync_log rows (--dry-run, --ops delete,create)
  prune-relations     Delete relations whose endpoints no longer resolve
  doctor              Check the install and store, with a fix for each failure (--repair, --dry-run)
  vacuum              Reclaim free pages in brain.db after a repair
  backup <dest>       Write a copy of the data dir that `sb restore` accepts, while the daemon runs
  redact --dry-run    Count stored secrets the daemon's redaction pass would remove
  sync-trust <host>   Fetch and pin a host's SSH key after fingerprint review
  reingest            Re-ingest all conversations
  consolidate         Distill raw memories via local LLM
  daily-pipeline      End-of-day: consolidate \u{2192} daily \u{2192} export \u{2192} enhance
  hook <name>         Run a Claude Code hook on the event JSON from stdin
  digest              What agents decided, abandoned and left blocked on you (--since 24h, --project X)
  device list|remove  Show this sync identity's devices, or remove one (--keep <name>, --yes)
  recovery [new|remove]  Show this identity's recovery phrases, make one, or retire one (remove <fingerprint>)
  restore <backup>    Restore a data-dir copy with its recovery phrase (stdin), --code <code> or --own-keys
  pair [<code>]       Show a code to add a device, or join with one (--host <host>, --discard-local, --restore-keys, --stop-waiting)
  delete              Permanently delete a memory, session or project everywhere (--memory <id> | --session <id> | --project <path>, --yes; --status <id>)
";

struct Case {
    args: &'static [&'static str],
    code: i32,
    stdout: &'static str,
    stderr: &'static str,
}

const CASES: &[Case] = &[
    Case {
        args: &[],
        code: 0,
        stdout: HELP,
        stderr: "",
    },
    Case {
        args: &["no-such-command"],
        code: 0,
        stdout: HELP,
        stderr: "",
    },
    Case {
        args: &["watch"],
        code: 0,
        stdout: "",
        stderr: "watch is deprecated \u{2014} the daemon handles file watching automatically\n",
    },
    Case {
        args: &["sync"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb sync <peer-host>\n",
    },
    Case {
        args: &["sync-trust"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb sync-trust <host>\n",
    },
    Case {
        args: &["backup"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb backup <dest>\nWrites a copy of the data dir to <dest>, a directory that must not exist yet, while the daemon keeps running; `sb restore <dest>` restores it.\n",
    },
    Case {
        args: &["backup", "--help"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb backup <dest>\nWrites a copy of the data dir to <dest>, a directory that must not exist yet, while the daemon keeps running; `sb restore <dest>` restores it.\n",
    },
    Case {
        args: &["backup", "/tmp/b1", "/tmp/b2"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb backup <dest>\nWrites a copy of the data dir to <dest>, a directory that must not exist yet, while the daemon keeps running; `sb restore <dest>` restores it.\n",
    },
    Case {
        args: &["recall"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb recall <query>\n",
    },
    Case {
        args: &["remember"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb remember <text>\n",
    },
    Case {
        args: &["reingest", "--clean"],
        code: 1,
        stdout: "",
        stderr: "error: --clean was removed: raw ids come from the transcript, so deleting raws before a re-ingest would delete them on every peer for good\n",
    },
    Case {
        args: &["redact"],
        code: 1,
        stdout: "",
        stderr: "error: usage: sb redact --dry-run (the daemon redacts stored content by itself when it starts)\n",
    },
    Case {
        args: &["consolidate", "--guard", "bogus"],
        code: 1,
        stdout: "",
        stderr: "error: unknown --guard \"bogus\", expected none or retry\n",
    },
    Case {
        args: &["consolidate"],
        code: 1,
        stdout: "",
        stderr: "error: no LLM endpoint configured; pass --llm-url or add an [llm] section to ~/.second-brain/config.toml\n",
    },
    Case {
        args: &["daily-pipeline"],
        code: 0,
        stdout: "=== daily pipeline ===\n\n[1/1] skipping consolidation: no LLM endpoint configured; pass --llm-url or add an [llm] section to ~/.second-brain/config.toml\n\n=== pipeline complete ===\n",
        stderr: "",
    },
];

#[test]
fn every_usage_and_dispatch_error_prints_exactly_as_before() {
    for case in CASES {
        let home = tempfile::tempdir().unwrap();
        let output = run_sb(home.path(), case.args);
        let stdout = String::from_utf8_lossy(&output.stdout);
        let stderr = String::from_utf8_lossy(&output.stderr);
        assert_eq!(output.status.code(), Some(case.code), "{:?}", case.args);
        assert_eq!(stdout, case.stdout, "stdout of {:?}", case.args);
        assert_eq!(stderr, case.stderr, "stderr of {:?}", case.args);
    }
}

fn sb_with_config(config: &str, args: &[&str]) -> Output {
    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();
    std::fs::write(data_dir.join("config.toml"), config).unwrap();
    run_sb(home.path(), args)
}

fn run_sb(home: &Path, args: &[&str]) -> Output {
    Command::new(env!("CARGO_BIN_EXE_sb"))
        .args(args)
        .env("HOME", home)
        .env("SECOND_BRAIN_API", "http://127.0.0.1:9")
        .env("SECOND_BRAIN_BIND", "127.0.0.1:9")
        .env_remove("RUST_LOG")
        .output()
        .unwrap()
}

const LLM_CONFIG: &str = "[llm]\nendpoint = \"http://llm.test:1\"\nmodel = \"config-model\"\n";

#[test]
fn consolidate_with_an_llm_section_gets_past_the_endpoint_check() {
    let output = sb_with_config(LLM_CONFIG, &["consolidate"]);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(1), "{stderr}");
    assert!(!stderr.contains("no LLM endpoint configured"), "{stderr}");
    assert!(stderr.contains("/v1/consolidate/batch"), "{stderr}");
}

#[test]
fn consolidate_with_llm_url_ignores_an_unusable_config() {
    let output = sb_with_config("[llm\n", &["consolidate", "--llm-url", "http://llm.test:1"]);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(1), "{stderr}");
    assert!(!stderr.contains("config.toml unusable"), "{stderr}");
    assert!(stderr.contains("/v1/consolidate/batch"), "{stderr}");
}

#[test]
fn consolidate_reports_an_unusable_config_on_one_line() {
    let output = sb_with_config("[llm\n", &["consolidate"]);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(output.status.code(), Some(1), "{stderr}");
    assert!(output.stdout.is_empty());
    assert!(
        stderr.starts_with("error: config.toml unusable: "),
        "{stderr}"
    );
    assert_eq!(stderr.matches('\n').count(), 1, "{stderr}");
}

#[test]
fn daily_pipeline_with_an_llm_section_runs_the_consolidate_step() {
    let output = sb_with_config(LLM_CONFIG, &["daily-pipeline"]);
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(output.status.code(), Some(0), "{stdout}");
    assert!(
        stdout.contains("[1/1] consolidating up to 200 memories..."),
        "{stdout}"
    );
    assert!(
        stdout.contains("consolidation failed (non-fatal)"),
        "{stdout}"
    );
}