second-brain-cli 0.13.5

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

/// Injected context reaches the model with every prompt or session it is
/// attached to, so each hook's text stays within this many characters.
pub(super) const MAX_CONTEXT_CHARS: usize = 1500;

const ELLIPSIS: char = '…';

pub(super) fn reply(event: &str, text: String) -> Value {
    json!({
        "hookSpecificOutput": {
            "hookEventName": event,
            "additionalContext": text,
        }
    })
}

pub(super) fn one_line(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// Fits each `(prefix, body)` line, plus the newline before it, into `room`
/// characters by cutting `body` with an ellipsis. Shorter lines are fitted
/// first to an even share of what is left, so the room they do not use goes
/// to the longer ones. A line with no room for its body is dropped as `None`.
/// Lines come back in their given order.
pub(super) fn fit(room: usize, lines: &[(String, String)]) -> Vec<Option<String>> {
    let mut order: Vec<usize> = (0..lines.len()).collect();
    order.sort_by_key(|&i| lines[i].0.chars().count() + lines[i].1.chars().count());
    let mut left = room;
    let mut fitted = vec![None; lines.len()];
    for (n, &i) in order.iter().enumerate() {
        let (prefix, body) = &lines[i];
        let share = left / (lines.len() - n);
        let line = cut(prefix, body, share.saturating_sub(1));
        if let Some(line) = &line {
            left -= line.chars().count() + 1;
        }
        fitted[i] = line;
    }
    fitted
}

fn cut(prefix: &str, body: &str, room: usize) -> Option<String> {
    let fixed = prefix.chars().count();
    if fixed + body.chars().count() <= room {
        return Some(format!("{prefix}{body}"));
    }
    let keep = room.checked_sub(fixed + 1).filter(|&keep| keep > 0)?;
    let kept: String = body.chars().take(keep).collect();
    Some(format!("{prefix}{}{ELLIPSIS}", kept.trim_end()))
}

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

    fn line(prefix: &str, body: &str) -> (String, String) {
        (prefix.to_string(), body.to_string())
    }

    #[test]
    fn short_lines_are_kept_whole() {
        let lines = [line("- ", "one"), line("- ", "two")];
        assert_eq!(
            fit(100, &lines),
            [Some("- one".to_string()), Some("- two".to_string())]
        );
    }

    #[test]
    fn long_bodies_share_the_room_and_end_in_an_ellipsis() {
        let lines = [line("- ", &"a".repeat(100)), line("- ", &"b".repeat(100))];
        let fitted = fit(40, &lines);
        let used: usize = fitted.iter().flatten().map(|l| l.chars().count() + 1).sum();
        assert!(used <= 40, "{fitted:?}");
        assert_eq!(
            fitted[0].as_deref(),
            Some(&*format!("- {}…", "a".repeat(16)))
        );
        assert_eq!(
            fitted[1].as_deref(),
            Some(&*format!("- {}…", "b".repeat(16)))
        );
    }

    #[test]
    fn a_line_without_room_for_its_body_is_dropped_and_its_share_passes_on() {
        let lines = [line(&"p".repeat(30), "body"), line("- ", &"b".repeat(100))];
        let fitted = fit(40, &lines);
        assert_eq!(fitted[0], None);
        assert_eq!(
            fitted[1].as_deref(),
            Some(&*format!("- {}…", "b".repeat(36)))
        );
    }

    #[test]
    fn room_short_lines_leave_goes_to_a_long_one_before_them() {
        let lines = [
            line("- ", &"a".repeat(1200)),
            line("- ", &"b".repeat(50)),
            line("- ", &"c".repeat(50)),
        ];
        let fitted = fit(1350, &lines);
        assert_eq!(
            fitted,
            [
                Some(format!("- {}", "a".repeat(1200))),
                Some(format!("- {}", "b".repeat(50))),
                Some(format!("- {}", "c".repeat(50))),
            ]
        );
    }

    #[test]
    fn whitespace_collapses_to_single_spaces() {
        assert_eq!(one_line("  a\n\tb   c \n"), "a b c");
    }
}