Skip to main content

memory/
lib.rs

1//! Durable memory: facts worth keeping across agent sessions and harnesses.
2//!
3//! A [`Provider`] keeps memories in four scopes (user, host, project,
4//! session) and finds them again by words. The daemon serves the
5//! `memory.*` API through whichever provider the settings name; this
6//! crate holds the interface, the deterministic full-text ranking every
7//! provider can share ([`search`]), and the providers: [`Files`], one
8//! markdown file per memory plus a `MEMORY.md` index, the layout Claude
9//! Code's memory uses; [`Sqlite`], one SQLite database per user with
10//! memories, their links as edges with valid times, vectors, collector
11//! rows, and session summaries; and, with the `kosmonaut` feature,
12//! `Kosmonaut`, the same kept on a Kosmonaut server over gRPC.
13//! [`transfer`] copies memories from one provider to another. See
14//! `docs/memory.md`.
15//!
16//! Headless: no GUI, and no model unless an [`embed`] embedder is
17//! configured. Calls do blocking I/O; the daemon runs them off its event
18//! loop. Only the Kosmonaut server client runs an async runtime, a small
19//! one of its own.
20
21pub mod embed;
22mod files;
23mod graph;
24mod index;
25#[cfg(feature = "kosmonaut")]
26mod kosmonaut;
27pub mod search;
28mod sqlite;
29mod time;
30
31use std::path::{Path, PathBuf};
32
33pub use files::Files;
34pub use graph::{CollectorRow, Summary};
35pub use index::{INDEX_BYTES, INDEX_HEAD, INDEX_LINES, index};
36#[cfg(feature = "kosmonaut")]
37pub use kosmonaut::{Kosmonaut, Server};
38pub use sqlite::Sqlite;
39
40/// Where a memory applies.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
42pub enum Scope {
43    /// The user, on every host and in every project.
44    User,
45    /// This host only.
46    Host,
47    /// One project, found from the caller's working directory.
48    Project,
49    /// One agent session.
50    Session,
51}
52
53impl Scope {
54    pub const ALL: [Scope; 4] = [Scope::User, Scope::Host, Scope::Project, Scope::Session];
55
56    pub fn name(self) -> &'static str {
57        match self {
58            Scope::User => "user",
59            Scope::Host => "host",
60            Scope::Project => "project",
61            Scope::Session => "session",
62        }
63    }
64
65    pub fn from_name(name: &str) -> Option<Scope> {
66        Scope::ALL.into_iter().find(|s| s.name() == name)
67    }
68}
69
70/// What a memory is about: Claude Code's four kinds.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub enum Kind {
73    User,
74    Feedback,
75    Project,
76    Reference,
77}
78
79impl Kind {
80    pub const ALL: [Kind; 4] = [Kind::User, Kind::Feedback, Kind::Project, Kind::Reference];
81
82    pub fn name(self) -> &'static str {
83        match self {
84            Kind::User => "user",
85            Kind::Feedback => "feedback",
86            Kind::Project => "project",
87            Kind::Reference => "reference",
88        }
89    }
90
91    pub fn from_name(name: &str) -> Option<Kind> {
92        Kind::ALL.into_iter().find(|k| k.name() == name)
93    }
94}
95
96/// Who is asking: what the project and session scopes are resolved from.
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct Context {
99    /// The caller's working directory (absolute).
100    pub cwd: Option<PathBuf>,
101    /// The agent session's id.
102    pub session: Option<String>,
103}
104
105/// One memory.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Memory {
108    /// `<scope>/<name>`; stable while the memory exists.
109    pub id: String,
110    pub scope: Scope,
111    pub kind: Kind,
112    pub title: String,
113    /// One line, for the index.
114    pub description: String,
115    pub text: String,
116    pub links: Vec<String>,
117    pub created_unix_ms: u64,
118    pub updated_unix_ms: u64,
119    /// The file that holds it, for a provider that keeps files.
120    pub path: Option<PathBuf>,
121    /// Set by recall: how well it matched, higher is better.
122    pub score: Option<u32>,
123}
124
125/// A new memory.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct New {
128    pub text: String,
129    pub kind: Kind,
130    pub scope: Scope,
131    /// Default: the text's first line, shortened.
132    pub title: Option<String>,
133    /// Default: the title.
134    pub description: Option<String>,
135    pub links: Vec<String>,
136}
137
138/// A change to a memory: `None` keeps what is there.
139#[derive(Debug, Clone, Default, PartialEq, Eq)]
140pub struct Change {
141    pub text: Option<String>,
142    pub kind: Option<Kind>,
143    pub title: Option<String>,
144    pub description: Option<String>,
145    pub links: Option<Vec<String>>,
146}
147
148/// A stored memory that could not be read. It is left alone and skipped.
149#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct Problem {
151    pub path: PathBuf,
152    pub message: String,
153}
154
155/// Memories, and what could not be read on the way.
156#[derive(Debug, Clone, Default, PartialEq, Eq)]
157pub struct Found {
158    pub items: Vec<Memory>,
159    pub problems: Vec<Problem>,
160}
161
162#[derive(Debug, Clone, PartialEq, Eq)]
163pub enum Error {
164    /// No memory with this id.
165    NotFound(String),
166    /// The request itself is wrong: an empty text, a bad id, or a scope
167    /// the context does not reach (project without a directory, session
168    /// without an id).
169    Invalid(String),
170    /// The memory exists but cannot be read.
171    Malformed(Problem),
172    /// The store failed.
173    Io(String),
174    /// The store cannot be reached: a Kosmonaut server that is down, does
175    /// not answer in time, or refuses the token. Memory is unavailable
176    /// until it is back; nothing else depends on it.
177    Unavailable(String),
178}
179
180impl std::fmt::Display for Error {
181    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        match self {
183            Error::NotFound(id) => write!(f, "no memory `{id}`"),
184            Error::Invalid(m) | Error::Io(m) => f.write_str(m),
185            Error::Unavailable(m) => write!(f, "memory unavailable: {m}"),
186            Error::Malformed(p) => write!(f, "{}: {}", p.path.display(), p.message),
187        }
188    }
189}
190
191impl std::error::Error for Error {}
192
193/// Default and largest number of memories recall returns.
194pub const DEFAULT_LIMIT: usize = 10;
195pub const MAX_LIMIT: usize = 100;
196
197/// A memory store. Every method resolves the project and session scopes
198/// from `cx`; `scope: None` means every scope `cx` reaches. Providers
199/// keep no cache that could go stale against their store.
200pub trait Provider: Send + Sync + std::fmt::Debug {
201    /// The settings name: `files`, `sqlite`, or `kosmonaut`.
202    fn name(&self) -> &'static str;
203
204    fn remember(&self, cx: &Context, new: New) -> Result<Memory, Error>;
205
206    /// Newest first.
207    fn list(&self, cx: &Context, scope: Option<Scope>, kind: Option<Kind>) -> Result<Found, Error>;
208
209    fn get(&self, cx: &Context, id: &str) -> Result<Memory, Error>;
210
211    fn update(&self, cx: &Context, id: &str, change: Change) -> Result<Memory, Error>;
212
213    /// Remove a memory; returns what was removed.
214    fn forget(&self, cx: &Context, id: &str) -> Result<Memory, Error>;
215
216    /// Keep `m` as it is, under its id and with its times, replacing a
217    /// memory with the same id: how memories move between providers
218    /// ([`transfer`]). `m.path` and `m.score` are ignored.
219    fn put(&self, cx: &Context, m: &Memory) -> Result<Memory, Error>;
220
221    /// Memories matching `query`, best first; at most `limit`
222    /// ([`DEFAULT_LIMIT`] when `None`, never more than [`MAX_LIMIT`]).
223    fn recall(
224        &self,
225        cx: &Context,
226        query: &str,
227        scope: Option<Scope>,
228        limit: Option<usize>,
229    ) -> Result<Found, Error> {
230        let mut found = self.list(cx, scope, None)?;
231        let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT);
232        found.items = search::rank(query, found.items, limit);
233        Ok(found)
234    }
235}
236
237/// The scopes `cx` reaches: user and host always, project with a working
238/// directory, session with a session id.
239pub fn reach(cx: &Context) -> Vec<Scope> {
240    Scope::ALL
241        .into_iter()
242        .filter(|s| match s {
243            Scope::Project => cx.cwd.is_some(),
244            Scope::Session => cx.session.is_some(),
245            _ => true,
246        })
247        .collect()
248}
249
250/// The project a working directory belongs to: the nearest directory at
251/// or above it that holds `.dreamer/memory` or `.git`, else the directory
252/// itself.
253pub fn project_root(cwd: &Path) -> PathBuf {
254    cwd.ancestors()
255        .find(|a| a.join(".dreamer").join("memory").is_dir() || a.join(".git").exists())
256        .unwrap_or(cwd)
257        .to_path_buf()
258}
259
260/// The project `cx` names, checked.
261pub(crate) fn project_of(cx: &Context) -> Result<PathBuf, Error> {
262    let cwd = cx
263        .cwd
264        .as_deref()
265        .ok_or_else(|| Error::Invalid("the project scope needs a working directory".into()))?;
266    if !cwd.is_absolute() {
267        return Err(Error::Invalid(format!(
268            "the working directory `{}` is not absolute",
269            cwd.display()
270        )));
271    }
272    Ok(project_root(cwd))
273}
274
275/// The session `cx` names, checked: letters, digits, `.`, `_`, `-`.
276pub(crate) fn session_of(cx: &Context) -> Result<&str, Error> {
277    let id = cx
278        .session
279        .as_deref()
280        .ok_or_else(|| Error::Invalid("the session scope needs a session id".into()))?;
281    let ok = !id.is_empty()
282        && id.len() <= 128
283        && !id.starts_with('.')
284        && id
285            .chars()
286            .all(|c| c.is_ascii_alphanumeric() || "._-".contains(c));
287    if !ok {
288        return Err(Error::Invalid(format!("`{id}` is not a session id")));
289    }
290    Ok(id)
291}
292
293/// `user/prefers-tabs` to its scope and name.
294pub(crate) fn split_id(id: &str) -> Result<(Scope, &str), Error> {
295    let bad = || Error::Invalid(format!("`{id}` is not a memory id (scope/name)"));
296    let (scope, name) = id.split_once('/').ok_or_else(bad)?;
297    let scope = Scope::from_name(scope).ok_or_else(bad)?;
298    let ok = !name.is_empty()
299        && name.len() <= 200
300        && !name.starts_with('.')
301        && name != "MEMORY"
302        && !name.contains(['/', '\\', '\0']);
303    if !ok {
304        return Err(bad());
305    }
306    Ok((scope, name))
307}
308
309/// What [`transfer`] copied, and what it could not read on the way.
310#[derive(Debug, Clone, Default, PartialEq, Eq)]
311pub struct Moved {
312    /// The ids copied, newest first.
313    pub ids: Vec<String>,
314    pub problems: Vec<Problem>,
315}
316
317/// Copy every memory `from` holds in `scope` (every scope `cx` reaches
318/// when `None`) into `to`, keeping ids, kinds, text, links, and times.
319/// A memory `to` already holds under the same id is replaced; nothing is
320/// removed from either side. Import from `files` and export back to it are
321/// this, with the providers swapped.
322pub fn transfer(
323    from: &dyn Provider,
324    to: &dyn Provider,
325    cx: &Context,
326    scope: Option<Scope>,
327) -> Result<Moved, Error> {
328    let found = from.list(cx, scope, None)?;
329    let mut moved = Moved {
330        ids: Vec::with_capacity(found.items.len()),
331        problems: found.problems,
332    };
333    for m in &found.items {
334        to.put(cx, m)?;
335        moved.ids.push(m.id.clone());
336    }
337    Ok(moved)
338}