second-brain-cli 0.13.3

Memory layer for AI coding agents: ingest, recall, and sync across machines
use anyhow::Result;

use crate::api;

pub(crate) fn cmd_ingest(_source: &str) -> Result<()> {
    let api = api::base_url();
    let client = api::client(std::time::Duration::from_secs(600))?;

    eprintln!("ingesting via daemon...");

    let resp = client
        .post(format!("{api}/v1/ingest"))
        .json(&serde_json::json!({}))
        .send()?;

    if !resp.status().is_success() {
        anyhow::bail!(
            "ingest failed: {} {}",
            resp.status(),
            resp.text().unwrap_or_default()
        );
    }

    let body: serde_json::Value = resp.json()?;
    if let Some(held) = not_run(&body) {
        eprintln!("{held}");
        return Ok(());
    }
    eprintln!(
        "ingested: {} memories, {} entities, {} conversations ({} dupes, {} unchanged, {} errors)",
        body["new_memories"],
        body["new_entities"],
        body["new_conversations"],
        body["skipped_dupes"],
        body["unchanged"],
        body["errors"],
    );

    Ok(())
}

pub(crate) const INGEST_QUEUED: &str =
    "ingest queued: store maintenance is running; it runs when maintenance finishes";

pub(crate) const INGEST_DEFERRED: &str = "ingest deferred: this device waits for its first sync \
     from the device that paired it; join with `sb pair <code> --host <host>` if it has not \
     joined yet, or run `sb pair --stop-waiting` to ingest without it";

/// The daemon answers a write with `queued: true` while store maintenance
/// runs; the body then holds no stored id or counts.
pub(crate) fn queued_reason(body: &serde_json::Value) -> Option<&str> {
    (body["queued"] == serde_json::Value::Bool(true)).then(|| {
        body["reason"]
            .as_str()
            .unwrap_or("store maintenance is running")
    })
}

/// Why an ingest answer carries no counts: deferred until a paired device's
/// first sync, or queued behind store maintenance.
pub(crate) fn not_run(body: &serde_json::Value) -> Option<&'static str> {
    if body["deferred"] == serde_json::Value::Bool(true) {
        Some(INGEST_DEFERRED)
    } else if queued_reason(body).is_some() {
        Some(INGEST_QUEUED)
    } else {
        None
    }
}

pub(crate) fn cmd_reingest() -> Result<()> {
    let api = api::base_url();
    let client = api::client(std::time::Duration::from_secs(600))?;

    eprintln!("reingest via daemon...");

    let resp = client
        .post(format!("{api}/v1/reingest"))
        .json(&serde_json::json!({}))
        .send()?;

    if !resp.status().is_success() {
        anyhow::bail!(
            "reingest failed: {} {}",
            resp.status(),
            resp.text().unwrap_or_default()
        );
    }

    let body: serde_json::Value = resp.json()?;
    if let Some(held) = not_run(&body) {
        eprintln!("{held}");
        return Ok(());
    }
    eprintln!("cleared {} ingest log entries", body["cleared_log"]);
    eprintln!(
        "ingested: {} memories, {} entities, {} conversations ({} dupes, {} unchanged, {} errors)",
        body["new_memories"],
        body["new_entities"],
        body["new_conversations"],
        body["skipped_dupes"],
        body["unchanged"],
        body["errors"],
    );

    Ok(())
}

#[cfg(test)]
mod queued_tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn a_queued_body_is_recognised_and_a_stored_one_is_not() {
        let queued = json!({"queued": true, "reason": "store maintenance is running", "id": "abc"});
        assert_eq!(queued_reason(&queued), Some("store maintenance is running"));
        assert!(queued_reason(&json!({"queued": true})).is_some());
        assert_eq!(queued_reason(&json!({"id": "abc"})), None);
        assert_eq!(queued_reason(&json!({"queued": false})), None);
    }

    #[test]
    fn a_deferred_answer_names_the_first_sync_and_is_not_read_as_queued() {
        let deferred = json!({"deferred": true, "new_memories": 0, "files_processed": 0});
        assert_eq!(not_run(&deferred), Some(INGEST_DEFERRED));
        assert_eq!(queued_reason(&deferred), None);
        assert!(INGEST_DEFERRED.contains("first sync"));
        assert!(INGEST_DEFERRED.contains("paired"));
        assert!(INGEST_DEFERRED.contains("`sb pair --stop-waiting`"));
    }

    #[test]
    fn a_queued_answer_says_queued_and_counts_say_nothing() {
        assert_eq!(
            not_run(&json!({"queued": true, "reason": "store maintenance is running"})),
            Some(INGEST_QUEUED)
        );
        assert_eq!(
            not_run(&json!({"new_memories": 3, "files_processed": 2})),
            None
        );
        assert_eq!(
            not_run(&json!({"deferred": false, "new_memories": 3})),
            None
        );
    }
}