use std::path::PathBuf;
use anyhow::{Context, Result};
use chrono::Utc;
use uuid::Uuid;
use second_brain_core::schema::{Conversation, Memory, MemoryType};
use crate::{Adapter, ConversationSource, IngestResult};
pub struct ClaudeMemoryAdapter {
base_path: PathBuf,
machine_id: String,
}
impl ClaudeMemoryAdapter {
pub fn new(machine_id: String) -> Self {
let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
let base_path = PathBuf::from(home).join(".claude").join("projects");
Self {
base_path,
machine_id,
}
}
pub fn with_path(base_path: PathBuf, machine_id: String) -> Self {
Self {
base_path,
machine_id,
}
}
}
struct Frontmatter {
description: String,
memory_type: MemoryType,
}
fn parse_frontmatter(content: &str) -> Option<(Frontmatter, &str)> {
let content = content.trim_start();
if !content.starts_with("---") {
return None;
}
let after_open = content.get(3..)?;
let end = after_open.find("\n---")?;
let front = &after_open[..end];
let body = after_open.get(end + 4..).unwrap_or("");
let mut description = String::new();
let mut type_str = String::new();
let mut in_metadata = false;
for line in front.lines() {
let trimmed = line.trim();
if trimmed == "metadata:" {
in_metadata = true;
continue;
}
if in_metadata && !line.starts_with(' ') && !line.starts_with('\t') {
in_metadata = false;
}
if in_metadata {
if let Some(rest) = trimmed.strip_prefix("type:") {
type_str = rest.trim().to_string();
}
continue;
}
if let Some(rest) = trimmed.strip_prefix("description:") {
description = rest.trim().to_string();
}
}
let memory_type = match type_str.as_str() {
"feedback" => MemoryType::Decision,
"project" => MemoryType::Episodic,
"reference" => MemoryType::Procedural,
_ => MemoryType::Semantic,
};
Some((
Frontmatter {
description,
memory_type,
},
body,
))
}
fn is_memory_index(path: &std::path::Path) -> bool {
path.file_name()
.is_some_and(|n| n.eq_ignore_ascii_case("MEMORY.md"))
}
impl Adapter for ClaudeMemoryAdapter {
fn name(&self) -> &str {
"claude-memory"
}
fn discover_conversations(&self) -> Result<Vec<ConversationSource>> {
let mut sources = Vec::new();
if !self.base_path.exists() {
return Ok(sources);
}
let mut dirs = vec![self.base_path.clone()];
while let Some(dir) = dirs.pop() {
for entry in std::fs::read_dir(&dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
dirs.push(path);
} else if path.extension().is_some_and(|e| e == "md")
&& path
.parent()
.is_some_and(|p| p.file_name().is_some_and(|n| n == "memory"))
&& !is_memory_index(&path)
{
sources.push(ConversationSource {
id: path.to_string_lossy().to_string(),
path: path.to_string_lossy().to_string(),
source_name: "claude-memory".to_string(),
machine_id: self.machine_id.clone(),
});
}
}
}
Ok(sources)
}
fn ingest_conversation(&self, source: &ConversationSource) -> Result<IngestResult> {
let path = PathBuf::from(&source.path);
let raw = std::fs::read_to_string(&path)
.with_context(|| format!("reading memory file: {}", path.display()))?;
let empty = || IngestResult {
conversation: Conversation {
id: Uuid::new_v4(),
source: "claude-memory".to_string(),
machine_id: source.machine_id.clone(),
started_at: Utc::now(),
project_path: None,
},
memories: Vec::new(),
entities: Vec::new(),
entities_extracted: 0,
};
let (frontmatter, body) = match parse_frontmatter(&raw) {
Some(pair) => pair,
None => return Ok(empty()),
};
let body = body.trim();
if body.is_empty() {
return Ok(empty());
}
let content = if frontmatter.description.is_empty() {
body.to_string()
} else {
format!("{}\n\n{}", frontmatter.description, body)
};
let project_path = path
.parent()
.and_then(|p| p.parent())
.and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()));
let conversation = Conversation {
id: Uuid::new_v4(),
source: "claude-memory".to_string(),
machine_id: source.machine_id.clone(),
started_at: Utc::now(),
project_path: project_path.clone(),
};
let mut memory = Memory::new(
content,
frontmatter.memory_type,
"claude-memory".to_string(),
source.path.clone(),
);
memory.project_path = project_path;
memory.machine_id = source.machine_id.clone();
Ok(IngestResult {
conversation,
memories: vec![memory],
entities: Vec::new(),
entities_extracted: 0,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn maps_feedback_to_decision() {
let src =
"---\nname: t\ndescription: A rule\nmetadata:\n type: feedback\n---\n\nBody here.";
let (fm, body) = parse_frontmatter(src).unwrap();
assert_eq!(fm.memory_type, MemoryType::Decision);
assert_eq!(fm.description, "A rule");
assert_eq!(body.trim(), "Body here.");
}
#[test]
fn maps_project_to_episodic() {
let src = "---\nname: t\ndescription: d\nmetadata:\n type: project\n---\n\nBody.";
let (fm, _) = parse_frontmatter(src).unwrap();
assert_eq!(fm.memory_type, MemoryType::Episodic);
}
#[test]
fn maps_reference_to_procedural() {
let src = "---\nname: t\ndescription: d\nmetadata:\n type: reference\n---\n\nBody.";
let (fm, _) = parse_frontmatter(src).unwrap();
assert_eq!(fm.memory_type, MemoryType::Procedural);
}
#[test]
fn maps_user_and_unknown_to_semantic() {
for t in &["user", "other", ""] {
let src = format!("---\nname: t\ndescription: d\nmetadata:\n type: {t}\n---\n\nBody.");
let (fm, _) = parse_frontmatter(&src).unwrap();
assert_eq!(fm.memory_type, MemoryType::Semantic, "type={t}");
}
}
#[test]
fn no_frontmatter_returns_none() {
assert!(parse_frontmatter("plain markdown content").is_none());
}
#[test]
fn description_prepended_to_body() {
let src = "---\nname: t\ndescription: Short summary\nmetadata:\n type: user\n---\n\nDetailed body.";
let (fm, body) = parse_frontmatter(src).unwrap();
let combined = format!("{}\n\n{}", fm.description, body.trim());
assert!(combined.starts_with("Short summary"));
assert!(combined.contains("Detailed body."));
}
#[test]
fn empty_body_after_frontmatter_yields_no_memories() {
let src = "---\nname: t\ndescription: d\nmetadata:\n type: user\n---\n\n ";
let (_, body) = parse_frontmatter(src).unwrap();
assert!(body.trim().is_empty());
}
}