2026-07-11 13:16:10 +07:00
|
|
|
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,
|
2026-07-11 21:06:22 +07:00
|
|
|
pub scope: Option<String>,
|
|
|
|
|
pub before_snippet: Option<String>,
|
|
|
|
|
pub after_snippet: Option<String>,
|
|
|
|
|
pub provenances: Vec<String>,
|
2026-07-11 13:16:10 +07:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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();
|
2026-07-11 21:06:22 +07:00
|
|
|
let scope_line = self.scope.as_ref().map(|s| format!("scope: {}", s)).unwrap_or_default();
|
|
|
|
|
let before_line = self.before_snippet.as_ref().map(|s| format!("before: {}", s)).unwrap_or_default();
|
|
|
|
|
let after_line = self.after_snippet.as_ref().map(|s| format!("after: {}", s)).unwrap_or_default();
|
|
|
|
|
let prov_line = if self.provenances.is_empty() {
|
|
|
|
|
String::new()
|
|
|
|
|
} else {
|
|
|
|
|
format!("provenances: {}", self.provenances.join(", "))
|
|
|
|
|
};
|
2026-07-11 13:16:10 +07:00
|
|
|
let content = format!(
|
2026-07-11 21:06:22 +07:00
|
|
|
"---\nname: {}\ndescription: {}\nkind: {}\ncreated_at: {}\nupdated_at: {}\nlifecycle: {}\n{}\n{}\n{}\n{}\n{}\n---\n\n{}",
|
|
|
|
|
self.name, self.description, self.kind, self.created_at, self.updated_at,
|
|
|
|
|
self.lifecycle, outcome_line, scope_line, before_line, after_line, prov_line,
|
|
|
|
|
self.content
|
2026-07-11 13:16:10 +07:00
|
|
|
);
|
|
|
|
|
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()),
|
2026-07-11 21:06:22 +07:00
|
|
|
scope: front.get("scope").cloned().filter(|s| !s.is_empty()),
|
|
|
|
|
before_snippet: front.get("before").cloned().filter(|s| !s.is_empty()),
|
|
|
|
|
after_snippet: front.get("after").cloned().filter(|s| !s.is_empty()),
|
|
|
|
|
provenances: front.get("provenances").cloned()
|
|
|
|
|
.map(|s| s.split(", ").map(|p| p.to_string()).collect())
|
|
|
|
|
.unwrap_or_default(),
|
2026-07-11 13:16:10 +07:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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 })
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-11 18:23:01 +07:00
|
|
|
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(())
|
|
|
|
|
}
|
2026-07-11 21:06:22 +07:00
|
|
|
pub fn promote_with_consensus(global_dir: &Path, lesson: &Memory) -> std::io::Result<bool> {
|
|
|
|
|
let global_path = global_dir.join("memory");
|
|
|
|
|
std::fs::create_dir_all(&global_path)?;
|
|
|
|
|
let existing = Memory::list(&global_path);
|
|
|
|
|
let slug = Memory::slugify(&lesson.name).unwrap_or_default();
|
|
|
|
|
if existing.contains(&slug) {
|
|
|
|
|
return Ok(true);
|
|
|
|
|
}
|
|
|
|
|
let consensus = lesson.outcome.as_deref() == Some("verified");
|
|
|
|
|
|
|
|
|
|
if consensus {
|
|
|
|
|
let mut promoted = lesson.clone();
|
|
|
|
|
promoted.scope = Some("global".to_string());
|
|
|
|
|
promoted.write(&global_path)?;
|
|
|
|
|
Ok(true)
|
|
|
|
|
} else {
|
|
|
|
|
Ok(false)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-11 18:23:01 +07:00
|
|
|
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)
|
|
|
|
|
}
|
2026-07-11 21:06:22 +07:00
|
|
|
pub fn auto_create_retrospective(session_dir: &Path, session: &Session) -> std::io::Result<Option<Memory>> {
|
|
|
|
|
let now = chrono::Utc::now().timestamp_millis();
|
|
|
|
|
let session_age_ms = now.saturating_sub(session.created_at);
|
|
|
|
|
if session_age_ms < 60_000 {
|
|
|
|
|
return Ok(None);
|
|
|
|
|
}
|
|
|
|
|
let retro_name = format!("retrospective-{}", session.id);
|
|
|
|
|
let retro_path = Memory::path(session_dir, &retro_name);
|
|
|
|
|
if retro_path.exists() {
|
|
|
|
|
return Ok(None);
|
|
|
|
|
}
|
|
|
|
|
let lessons: Vec<Memory> = Memory::list(session_dir)
|
|
|
|
|
.iter()
|
|
|
|
|
.filter_map(|n| Memory::read(session_dir, n).ok())
|
|
|
|
|
.filter(|m| m.kind == "lesson")
|
|
|
|
|
.collect();
|
|
|
|
|
|
|
|
|
|
if lessons.is_empty() {
|
|
|
|
|
return Ok(None);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let retrospective = create_retrospective(session_dir, session, &lessons)?;
|
|
|
|
|
Ok(Some(retrospective))
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-11 13:16:10 +07:00
|
|
|
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(),
|
2026-07-11 21:06:22 +07:00
|
|
|
scope: Some("project".to_string()),
|
|
|
|
|
before_snippet: None,
|
|
|
|
|
after_snippet: None,
|
|
|
|
|
provenances: vec![],
|
2026-07-11 13:16:10 +07:00
|
|
|
};
|
|
|
|
|
memory.write(session_dir)?;
|
|
|
|
|
Ok(memory)
|
|
|
|
|
}
|