use std::io::Write;
use mnemo_engine::{
Memory, MemoryType, Scope, MNEMO_META_KEY, MNEMO_META_KIND, MNEMO_META_KIND_TURN,
};
use serde_json::{Map, Number, Value};
#[derive(Copy, Clone, Debug, PartialEq, Eq, clap::ValueEnum)]
#[clap(rename_all = "lowercase")]
pub enum ExportFormat {
Markdown,
Jsonl,
}
pub struct ExportOptions {
pub format: ExportFormat,
pub git: bool,
pub types: Option<Vec<MemoryType>>,
pub agent: Option<String>,
}
pub struct FileFacts {
pub format_version: u16,
pub dimensions: usize,
}
fn key_of(m: &Memory) -> Option<&str> {
m.metadata.get(MNEMO_META_KEY).and_then(Value::as_str)
}
fn kind_of(m: &Memory) -> Option<&str> {
m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str)
}
fn task_slug(m: &Memory) -> Option<&str> {
(kind_of(m) == Some("task"))
.then(|| m.metadata.get("_mnemo.slug").and_then(Value::as_str))
.flatten()
}
fn done_long_ago(m: &Memory, now: i64) -> bool {
if task_slug(m).is_none()
|| m.metadata.get("_mnemo.status").and_then(Value::as_str) != Some("done")
{
return false;
}
let at = m
.metadata
.get("_mnemo.status_history")
.and_then(Value::as_array)
.and_then(|h| h.last())
.and_then(|e| e.get("at"))
.and_then(Value::as_i64)
.unwrap_or(m.created_at);
now - at > mnemo_engine::TASK_DONE_EXPORT_KEEP_SECS
}
fn is_turn(m: &Memory) -> bool {
m.metadata.get(MNEMO_META_KIND).and_then(Value::as_str) == Some(MNEMO_META_KIND_TURN)
}
pub fn select(mut all: Vec<Memory>, o: &ExportOptions) -> Vec<Memory> {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs() as i64);
all.retain(|m| !matches!(kind_of(m), Some("claim" | "presence")));
if o.git {
all.retain(|m| kind_of(m) != Some("message"));
all.retain(|m| !done_long_ago(m, now));
}
if let Some(ts) = &o.types {
all.retain(|m| ts.contains(&m.memory_type));
}
if let Some(a) = &o.agent {
all.retain(|m| &m.agent_id == a);
}
if o.git {
all.retain(|m| !is_turn(m));
all.sort_by(|a, b| {
let ka = key_of(a);
let kb = key_of(b);
let (ta, tb) = (task_slug(a), task_slug(b));
(ka.is_none(), ka, ta.is_none(), ta, a.id).cmp(&(
kb.is_none(),
kb,
tb.is_none(),
tb,
b.id,
))
});
} else {
all.sort_by_key(|m| m.id);
}
all
}
pub fn render(memories: &[Memory], o: &ExportOptions, facts: &FileFacts) -> String {
match o.format {
ExportFormat::Jsonl => {
let mut out = String::new();
for m in memories {
let line = serde_json::to_string(&Value::Object(record(m, o.git)))
.unwrap_or_else(|_| "{}".into());
out.push_str(&line);
out.push('\n');
}
out
}
ExportFormat::Markdown => markdown(memories, o, facts),
}
}
pub fn write_private(path: &str, body: &str) -> std::result::Result<(), String> {
let target = std::path::Path::new(path);
let dir = match target.parent() {
Some(d) if !d.as_os_str().is_empty() => d.to_path_buf(),
_ => std::path::PathBuf::from("."),
};
let name = target
.file_name()
.ok_or_else(|| format!("{path}: not a file name"))?
.to_string_lossy()
.into_owned();
let mut last_err = None;
for attempt in 0..16u32 {
let tmp = dir.join(format!(".{name}.{}-{attempt}.tmp", std::process::id()));
let mut opts = std::fs::OpenOptions::new();
opts.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
let mut f = match opts.open(&tmp) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
last_err = Some(e);
continue;
}
Err(e) => return Err(format!("writing beside {path}: {e}")),
};
let written = f
.write_all(body.as_bytes())
.and_then(|_| f.sync_all())
.and_then(|_| {
drop(f);
std::fs::rename(&tmp, target)
});
return written.map_err(|e| {
let _ = std::fs::remove_file(&tmp);
format!("writing {path}: {e}")
});
}
Err(format!(
"writing beside {path}: {}",
last_err.map(|e| e.to_string()).unwrap_or_default()
))
}
fn scope_str(s: Scope) -> &'static str {
match s {
Scope::Private => "private",
Scope::Shared => "shared",
}
}
fn short_f32(x: f32) -> Value {
format!("{x}")
.parse::<f64>()
.ok()
.and_then(Number::from_f64)
.map(Value::Number)
.unwrap_or(Value::Null)
}
fn record(m: &Memory, git: bool) -> Map<String, Value> {
let mut r = Map::new();
r.insert("id".into(), Value::String(m.id.to_string()));
r.insert("type".into(), Value::String(m.memory_type.as_str().into()));
r.insert("agent".into(), Value::String(m.agent_id.clone()));
if let Some(k) = key_of(m) {
r.insert("key".into(), Value::String(k.into()));
}
if let Some(s) = &m.session_id {
r.insert("session".into(), Value::String(s.clone()));
}
r.insert("scope".into(), Value::String(scope_str(m.scope).into()));
r.insert("created_at".into(), Value::from(m.created_at));
r.insert("importance".into(), short_f32(m.importance));
if let Some(t) = m.ttl_secs {
r.insert("ttl_secs".into(), Value::from(t));
}
if !git {
r.insert("accessed_at".into(), Value::from(m.accessed_at));
r.insert("access_count".into(), Value::from(m.access_count));
}
if !m.metadata.is_empty() {
let mut meta = m.metadata.clone();
if git {
meta.remove("_mnemo.delivery");
}
r.insert("metadata".into(), Value::Object(meta));
}
r.insert("content".into(), Value::String(m.content.clone()));
r
}
fn markdown(memories: &[Memory], o: &ExportOptions, facts: &FileFacts) -> String {
let mut out = String::new();
out.push_str("# mnemo export\n\n");
out.push_str(&format!(
"Plaintext export of a `.mnemo` file (format v{}, {} dimensions). \
Keep it as safe as the file's passphrase.\n\n",
facts.format_version, facts.dimensions
));
if o.git {
out.push_str(
"Written with `--git`: ordered by key, then id; vectors, thread turns \
and access stats are left out.\n",
);
} else {
out.push_str(&format!(
"{} {}. Vectors are left out.\n",
memories.len(),
if memories.len() == 1 {
"memory"
} else {
"memories"
}
));
}
for m in memories {
out.push('\n');
out.push_str(&format!("## {}\n\n", m.id));
out.push_str(&format!("- type: {}\n", m.memory_type.as_str()));
out.push_str(&format!("- agent: {}\n", code(&m.agent_id)));
if let Some(k) = key_of(m) {
out.push_str(&format!("- key: {}\n", code(k)));
}
if let Some(s) = &m.session_id {
out.push_str(&format!("- session: {}\n", code(s)));
}
out.push_str(&format!("- scope: {}\n", scope_str(m.scope)));
out.push_str(&format!("- created: {}\n", rfc3339(m.created_at)));
out.push_str(&format!("- importance: {}\n", m.importance));
if let Some(t) = m.ttl_secs {
out.push_str(&format!("- ttl: {t} s\n"));
}
if !o.git {
out.push_str(&format!(
"- accessed: {} ({} {})\n",
rfc3339(m.accessed_at),
m.access_count,
if m.access_count == 1 { "time" } else { "times" }
));
}
if !m.metadata.is_empty() {
let meta = serde_json::to_string(&Value::Object(m.metadata.clone()))
.unwrap_or_else(|_| "{}".into());
out.push_str(&format!("- metadata: {}\n", code(&meta)));
}
out.push('\n');
let fence = "`".repeat(longest_run(&m.content, '`').max(2) + 1);
out.push_str(&format!("{fence}text\n{}\n{fence}\n", m.content));
}
out
}
fn longest_run(s: &str, c: char) -> usize {
let (mut best, mut cur) = (0, 0);
for ch in s.chars() {
if ch == c {
cur += 1;
best = best.max(cur);
} else {
cur = 0;
}
}
best
}
fn code(s: &str) -> String {
let s = s.replace('\r', "\\r").replace('\n', "\\n");
let ticks = "`".repeat(longest_run(&s, '`') + 1);
if s.starts_with('`') || s.ends_with('`') {
format!("{ticks} {s} {ticks}")
} else {
format!("{ticks}{s}{ticks}")
}
}
pub fn rfc3339(secs: i64) -> String {
let days = secs.div_euclid(86_400);
let rem = secs.rem_euclid(86_400);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!(
"{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
rem / 3600,
rem % 3600 / 60,
rem % 60
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc3339_matches_known_times() {
assert_eq!(rfc3339(0), "1970-01-01T00:00:00Z");
assert_eq!(rfc3339(951_782_400), "2000-02-29T00:00:00Z");
assert_eq!(rfc3339(1_794_389_400), "2026-11-11T09:30:00Z");
assert_eq!(rfc3339(-1), "1969-12-31T23:59:59Z");
}
#[test]
fn code_survives_backticks_and_newlines() {
assert_eq!(code("plain"), "`plain`");
assert_eq!(code("a`b"), "``a`b``");
assert_eq!(code("`x"), "`` `x ``");
assert_eq!(code("two\nlines"), "`two\\nlines`");
}
#[test]
fn importance_reads_as_written() {
assert_eq!(short_f32(0.7).to_string(), "0.7");
assert_eq!(short_f32(1.0).to_string(), "1.0");
}
}