second-brain-cli 0.13.1

Memory layer for AI coding agents: ingest, recall, and sync across machines
use std::time::Duration;

use anyhow::{Context, Result};
use serde_json::{Value, json};

use crate::api;

/// Longer than the daemon's own wait for the index drain, so its reply,
/// including a drain that is still running, always arrives.
const REPLY_WAIT: Duration = Duration::from_secs(660);

const USAGE: &str = "usage: sb delete (--memory <id> | --session <id> | --project <path>) [--yes]\n       sb delete --status <delete id or target>";

#[derive(Debug, PartialEq, Eq)]
pub(crate) struct DeleteArgs {
    scope: &'static str,
    target: String,
    yes: bool,
}

impl DeleteArgs {
    pub(crate) fn parse(args: &[String]) -> Result<DeleteArgs> {
        let mut scope: Option<(&'static str, String)> = None;
        let mut yes = false;
        let mut words = args.iter();
        while let Some(flag) = words.next() {
            let name = match flag.as_str() {
                "--yes" => {
                    yes = true;
                    continue;
                }
                "--memory" => "memory",
                "--session" => "session",
                "--project" => "project",
                other => anyhow::bail!("unexpected argument {other:?}\n{USAGE}"),
            };
            let value = words
                .next()
                .with_context(|| format!("{flag} needs a value\n{USAGE}"))?;
            if scope.replace((name, value.clone())).is_some() {
                anyhow::bail!("pass exactly one of --memory, --session, --project\n{USAGE}");
            }
        }
        let (scope, target) = scope.with_context(|| format!("name what to delete\n{USAGE}"))?;
        Ok(DeleteArgs { scope, target, yes })
    }

    fn body(&self) -> Value {
        json!({ self.scope: self.target, "dry_run": !self.yes })
    }
}

/// The delete `--status` asks about, when it is the only flag.
fn status_key(args: &[String]) -> Option<Result<String>> {
    if !args.iter().any(|a| a == "--status") {
        return None;
    }
    Some(match args {
        [flag, key] if flag == "--status" => Ok(key.clone()),
        _ => Err(anyhow::anyhow!(
            "--status takes one delete id or target and no other flag\n{USAGE}"
        )),
    })
}

pub(crate) fn cmd_delete(args: &[String]) -> Result<()> {
    if let Some(key) = status_key(args) {
        return cmd_delete_status(&key?);
    }
    let args = DeleteArgs::parse(args)?;
    let client = api::client(REPLY_WAIT)?;
    let resp = api::daemon_ok(
        client
            .post(format!("{}/v1/delete", api::base_url()))
            .json(&args.body())
            .send()
            .context("daemon not reachable; is it running?")?,
    )
    .context("delete request failed")?;
    let body: Value = resp.json().context("reading the daemon's delete answer")?;
    println!("{}", render(&body));
    Ok(())
}

fn cmd_delete_status(key: &str) -> Result<()> {
    let client = api::client(Duration::from_secs(30))?;
    let resp = api::daemon_ok(
        client
            .get(status_url(&api::base_url(), key)?)
            .send()
            .context("daemon not reachable; is it running?")?,
    )
    .context("delete status request failed")?;
    let body: Value = resp.json().context("reading the daemon's delete status")?;
    println!("{}", render_status(&body));
    Ok(())
}

/// The key as one path segment, so a project directory's slashes survive.
fn status_url(base: &str, key: &str) -> Result<reqwest::Url> {
    let mut url = reqwest::Url::parse(base).with_context(|| format!("bad daemon url {base}"))?;
    url.path_segments_mut()
        .map_err(|()| anyhow::anyhow!("bad daemon url {base}"))?
        .pop_if_empty()
        .extend(["v1", "delete", key]);
    Ok(url)
}

fn render_status(body: &Value) -> String {
    let mut text = format!(
        "Delete {} of {} {}, sync log seq {}",
        body["id"].as_str().unwrap_or(""),
        body["scope"].as_str().unwrap_or("target"),
        body["target"].as_str().unwrap_or(""),
        count(body, "seq"),
    );
    let peers = body["peers"].as_array().map(Vec::as_slice).unwrap_or(&[]);
    if peers.is_empty() {
        text.push_str("\nNo synced machine is known here, so none has to acknowledge it.");
        return text;
    }
    let (acked, pending): (Vec<&Value>, Vec<&Value>) = peers
        .iter()
        .partition(|p| p["acked"].as_bool() == Some(true));
    let describe = |p: &&Value| {
        let name = p["peer_id"].as_str().unwrap_or("?");
        let seq = match p["acked_seq"].as_u64() {
            Some(seq) => format!("acked seq {seq}"),
            None => "never acked".to_string(),
        };
        let silent = if p["live"].as_bool() == Some(false) {
            ", not live"
        } else {
            ""
        };
        format!("{name} ({seq}{silent})")
    };
    for (label, group) in [("acknowledged", acked), ("pending", pending)] {
        if !group.is_empty() {
            let names: Vec<String> = group.iter().map(describe).collect();
            text.push_str(&format!("\n{label}: {}", names.join(", ")));
        }
    }
    text
}

fn count(value: &Value, key: &str) -> u64 {
    value[key].as_u64().unwrap_or(0)
}

fn render(body: &Value) -> String {
    let dry_run = body["dry_run"].as_bool().unwrap_or(false);
    let scope = body["scope"].as_str().unwrap_or("target");
    let target = body["target"].as_str().unwrap_or("");
    let removed = &body["removed"];
    let layers = &body["layers"];
    let (verb, from) = if dry_run {
        ("Would delete", "would be removed")
    } else {
        ("Deleted", "removed")
    };
    let mut text = format!(
        "{verb} {scope} {target}: {} memories, {} distillates, {} chunks, {} relations, {} markers, {} conversations\n{from} from vector {}, bm25 {}, raw index {}, cold {}, archive {}, sync log {}",
        count(removed, "memories"),
        count(removed, "distillates"),
        count(removed, "chunks"),
        count(removed, "relations"),
        count(removed, "markers"),
        count(removed, "conversations"),
        count(layers, "vector") + count(layers, "chunk_vectors"),
        count(layers, "bm25"),
        count(layers, "raw_index"),
        count(layers, "cold_records"),
        count(layers, "archive"),
        count(layers, "sync_log"),
    );
    if let Some(warnings) = body["warnings"].as_array() {
        for warning in warnings.iter().filter_map(Value::as_str) {
            text.push_str(&format!("\nwarning: {warning}"));
        }
    }
    if dry_run {
        text.push_str(
            "\nNothing was deleted. Re-run with --yes to delete it from every synced machine.",
        );
    } else if body["drained"].as_bool() == Some(false) {
        text.push_str("\nSearch index removal is still pending and finishes in the background.");
    }
    if let Some(id) = body["delete_id"].as_str() {
        text.push_str(&format!(
            "\nSee which direct peers acknowledged it: sb delete --status {id}"
        ));
    }
    text
}

#[cfg(test)]
mod tests {
    use super::*;

