Skip to main content

memory/
graph.rs

1//! What the database providers (`sqlite`, and `kosmonaut` with its
2//! feature) share: how a memory is keyed and owned, which edges its links
3//! make, how a new or changed memory is filled in, and how recall merges
4//! word matches, neighbours, and vectors. Each provider keeps the same
5//! things its own way; with this they answer alike.
6
7use std::collections::{BTreeMap, BTreeSet, HashMap};
8use std::path::{Path, PathBuf};
9
10use crate::embed::{Embedder, cosine};
11use crate::files::{one_line, slug, title_of};
12use crate::{
13    Change, Context, DEFAULT_LIMIT, Error, Found, MAX_LIMIT, Memory, New, Problem, Scope, search,
14    split_id, time,
15};
16
17/// Recall: a memory one edge from a match scores this, plus 10 for each
18/// further edge, below any word match (every word match scores 1000 or
19/// more; see [`crate::search`]).
20pub(crate) const RELATED_BASE: u32 = 500;
21/// Recall: a memory whose vector is at least this close to the query's
22/// (cosine) is included; its score is the similarity times 400.
23pub(crate) const NEAR: f32 = 0.5;
24
25/// The relations from a memory: to its project, its session, a file, a
26/// pane, and another memory.
27pub(crate) const IN_PROJECT: &str = "IN_PROJECT";
28pub(crate) const IN_SESSION: &str = "IN_SESSION";
29pub(crate) const ABOUT_FILE: &str = "ABOUT_FILE";
30pub(crate) const ABOUT_PANE: &str = "ABOUT_PANE";
31pub(crate) const LINKS_TO: &str = "LINKS_TO";
32
33/// A row a collector kept: what the daemon's collectors write when a
34/// database provider keeps memory, so rows can be found next to the
35/// memories, panes, and sessions they came from.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct CollectorRow {
38    pub collector: String,
39    pub at_unix_ms: u64,
40    /// The pane, as tmux names it (`%3`).
41    pub pane: String,
42    pub session: Option<String>,
43    pub cwd: Option<PathBuf>,
44    pub command: Option<String>,
45    pub fields: Vec<(String, String)>,
46    pub context: Vec<String>,
47}
48
49/// What an agent session came to: one per session, replaced on each write.
50#[derive(Debug, Clone, PartialEq, Eq)]
51pub struct Summary {
52    pub session: String,
53    pub text: String,
54    pub updated_unix_ms: u64,
55}
56
57/// Vectors by memory key.
58pub(crate) type Vectors = HashMap<String, Vec<f32>>;
59
60/// The database key of a memory: scope, owner, and name, which no part
61/// can make ambiguous (none of them holds a NUL).
62pub(crate) fn key(scope: Scope, owner: &str, name: &str) -> String {
63    format!("{}\0{owner}\0{name}", scope.name())
64}
65
66/// The owner a scope's memories are kept under for `cx`: the project root
67/// or the session id; nothing for user and host. The project root is the
68/// real path (symbolic links resolved), so one project is one owner
69/// however a caller names it: `/tmp/app` and `/private/tmp/app` on macOS,
70/// or a shell's path through a link and the process's own working
71/// directory. A root that cannot be resolved is kept as given.
72pub(crate) fn owner(cx: &Context, scope: Scope) -> Result<String, Error> {
73    Ok(match scope {
74        Scope::User | Scope::Host => String::new(),
75        Scope::Project => {
76            let root = crate::project_of(cx)?;
77            std::fs::canonicalize(&root)
78                .unwrap_or(root)
79                .display()
80                .to_string()
81        }
82        Scope::Session => crate::session_of(cx)?.to_owned(),
83    })
84}
85
86/// The scopes a call looks in: the one given, or every one `cx` reaches.
87pub(crate) fn scopes(cx: &Context, scope: Option<Scope>) -> Vec<Scope> {
88    scope.map_or_else(|| crate::reach(cx), |s| vec![s])
89}
90
91/// Newest first, then by id: the order `list` gives.
92pub(crate) fn newest_first(items: &mut [(String, Memory)]) {
93    items.sort_by(|(_, a), (_, b)| {
94        b.updated_unix_ms
95            .cmp(&a.updated_unix_ms)
96            .then(a.id.cmp(&b.id))
97    });
98}
99
100/// The edges a memory should have now: (relation, target). A link that
101/// is another memory's id is an edge to it when `exists` finds its key.
102pub(crate) fn wanted(
103    cx: &Context,
104    scope: Scope,
105    owner: &str,
106    links: &[String],
107    mut exists: impl FnMut(&str) -> Result<bool, Error>,
108) -> Result<BTreeSet<(&'static str, String)>, Error> {
109    let mut out = BTreeSet::new();
110    match scope {
111        Scope::Project => {
112            out.insert((IN_PROJECT, owner.to_owned()));
113        }
114        Scope::Session => {
115            out.insert((IN_SESSION, owner.to_owned()));
116        }
117        Scope::User | Scope::Host => {}
118    }
119    for l in links {
120        let l = l.trim();
121        if l.is_empty() || l.contains("://") {
122            continue;
123        }
124        // Another memory's id, when it names one that exists.
125        if let Ok((s, name)) = split_id(l)
126            && let Ok(o) = self::owner(cx, s)
127        {
128            let target = key(s, &o, name);
129            if exists(&target)? {
130                out.insert((LINKS_TO, target));
131                continue;
132            }
133        }
134        if let Some(pane) = l.strip_prefix("pane:") {
135            out.insert((ABOUT_PANE, pane.trim().to_owned()));
136            continue;
137        }
138        if l.starts_with('%') && l.len() > 1 && l[1..].bytes().all(|b| b.is_ascii_digit()) {
139            out.insert((ABOUT_PANE, l.to_owned()));
140            continue;
141        }
142        // A path; a relative one is the project's, for a project memory.
143        let p = Path::new(l);
144        let path = if p.is_relative() && scope == Scope::Project {
145            Path::new(owner).join(p).display().to_string()
146        } else {
147            l.to_owned()
148        };
149        out.insert((ABOUT_FILE, path));
150    }
151    Ok(out)
152}
153
154/// A new memory as `remember` keeps it, under the first name from its
155/// title that `taken` says is free (`-2`, `-3`, ... after the first).
156/// Returns its key and owner too.
157pub(crate) fn fresh(
158    cx: &Context,
159    new: New,
160    mut taken: impl FnMut(&str) -> Result<bool, Error>,
161) -> Result<(String, String, Memory), Error> {
162    if new.text.trim().is_empty() {
163        return Err(Error::Invalid("a memory needs text".into()));
164    }
165    let owner = owner(cx, new.scope)?;
166    let title = new
167        .title
168        .as_deref()
169        .map(one_line)
170        .filter(|t| !t.is_empty())
171        .unwrap_or_else(|| title_of(&new.text));
172    let description = new
173        .description
174        .as_deref()
175        .map(one_line)
176        .filter(|d| !d.is_empty())
177        .unwrap_or_else(|| title.clone());
178    let base = slug(&title);
179    let mut name = base.clone();
180    for n in 2.. {
181        if !taken(&key(new.scope, &owner, &name))? {
182            break;
183        }
184        name = format!("{base}-{n}");
185    }
186    let now = time::now_ms();
187    let m = Memory {
188        id: format!("{}/{name}", new.scope.name()),
189        scope: new.scope,
190        kind: new.kind,
191        title,
192        description,
193        text: new.text.trim_end().to_owned(),
194        links: new.links,
195        created_unix_ms: now,
196        updated_unix_ms: now,
197        path: None,
198        score: None,
199    };
200    Ok((key(new.scope, &owner, &name), owner, m))
201}
202
203/// The memory with `change` applied, as `update` keeps it.
204pub(crate) fn changed(mut m: Memory, change: Change) -> Result<Memory, Error> {
205    if let Some(t) = change.text {
206        if t.trim().is_empty() {
207            return Err(Error::Invalid("a memory needs text".into()));
208        }
209        m.text = t.trim_end().to_owned();
210    }
211    if let Some(kind) = change.kind {
212        m.kind = kind;
213    }
214    if let Some(t) = change.title.as_deref().map(one_line) {
215        if t.is_empty() {
216            return Err(Error::Invalid("a title cannot be empty".into()));
217        }
218        m.title = t;
219    }
220    if let Some(d) = change.description.as_deref() {
221        m.description = one_line(d);
222    }
223    if let Some(l) = change.links {
224        m.links = l;
225    }
226    m.updated_unix_ms = time::now_ms().max(m.updated_unix_ms);
227    Ok(m)
228}
229
230/// `m` as `put` keeps it, checked, with its key and owner.
231pub(crate) fn placed(cx: &Context, m: &Memory) -> Result<(String, String, Memory), Error> {
232    if m.text.trim().is_empty() {
233        return Err(Error::Invalid("a memory needs text".into()));
234    }
235    let (scope, name) = split_id(&m.id)?;
236    if scope != m.scope {
237        return Err(Error::Invalid(format!(
238            "`{}` is not in the {} scope",
239            m.id,
240            m.scope.name()
241        )));
242    }
243    let owner = owner(cx, scope)?;
244    let mut m = m.clone();
245    m.text = m.text.trim_end().to_owned();
246    m.path = None;
247    m.score = None;
248    Ok((key(scope, &owner, name), owner, m))
249}
250
251/// A relation's target as a person reads it: a memory's id for LINKS_TO.
252pub(crate) fn shown(rel: &str, target: &str) -> String {
253    if rel == LINKS_TO {
254        let mut parts = target.split('\0');
255        let scope = parts.next().unwrap_or_default();
256        let name = parts.nth(1).unwrap_or_default();
257        format!("{scope}/{name}")
258    } else {
259        target.to_owned()
260    }
261}
262
263/// What a memory's vector is made from.
264pub(crate) fn vector_text(m: &Memory) -> String {
265    format!("{}\n{}\n{}", m.title, m.description, m.text)
266}
267
268/// Whether an edge open from `from` and closed at `to` (microseconds;
269/// `None` while open) held at `at`.
270pub(crate) fn held(from: i64, to: Option<i64>, at: i64) -> bool {
271    from <= at && to.is_none_or(|t| t > at)
272}
273
274/// Microseconds, for valid times.
275pub(crate) fn now_us() -> i64 {
276    std::time::SystemTime::now()
277        .duration_since(std::time::UNIX_EPOCH)
278        .map_or(0, |d| i64::try_from(d.as_micros()).unwrap_or(i64::MAX))
279}
280
281/// A time in milliseconds as valid-time microseconds.
282pub(crate) fn ms_to_us(unix_ms: u64) -> i64 {
283    i64::try_from(unix_ms)
284        .unwrap_or(i64::MAX)
285        .saturating_mul(1000)
286}
287
288/// Where recall gets what goes past the words: a provider's store.
289pub(crate) trait Recall {
290    /// Keys of memories one current edge from any of `keys`, with how
291    /// many such edges each has.
292    fn neighbours(&self, keys: &[String]) -> Result<BTreeMap<String, u32>, Error>;
293
294    /// The query's vector and the vectors of `items` from the embedder's
295    /// model, embedding (and keeping) the ones that have none yet.
296    fn vectors(
297        &self,
298        e: &dyn Embedder,
299        query: &str,
300        items: &[(String, Memory)],
301    ) -> Result<(Vec<f32>, Vectors), Error>;
302
303    /// The database, or the server: what a problem names.
304    fn place(&self) -> PathBuf;
305}
306
307/// Recall over `all` (every memory the call reaches, newest first, with
308/// keys): word matches ranked exactly as [`search::rank`] ranks them, then
309/// memories one edge from the best of them, then, with an embedder,
310/// memories near the query in meaning.
311pub(crate) fn recall(
312    store: &dyn Recall,
313    embedder: Option<&dyn Embedder>,
314    all: Vec<(String, Memory)>,
315    query: &str,
316    limit: Option<usize>,
317) -> Result<Found, Error> {
318    let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT);
319    let mut terms = search::words(query);
320    terms.sort();
321    terms.dedup();
322    if terms.is_empty() {
323        let items = all.into_iter().take(limit).map(|(_, m)| m).collect();
324        return Ok(Found {
325            items,
326            problems: Vec::new(),
327        });
328    }
329    let mut problems = Vec::new();
330    // Words first, the same ranking every provider gives.
331    let mut picked: BTreeMap<String, Memory> = BTreeMap::new();
332    for (k, m) in &all {
333        let score = search::score(&terms, m);
334        if score > 0 {
335            let mut m = m.clone();
336            m.score = Some(score);
337            picked.insert(k.clone(), m);
338        }
339    }
340    // Then memories one edge from the best matches.
341    let mut seeds: Vec<(&String, &Memory)> = picked.iter().collect();
342    seeds.sort_by_key(|a| std::cmp::Reverse(a.1.score));
343    let seeds: Vec<String> = seeds
344        .into_iter()
345        .take(limit)
346        .map(|(k, _)| k.clone())
347        .collect();
348    let near = if seeds.is_empty() {
349        BTreeMap::new()
350    } else {
351        store.neighbours(&seeds)?
352    };
353    for (k, m) in &all {
354        if picked.contains_key(k) {
355            continue;
356        }
357        if let Some(n) = near.get(k) {
358            let mut m = m.clone();
359            m.score = Some(RELATED_BASE + 10 * (*n).min(49));
360            picked.insert(k.clone(), m);
361        }
362    }
363    // Then, with an embedder, memories near the query in meaning.
364    if let Some(e) = embedder {
365        let rest: Vec<(String, Memory)> = all
366            .iter()
367            .filter(|(k, _)| !picked.contains_key(k))
368            .cloned()
369            .collect();
370        if !rest.is_empty() {
371            // The words and the graph still answer when the embedder
372            // fails; the reply says why there are no vectors.
373            match store.vectors(e, query, &rest) {
374                Ok((q, have)) => {
375                    for (k, m) in rest {
376                        let sim = have.get(&k).map_or(0.0, |v| cosine(&q, v));
377                        if sim >= NEAR {
378                            let mut m = m;
379                            m.score = Some(((sim * 400.0) as u32).clamp(1, RELATED_BASE - 1));
380                            picked.insert(k, m);
381                        }
382                    }
383                }
384                Err(err) => problems.push(Problem {
385                    path: store.place(),
386                    message: format!("recalled without vectors: embedder {}: {err}", e.model()),
387                }),
388            }
389        }
390    }
391    let mut items: Vec<Memory> = picked.into_values().collect();
392    items.sort_by(|a, b| {
393        b.score
394            .cmp(&a.score)
395            .then(b.updated_unix_ms.cmp(&a.updated_unix_ms))
396            .then(a.id.cmp(&b.id))
397    });
398    items.truncate(limit);
399    Ok(Found { items, problems })
400}