1pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
42pub enum Scope {
43 User,
45 Host,
47 Project,
49 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#[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#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct Context {
99 pub cwd: Option<PathBuf>,
101 pub session: Option<String>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq)]
107pub struct Memory {
108 pub id: String,
110 pub scope: Scope,
111 pub kind: Kind,
112 pub title: String,
113 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 pub path: Option<PathBuf>,
121 pub score: Option<u32>,
123}
124
125#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct New {
128 pub text: String,
129 pub kind: Kind,
130 pub scope: Scope,
131 pub title: Option<String>,
133 pub description: Option<String>,
135 pub links: Vec<String>,
136}
137
138#[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#[derive(Debug, Clone, PartialEq, Eq)]
150pub struct Problem {
151 pub path: PathBuf,
152 pub message: String,
153}
154
155#[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 NotFound(String),
166 Invalid(String),
170 Malformed(Problem),
172 Io(String),
174 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
193pub const DEFAULT_LIMIT: usize = 10;
195pub const MAX_LIMIT: usize = 100;
196
197pub trait Provider: Send + Sync + std::fmt::Debug {
201 fn name(&self) -> &'static str;
203
204 fn remember(&self, cx: &Context, new: New) -> Result<Memory, Error>;
205
206 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 fn forget(&self, cx: &Context, id: &str) -> Result<Memory, Error>;
215
216 fn put(&self, cx: &Context, m: &Memory) -> Result<Memory, Error>;
220
221 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
237pub 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
250pub 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
260pub(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
275pub(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
293pub(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#[derive(Debug, Clone, Default, PartialEq, Eq)]
311pub struct Moved {
312 pub ids: Vec<String>,
314 pub problems: Vec<Problem>,
315}
316
317pub 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}