Files
zesdex/src/model/memory.rs
T

181 lines
6.7 KiB
Rust
Raw Normal View History

use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use super::session::Session;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Memory {
pub name: String,
pub description: String,
pub content: String,
pub kind: String,
pub created_at: i64,
pub updated_at: i64,
pub outcome: Option<String>,
pub lifecycle: String,
}
impl Memory {
pub fn slugify(s: &str) -> Option<String> {
let slug: String = s
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let slug: String = slug
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-");
if slug.is_empty() || slug.len() > 80 {
return None;
}
Some(slug)
}
pub fn path(memory_dir: &Path, name: &str) -> PathBuf {
let slug = Self::slugify(name).unwrap_or_else(|| "memory".to_string());
slug_path(memory_dir, &format!("{}.md", slug))
}
pub fn write(&self, memory_dir: &Path) -> std::io::Result<()> {
let path = Self::path(memory_dir, &self.name);
let parent = path.parent().unwrap();
std::fs::create_dir_all(parent)?;
let outcome_line = self.outcome.as_ref().map(|o| format!("outcome: {}", o)).unwrap_or_default();
let content = format!(
"---\nname: {}\ndescription: {}\nkind: {}\ncreated_at: {}\nupdated_at: {}\nlifecycle: {}\n{}\n---\n\n{}",
self.name, self.description, self.kind, self.created_at, self.updated_at, self.lifecycle, outcome_line, self.content
);
let tmp = parent.join(format!(".{}.tmp", std::process::id()));
std::fs::write(&tmp, &content)?;
std::fs::rename(&tmp, path)?;
Ok(())
}
pub fn read(memory_dir: &Path, name: &str) -> std::io::Result<Self> {
let path = Self::path(memory_dir, name);
let content = std::fs::read_to_string(&path)?;
Self::parse(&content)
}
pub fn parse(content: &str) -> std::io::Result<Self> {
let parts: Vec<&str> = content.splitn(2, "---\n").collect();
if parts.len() < 2 {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "missing frontmatter"));
}
let front: std::collections::HashMap<String, String> = parts[0]
.lines()
.filter_map(|l| {
let mut it = l.splitn(2, ':');
Some((it.next()?.trim().to_string(), it.next()?.trim().to_string()))
})
.collect();
let body = parts.get(1).unwrap_or(&"").trim().to_string();
Ok(Memory {
name: front.get("name").cloned().unwrap_or_default(),
description: front.get("description").cloned().unwrap_or_default(),
content: body,
kind: front.get("kind").cloned().unwrap_or_else(|| "reference".to_string()),
created_at: front.get("created_at").and_then(|v| v.parse().ok()).unwrap_or(0),
updated_at: front.get("updated_at").and_then(|v| v.parse().ok()).unwrap_or(0),
outcome: front.get("outcome").cloned().filter(|s| !s.is_empty()),
lifecycle: front.get("lifecycle").cloned().unwrap_or_else(|| "new".to_string()),
})
}
pub fn remove(memory_dir: &Path, name: &str) -> std::io::Result<()> {
let path = Self::path(memory_dir, name);
if path.exists() {
std::fs::remove_file(path)?;
}
Ok(())
}
pub fn list(memory_dir: &Path) -> Vec<String> {
let entries = match std::fs::read_dir(memory_dir) {
Ok(e) => e,
Err(_) => return Vec::new(),
};
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|x| x == "md").unwrap_or(false))
.filter_map(|e| {
let name = e.file_name().to_string_lossy().to_string();
if name == "MEMORY.md" { return None; }
let slug = name.strip_suffix(".md")?.to_string();
Some(slug)
})
.collect()
}
pub fn load_index(memory_dir: &Path) -> Vec<String> {
let index_path = memory_dir.join("MEMORY.md");
let content = std::fs::read_to_string(index_path).unwrap_or_default();
content.lines().filter_map(|l| {
let l = l.trim();
if l.is_empty() || l.starts_with('#') { return None; }
l.split(']').next().and_then(|s| s.split('[').nth(1)).map(|s| s.to_string())
}).collect()
}
}
pub fn slug_path(memory_dir: &Path, raw: &str) -> PathBuf {
let clean: String = raw.chars()
.map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '-' })
.collect();
let clean = clean.trim_start_matches('.').to_string();
memory_dir.join(if clean.is_empty() { "memory.md" } else { &clean })
}
pub fn export_lessons(memory_dir: &Path, output: &Path) -> std::io::Result<()> {
let names = Memory::list(memory_dir);
let lessons: Vec<Memory> = names.iter()
.filter_map(|n| Memory::read(memory_dir, n).ok())
.collect();
let data = serde_json::to_string_pretty(&lessons)
.map_err(std::io::Error::other)?;
std::fs::write(output, data)?;
Ok(())
}
pub fn import_lessons(memory_dir: &Path, input: &Path) -> std::io::Result<usize> {
let data = std::fs::read_to_string(input)?;
let lessons: Vec<Memory> = serde_json::from_str(&data)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
let existing: std::collections::HashSet<String> = Memory::list(memory_dir).into_iter().collect();
let mut imported = 0;
for lesson in &lessons {
let slug = Memory::slugify(&lesson.name).unwrap_or_default();
if !existing.contains(&slug) {
lesson.write(memory_dir)?;
imported += 1;
}
}
Ok(imported)
}
pub fn create_retrospective(session_dir: &Path, session: &Session, lessons: &[Memory]) -> std::io::Result<Memory> {
let now = chrono::Utc::now().timestamp_millis();
let lessons_content: String = lessons.iter()
.map(|l| format!("- {}: {}", l.name, l.description))
.collect::<Vec<_>>()
.join("\n");
let content = format!(
"# Session Retrospective\n\nSession: {}\nCreated: {}\nLessons learned:\n{}\n",
session.title, now, lessons_content,
);
let memory = Memory {
name: format!("retrospective-{}", session.id),
description: format!("End-of-session retrospective for {}", session.title),
content,
kind: "retrospective".to_string(),
created_at: now,
updated_at: now,
outcome: None,
lifecycle: "new".to_string(),
};
memory.write(session_dir)?;
Ok(memory)
}