    fn words(args: &[&str]) -> Vec<String> {
        args.iter().map(|a| a.to_string()).collect()
    }

    fn reply(dry_run: bool) -> Value {
        json!({
            "scope": "session", "target": "s1", "dry_run": dry_run,
            "removed": {"memories": 3, "distillates": 1, "chunks": 4, "relations": 2, "markers": 2, "conversations": 1},
            "layers": {"vector": 2, "chunk_vectors": 1, "bm25": 3, "raw_index": 5, "cold_records": 0, "archive": 1, "sync_log": 7},
            "drained": true,
            "warnings": []
        })
    }

    #[test]
    fn each_scope_parses_and_defaults_to_a_dry_run() {
        for (flag, scope) in [
            ("--memory", "memory"),
            ("--session", "session"),
            ("--project", "project"),
        ] {
            let parsed = DeleteArgs::parse(&words(&[flag, "x"])).unwrap();
            assert_eq!(
                parsed,
                DeleteArgs {
                    scope,
                    target: "x".to_string(),
                    yes: false
                }
            );
            assert_eq!(parsed.body(), json!({ scope: "x", "dry_run": true }));
        }
    }

    #[test]
    fn yes_sends_a_real_delete() {
        let parsed = DeleteArgs::parse(&words(&["--yes", "--session", "s1"])).unwrap();
        assert!(parsed.yes);
        assert_eq!(parsed.body(), json!({"session": "s1", "dry_run": false}));
    }

