pub mod embed;
mod files;
mod graph;
mod index;
#[cfg(feature = "kosmonaut")]
mod kosmonaut;
pub mod search;
mod sqlite;
mod time;
use std::path::{Path, PathBuf};
pub use files::Files;
pub use graph::{CollectorRow, Summary};
pub use index::{INDEX_BYTES, INDEX_HEAD, INDEX_LINES, index};
#[cfg(feature = "kosmonaut")]
pub use kosmonaut::{Kosmonaut, Server};
pub use sqlite::Sqlite;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Scope {
User,
Host,
Project,
Session,
}
impl Scope {
pub const ALL: [Scope; 4] = [Scope::User, Scope::Host, Scope::Project, Scope::Session];
pub fn name(self) -> &'static str {
match self {
Scope::User => "user",
Scope::Host => "host",
Scope::Project => "project",
Scope::Session => "session",
}
}
pub fn from_name(name: &str) -> Option<Scope> {
Scope::ALL.into_iter().find(|s| s.name() == name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Kind {
User,
Feedback,
Project,
Reference,
}
impl Kind {
pub const ALL: [Kind; 4] = [Kind::User, Kind::Feedback, Kind::Project, Kind::Reference];
pub fn name(self) -> &'static str {
match self {
Kind::User => "user",
Kind::Feedback => "feedback",
Kind::Project => "project",
Kind::Reference => "reference",
}
}
pub fn from_name(name: &str) -> Option<Kind> {
Kind::ALL.into_iter().find(|k| k.name() == name)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Context {
pub cwd: Option<PathBuf>,
pub session: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Memory {
pub id: String,
pub scope: Scope,
pub kind: Kind,
pub title: String,
pub description: String,
pub text: String,
pub links: Vec<String>,
pub created_unix_ms: u64,
pub updated_unix_ms: u64,
pub path: Option<PathBuf>,
pub score: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct New {
pub text: String,
pub kind: Kind,
pub scope: Scope,
pub title: Option<String>,
pub description: Option<String>,
pub links: Vec<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Change {
pub text: Option<String>,
pub kind: Option<Kind>,
pub title: Option<String>,
pub description: Option<String>,
pub links: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Problem {
pub path: PathBuf,
pub message: String,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Found {
pub items: Vec<Memory>,
pub problems: Vec<Problem>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
NotFound(String),
Invalid(String),
Malformed(Problem),
Io(String),
Unavailable(String),
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::NotFound(id) => write!(f, "no memory `{id}`"),
Error::Invalid(m) | Error::Io(m) => f.write_str(m),
Error::Unavailable(m) => write!(f, "memory unavailable: {m}"),
Error::Malformed(p) => write!(f, "{}: {}", p.path.display(), p.message),
}
}
}
impl std::error::Error for Error {}
pub const DEFAULT_LIMIT: usize = 10;
pub const MAX_LIMIT: usize = 100;
pub trait Provider: Send + Sync + std::fmt::Debug {
fn name(&self) -> &'static str;
fn remember(&self, cx: &Context, new: New) -> Result<Memory, Error>;
fn list(&self, cx: &Context, scope: Option<Scope>, kind: Option<Kind>) -> Result<Found, Error>;
fn get(&self, cx: &Context, id: &str) -> Result<Memory, Error>;
fn update(&self, cx: &Context, id: &str, change: Change) -> Result<Memory, Error>;
fn forget(&self, cx: &Context, id: &str) -> Result<Memory, Error>;
fn put(&self, cx: &Context, m: &Memory) -> Result<Memory, Error>;
fn recall(
&self,
cx: &Context,
query: &str,
scope: Option<Scope>,
limit: Option<usize>,
) -> Result<Found, Error> {
let mut found = self.list(cx, scope, None)?;
let limit = limit.unwrap_or(DEFAULT_LIMIT).clamp(1, MAX_LIMIT);
found.items = search::rank(query, found.items, limit);
Ok(found)
}
}
pub fn reach(cx: &Context) -> Vec<Scope> {
Scope::ALL
.into_iter()
.filter(|s| match s {
Scope::Project => cx.cwd.is_some(),
Scope::Session => cx.session.is_some(),
_ => true,
})
.collect()
}
pub fn project_root(cwd: &Path) -> PathBuf {
cwd.ancestors()
.find(|a| a.join(".dreamer").join("memory").is_dir() || a.join(".git").exists())
.unwrap_or(cwd)
.to_path_buf()
}
pub(crate) fn project_of(cx: &Context) -> Result<PathBuf, Error> {
let cwd = cx
.cwd
.as_deref()
.ok_or_else(|| Error::Invalid("the project scope needs a working directory".into()))?;
if !cwd.is_absolute() {
return Err(Error::Invalid(format!(
"the working directory `{}` is not absolute",
cwd.display()
)));
}
Ok(project_root(cwd))
}
pub(crate) fn session_of(cx: &Context) -> Result<&str, Error> {
let id = cx
.session
.as_deref()
.ok_or_else(|| Error::Invalid("the session scope needs a session id".into()))?;
let ok = !id.is_empty()
&& id.len() <= 128
&& !id.starts_with('.')
&& id
.chars()
.all(|c| c.is_ascii_alphanumeric() || "._-".contains(c));
if !ok {
return Err(Error::Invalid(format!("`{id}` is not a session id")));
}
Ok(id)
}
pub(crate) fn split_id(id: &str) -> Result<(Scope, &str), Error> {
let bad = || Error::Invalid(format!("`{id}` is not a memory id (scope/name)"));
let (scope, name) = id.split_once('/').ok_or_else(bad)?;
let scope = Scope::from_name(scope).ok_or_else(bad)?;
let ok = !name.is_empty()
&& name.len() <= 200
&& !name.starts_with('.')
&& name != "MEMORY"
&& !name.contains(['/', '\\', '\0']);
if !ok {
return Err(bad());
}
Ok((scope, name))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Moved {
pub ids: Vec<String>,
pub problems: Vec<Problem>,
}
pub fn transfer(
from: &dyn Provider,
to: &dyn Provider,
cx: &Context,
scope: Option<Scope>,
) -> Result<Moved, Error> {
let found = from.list(cx, scope, None)?;
let mut moved = Moved {
ids: Vec::with_capacity(found.items.len()),
problems: found.problems,
};
for m in &found.items {
to.put(cx, m)?;
moved.ids.push(m.id.clone());
}
Ok(moved)
}