Skip to main content

memory/
index.rs

1//! The memory index an agent session starts with: one line per memory
2//! (id, title, and its one-line hook), bounded in lines and bytes, so the
3//! agent knows what it can recall without reading every memory.
4
5use crate::Memory;
6
7/// Memories the index lists at most.
8pub const INDEX_LINES: usize = 40;
9/// The index's size at most, in bytes.
10pub const INDEX_BYTES: usize = 4096;
11/// One line's size at most, in characters.
12const LINE_CHARS: usize = 160;
13
14/// What the index says before its lines.
15pub const INDEX_HEAD: &str = "Dreamer memory: notes kept from earlier sessions for this user, \
16this host, this project, and this session (newest first: id, title, and what it is about). \
17Read one in full with memory_recall, and keep a fact worth having in a later session with \
18memory_remember (from a shell: `dream memory recall WORDS`, `dream memory remember`).";
19
20fn line(m: &Memory) -> String {
21    let title = m.title.trim();
22    let hook = m.description.trim();
23    let l = if hook.is_empty() || hook == title {
24        format!("- {}: {title}", m.id)
25    } else {
26        format!("- {}: {title} — {hook}", m.id)
27    };
28    let l = l.replace(['\n', '\r'], " ");
29    if l.chars().count() > LINE_CHARS {
30        l.chars().take(LINE_CHARS - 1).collect::<String>() + "…"
31    } else {
32        l
33    }
34}
35
36/// The index of `items` (in the order given, newest first), or `None` when
37/// there are none. At most [`INDEX_LINES`] lines and [`INDEX_BYTES`]
38/// bytes; the rest are counted in a last line.
39pub fn index(items: &[Memory]) -> Option<String> {
40    if items.is_empty() {
41        return None;
42    }
43    let mut out = String::from(INDEX_HEAD);
44    let mut listed = 0;
45    for m in items.iter().take(INDEX_LINES) {
46        let l = line(m);
47        // Room is kept for the last line.
48        if out.len() + 1 + l.len() > INDEX_BYTES - 80 {
49            break;
50        }
51        out.push('\n');
52        out.push_str(&l);
53        listed += 1;
54    }
55    let rest = items.len() - listed;
56    if rest > 0 {
57        out.push_str(&format!(
58            "\n({rest} more not listed; memory_recall finds them.)"
59        ));
60    }
61    Some(out)
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use crate::{Kind, Scope};
68
69    fn mem(i: usize, title: &str, hook: &str) -> Memory {
70        Memory {
71            id: format!("project/m{i}"),
72            scope: Scope::Project,
73            kind: Kind::Project,
74            title: title.into(),
75            description: hook.into(),
76            text: String::new(),
77            links: Vec::new(),
78            created_unix_ms: 0,
79            updated_unix_ms: 0,
80            path: None,
81            score: None,
82        }
83    }
84
85    #[test]
86    fn the_index_is_bounded_and_counts_the_rest() {
87        assert_eq!(index(&[]), None);
88        let one = index(&[mem(1, "Port", "Staging listens on 8461")]).expect("index");
89        assert!(
90            one.ends_with("\n- project/m1: Port — Staging listens on 8461"),
91            "{one}"
92        );
93        let same = index(&[mem(1, "Port", "Port")]).expect("index");
94        assert!(same.ends_with("\n- project/m1: Port"), "{same}");
95
96        let many: Vec<Memory> = (0..100).map(|i| mem(i, "T", "h")).collect();
97        let text = index(&many).expect("index");
98        assert_eq!(
99            text.lines().filter(|l| l.starts_with("- ")).count(),
100            INDEX_LINES
101        );
102        assert!(
103            text.ends_with("(60 more not listed; memory_recall finds them.)"),
104            "{text}"
105        );
106
107        let long: Vec<Memory> = (0..40).map(|i| mem(i, &"x".repeat(500), "h")).collect();
108        let text = index(&long).expect("index");
109        assert!(text.len() <= INDEX_BYTES, "{}", text.len());
110        assert!(
111            text.lines()
112                .filter(|l| l.starts_with("- "))
113                .all(|l| l.chars().count() <= LINE_CHARS)
114        );
115        assert!(text.contains("more not listed"));
116    }
117}