second-brain-cli 0.13.5

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

use serde_json::Value;

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

const NOTES: &str = "10";

const MAX_ENTRIES: usize = 5;

/// Agents pass this id to the `note` tool mid-run, and nothing else tells
/// them their session id.
const ID_LINE: &str = "This session's id for second-brain notes:";

const HEADER: &str = "Items waiting on the user and open items from this project's latest \
                      second-brain session notes; they may be done by now, so check first:";

/// Waiting-on-user entries come first so a long open-items list cannot
/// crowd them out of `MAX_ENTRIES`.
const SECTIONS: [(&str, &str); 2] = [
    ("blocked_on_user", "Waiting on the user:"),
    ("open_items", "Open items:"),
];

/// Names the session, then injects sibling notes in up to half the room and
/// what the project's latest notes left open in the rest, for a new session
/// or a subagent alike; every doubt leaves its section out. The two daemon
/// calls run side by side so a hung daemon costs one timeout, not two.
pub(super) fn run(event: &'static str, input: &Value) -> Option<Value> {
    let id_line = input["session_id"]
        .as_str()
        .filter(|id| !id.is_empty())
        .map(|id| format!("{ID_LINE} {id}"));
    let room = MAX_CONTEXT_CHARS
        .saturating_sub(id_line.as_ref().map_or(0, |line| line.chars().count() + 1));
    let (siblings, open) = std::thread::scope(|scope| {
        let open = scope.spawn(|| open_entries(input));
        let siblings = siblings::section(input, room / 2, SystemTime::now());
        (siblings, open.join().ok().flatten())
    });
    let room = room.saturating_sub(siblings.as_ref().map_or(0, |text| text.chars().count() + 1));
    let open = open.and_then(|entries| render(&entries, room));
    let text = [id_line, siblings, open]
        .into_iter()
        .flatten()
        .collect::<Vec<_>>()
        .join("\n");
    (!text.is_empty()).then(|| context::reply(event, text))
}

fn open_entries(input: &Value) -> Option<[Vec<String>; 2]> {
    let project = project::of(input)?;
    let reply = daemon::get("/v1/notes", &[("project", &project), ("limit", NOTES)])?;
    Some(entries(reply["notes"].as_array()?))
}

fn render(entries: &[Vec<String>; 2], room: usize) -> Option<String> {
    let headings = SECTIONS
        .iter()
        .zip(entries)
        .filter(|(_, list)| !list.is_empty())
        .map(|((_, heading), _)| heading.chars().count() + 1)
        .sum::<usize>();
    let room = room.saturating_sub(HEADER.chars().count() + headings);
    let lines: Vec<(String, String)> = entries
        .iter()
        .flatten()
        .map(|entry| ("- ".to_string(), entry.clone()))
        .collect();
    let mut fitted = context::fit(room, &lines).into_iter();
    let mut text = HEADER.to_string();
    let mut shown_any = false;
    for ((_, heading), list) in SECTIONS.iter().zip(entries) {
        let shown: Vec<String> = fitted.by_ref().take(list.len()).flatten().collect();
        if shown.is_empty() {
            continue;
        }
        shown_any = true;
        text.push('\n');
        text.push_str(heading);
        for line in shown {
            text.push('\n');
            text.push_str(&line);
        }
    }
    shown_any.then_some(text)
}

/// Notes arrive newest first; each section takes its field from every note
/// in that order, skipping exact repeats, until `MAX_ENTRIES` are taken.
fn entries(notes: &[Value]) -> [Vec<String>; 2] {
    let mut seen = HashSet::new();
    let mut left = MAX_ENTRIES;
    SECTIONS.map(|(field, _)| {
        let list: Vec<String> = notes
            .iter()
            .filter_map(|note| note[field].as_array())
            .flatten()
            .filter_map(Value::as_str)
            .map(context::one_line)
            .filter(|entry| !entry.is_empty() && seen.insert(entry.clone()))
            .take(left)
            .collect();
        left -= list.len();
        list
    })
}