    #[test]
    fn a_missing_two_or_unknown_scope_is_an_error_with_the_usage() {
        for args in [
            words(&[]),
            words(&["--yes"]),
            words(&["--memory", "a", "--session", "b"]),
            words(&["--memory", "a", "--memory", "b"]),
            words(&["--memory"]),
            words(&["--bogus", "a"]),
        ] {
            let err = DeleteArgs::parse(&args).unwrap_err().to_string();
            assert!(err.contains(USAGE), "{args:?}: {err}");
        }
    }

    #[test]
    fn a_dry_run_says_nothing_was_deleted() {
        let text = render(&reply(true));
        assert!(text.starts_with("Would delete session s1: 3 memories, 1 distillates"));
        assert!(text.contains(
            "would be removed from vector 3, bm25 3, raw index 5, cold 0, archive 1, sync log 7"
        ));
        assert!(text.ends_with(
            "Nothing was deleted. Re-run with --yes to delete it from every synced machine."
        ));
    }

    #[test]
    fn a_real_delete_prints_the_counts_only() {
        let text = render(&reply(false));
        assert!(text.starts_with("Deleted session s1: 3 memories"));
        assert!(text.contains("\nremoved from vector 3"));
        assert!(!text.contains("Nothing was deleted"));
        assert!(!text.contains("pending"));
    }

    #[test]
    fn status_takes_one_key_and_no_other_flag() {
        assert_eq!(
            status_key(&words(&["--status", "d1"])).unwrap().unwrap(),
            "d1"
        );
        assert!(status_key(&words(&["--memory", "a"])).is_none());
        for args in [
            words(&["--status"]),
            words(&["--status", "d1", "--yes"]),
            words(&["--memory", "a", "--status", "d1"]),
        ] {
            let err = status_key(&args).unwrap().unwrap_err().to_string();
            assert!(err.contains(USAGE), "{args:?}: {err}");
        }
    }

    #[test]
    fn a_project_path_status_key_stays_one_segment() {
        assert_eq!(
            status_url("http://127.0.0.1:7200", "/srv/garden")
                .unwrap()
                .as_str(),
            "http://127.0.0.1:7200/v1/delete/%2Fsrv%2Fgarden"
        );
    }

    #[test]
    fn a_real_delete_points_at_its_status() {
        let mut body = reply(false);
        body["delete_id"] = json!("d1");
        assert!(render(&body).ends_with("sb delete --status d1"));
        assert!(!render(&reply(true)).contains("--status"));
    }

    #[test]
    fn the_status_lists_acked_and_pending_peers() {
        let text = render_status(&json!({
            "id": "d1", "scope": "session", "target": "s1", "seq": 42, "deleted_at": 0,
            "peers": [
                {"peer_id": "pi", "acked_seq": 50, "acked": true, "live": true},
                {"peer_id": "mac", "acked_seq": 40, "acked": false, "live": true},
                {"peer_id": "laptop", "acked_seq": null, "acked": false, "live": false}
            ]
        }));
        assert_eq!(
            text,
            "Delete d1 of session s1, sync log seq 42\n\
             acknowledged: pi (acked seq 50)\n\
             pending: mac (acked seq 40), laptop (never acked, not live)"
        );
        let alone = render_status(
            &json!({"id": "d1", "scope": "memory", "target": "m1", "seq": 3, "peers": []}),
        );
        assert!(alone.ends_with("none has to acknowledge it."));
    }

    #[test]
    fn warnings_and_an_undrained_index_are_shown() {
        let mut body = reply(false);
        body["drained"] = json!(false);
        body["warnings"] = json!(["cold storage was not checked"]);
        let text = render(&body);
        assert!(text.contains("warning: cold storage was not checked"));
        assert!(text.contains("Search index removal is still pending"));
    }
}