second-brain-cli 0.13.5

Memory layer for AI coding agents: ingest, recall, and sync across machines
use chrono::DateTime;
use serde_json::{Value, json};

use super::context::{self, MAX_CONTEXT_CHARS};
use super::{daemon, project};

const MIN_PROMPT_CHARS: usize = 20;

const MAX_QUERY_CHARS: usize = 1000;

const MAX_MEMORIES: usize = 3;

/// The daemon embeds and reranks only on sessions already loaded and free
/// within it, and starts no rerank past it, but a rerank it starts runs to
/// completion, so a late one can still answer after the hook's daemon
/// timeout. An answer without the rerank has no bar, which injects nothing.
const RECALL_BUDGET_MS: u64 = 1200;

/// evals/rerank-cost-curve.md: fuse_top 5 with 512-char documents reranks
/// about 4x faster than fuse_top 10 with 1024, which a per-prompt hook
/// needs; one wide pass, not a project pass first, saves a second rerank.
const RERANK_TOP: usize = 5;
const RERANK_DOC_CHARS: usize = 512;

const HEADER: &str = "Memories from past sessions that second-brain matched to this prompt; \
                      they may be stale, so verify them before relying on them:";

/// Injects what recall ranks at or above the bar the daemon reports it
/// applied; an answer with no bar was not gated, so it injects nothing, as
/// does every other doubt. Recall leaves access counts alone, because
/// ranking blends them in and an injection is not a use, and leaves out the
/// session's own memories, which the agent already holds.
pub(super) fn run(event: &'static str, input: &Value) -> Option<Value> {
    let prompt = input["prompt"].as_str()?.trim();
    if is_slash_command(prompt) || prompt.chars().count() < MIN_PROMPT_CHARS {
        return None;
    }
    let project = project::of(input)?;
    let reply = daemon::post(
        "/v1/recall",
        &json!({
            "query": prompt.chars().take(MAX_QUERY_CHARS).collect::<String>(),
            "limit": MAX_MEMORIES,
            "current_project": project,
            "record_access": false,
            "exclude_session": input["session_id"],
            "budget_ms": RECALL_BUDGET_MS,
            "rerank_top": RERANK_TOP,
            "rerank_doc_chars": RERANK_DOC_CHARS,
            "project_pass": false,
        }),
    )?;
    if !reply["degraded"].is_null() {
        return None;
    }
    let bar = reply["abstain_bar"].as_f64()?;
    let lines: Vec<(String, String)> = reply["memories"]
        .as_array()?
        .iter()
        .filter(|memory| memory["relevance"].as_f64().is_some_and(|r| r >= bar))
        .take(MAX_MEMORIES)
        .filter_map(memory_line)
        .collect();
    let room = MAX_CONTEXT_CHARS - HEADER.chars().count();
    let shown: Vec<String> = context::fit(room, &lines).into_iter().flatten().collect();
    if shown.is_empty() {
        return None;
    }
    let text = std::iter::once(HEADER.to_string())
        .chain(shown)
        .collect::<Vec<_>>()
        .join("\n");
    Some(context::reply(event, text))
}

fn memory_line(memory: &Value) -> Option<(String, String)> {
    let id = memory["id"].as_str().filter(|id| !id.is_empty())?;
    let content = context::one_line(memory["content"].as_str()?);
    if content.is_empty() {
        return None;
    }
    let project = memory["project_path"]
        .as_str()
        .filter(|project| !project.is_empty())
        .unwrap_or("no project");
    let date = memory["session_at"]
        .as_str()
        .and_then(|at| DateTime::parse_from_rfc3339(at).ok())
        .map_or_else(
            || "date unknown".to_string(),
            |at| at.date_naive().to_string(),
        );
    Some((format!("- [{id}] ({project}, session {date}) "), content))
}

/// `/name args`, as opposed to a prompt that opens with an absolute path.
fn is_slash_command(prompt: &str) -> bool {
    prompt
        .split_whitespace()
        .next()
        .and_then(|word| word.strip_prefix('/'))
        .is_some_and(|name| !name.contains('/'))
}