second-brain-cli 0.12.0

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 queued_reason(&body).is_some() {
        eprintln!("{INGEST_QUEUED}");
        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";

/// 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")
    })
}

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()?;
    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);
    }
}