Skip to main content

second_brain_adapters/
claude_memory.rs

1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use chrono::Utc;
5use uuid::Uuid;
6
7use second_brain_core::schema::{Conversation, Memory, MemoryType};
8
9use crate::{Adapter, ConversationSource, IngestResult};
10
11pub struct ClaudeMemoryAdapter {
12    base_path: PathBuf,
13    machine_id: String,
14}
15
16impl ClaudeMemoryAdapter {
17    pub fn new(machine_id: String) -> Self {
18        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".to_string());
19        let base_path = PathBuf::from(home).join(".claude").join("projects");
20        Self { base_path, machine_id }
21    }
22
23    pub fn with_path(base_path: PathBuf, machine_id: String) -> Self {
24        Self { base_path, machine_id }
25    }
26}
27
28struct Frontmatter {
29    description: String,
30    memory_type: MemoryType,
31}
32
33fn parse_frontmatter(content: &str) -> Option<(Frontmatter, &str)> {
34    let content = content.trim_start();
35    if !content.starts_with("---") {
36        return None;
37    }
38    let after_open = content.get(3..)?;
39    let end = after_open.find("\n---")?;
40    let front = &after_open[..end];
41    let body = after_open.get(end + 4..).unwrap_or("");
42
43    let mut description = String::new();
44    let mut type_str = String::new();
45    let mut in_metadata = false;
46
47    for line in front.lines() {
48        let trimmed = line.trim();
49        if trimmed == "metadata:" {
50            in_metadata = true;
51            continue;
52        }
53        if in_metadata && !line.starts_with(' ') && !line.starts_with('\t') {
54            in_metadata = false;
55        }
56        if in_metadata {
57            if let Some(rest) = trimmed.strip_prefix("type:") {
58                type_str = rest.trim().to_string();
59            }
60            continue;
61        }
62        if let Some(rest) = trimmed.strip_prefix("description:") {
63            description = rest.trim().to_string();
64        }
65    }
66
67    let memory_type = match type_str.as_str() {
68        "feedback" => MemoryType::Decision,
69        "project" => MemoryType::Episodic,
70        "reference" => MemoryType::Procedural,
71        _ => MemoryType::Semantic,
72    };
73
74    Some((Frontmatter { description, memory_type }, body))
75}
76
77fn is_memory_index(path: &std::path::Path) -> bool {
78    path.file_name()
79        .is_some_and(|n| n.eq_ignore_ascii_case("MEMORY.md"))
80}
81
82impl Adapter for ClaudeMemoryAdapter {
83    fn name(&self) -> &str {
84        "claude-memory"
85    }
86
87    fn discover_conversations(&self) -> Result<Vec<ConversationSource>> {
88        let mut sources = Vec::new();
89
90        if !self.base_path.exists() {
91            return Ok(sources);
92        }
93
94        let mut dirs = vec![self.base_path.clone()];
95        while let Some(dir) = dirs.pop() {
96            for entry in std::fs::read_dir(&dir)? {
97                let entry = entry?;
98                let path = entry.path();
99                if path.is_dir() {
100                    dirs.push(path);
101                } else if path.extension().is_some_and(|e| e == "md")
102                    && path
103                        .parent()
104                        .is_some_and(|p| p.file_name().is_some_and(|n| n == "memory"))
105                    && !is_memory_index(&path)
106                {
107                    sources.push(ConversationSource {
108                        id: path.to_string_lossy().to_string(),
109                        path: path.to_string_lossy().to_string(),
110                        source_name: "claude-memory".to_string(),
111                        machine_id: self.machine_id.clone(),
112                    });
113                }
114            }
115        }
116
117        Ok(sources)
118    }
119
120    fn ingest_conversation(&self, source: &ConversationSource) -> Result<IngestResult> {
121        let path = PathBuf::from(&source.path);
122        let raw = std::fs::read_to_string(&path)
123            .with_context(|| format!("reading memory file: {}", path.display()))?;
124
125        let empty = || IngestResult {
126            conversation: Conversation {
127                id: Uuid::new_v4(),
128                source: "claude-memory".to_string(),
129                machine_id: source.machine_id.clone(),
130                started_at: Utc::now(),
131                project_path: None,
132            },
133            memories: Vec::new(),
134            entities: Vec::new(),
135            entities_extracted: 0,
136        };
137
138        let (frontmatter, body) = match parse_frontmatter(&raw) {
139            Some(pair) => pair,
140            None => return Ok(empty()),
141        };
142
143        let body = body.trim();
144        if body.is_empty() {
145            return Ok(empty());
146        }
147
148        let content = if frontmatter.description.is_empty() {
149            body.to_string()
150        } else {
151            format!("{}\n\n{}", frontmatter.description, body)
152        };
153
154        let project_path = path
155            .parent()
156            .and_then(|p| p.parent())
157            .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()));
158
159        let conversation = Conversation {
160            id: Uuid::new_v4(),
161            source: "claude-memory".to_string(),
162            machine_id: source.machine_id.clone(),
163            started_at: Utc::now(),
164            project_path: project_path.clone(),
165        };
166
167        let mut memory = Memory::new(
168            content,
169            frontmatter.memory_type,
170            "claude-memory".to_string(),
171            source.path.clone(),
172        );
173        memory.project_path = project_path;
174        memory.machine_id = source.machine_id.clone();
175
176        Ok(IngestResult {
177            conversation,
178            memories: vec![memory],
179            entities: Vec::new(),
180            entities_extracted: 0,
181        })
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188
189    #[test]
190    fn maps_feedback_to_decision() {
191        let src = "---\nname: t\ndescription: A rule\nmetadata:\n  type: feedback\n---\n\nBody here.";
192        let (fm, body) = parse_frontmatter(src).unwrap();
193        assert_eq!(fm.memory_type, MemoryType::Decision);
194        assert_eq!(fm.description, "A rule");
195        assert_eq!(body.trim(), "Body here.");
196    }
197
198    #[test]
199    fn maps_project_to_episodic() {
200        let src = "---\nname: t\ndescription: d\nmetadata:\n  type: project\n---\n\nBody.";
201        let (fm, _) = parse_frontmatter(src).unwrap();
202        assert_eq!(fm.memory_type, MemoryType::Episodic);
203    }
204
205    #[test]
206    fn maps_reference_to_procedural() {
207        let src = "---\nname: t\ndescription: d\nmetadata:\n  type: reference\n---\n\nBody.";
208        let (fm, _) = parse_frontmatter(src).unwrap();
209        assert_eq!(fm.memory_type, MemoryType::Procedural);
210    }
211
212    #[test]
213    fn maps_user_and_unknown_to_semantic() {
214        for t in &["user", "other", ""] {
215            let src = format!("---\nname: t\ndescription: d\nmetadata:\n  type: {t}\n---\n\nBody.");
216            let (fm, _) = parse_frontmatter(&src).unwrap();
217            assert_eq!(fm.memory_type, MemoryType::Semantic, "type={t}");
218        }
219    }
220
221    #[test]
222    fn no_frontmatter_returns_none() {
223        assert!(parse_frontmatter("plain markdown content").is_none());
224    }
225
226    #[test]
227    fn description_prepended_to_body() {
228        let src = "---\nname: t\ndescription: Short summary\nmetadata:\n  type: user\n---\n\nDetailed body.";
229        let (fm, body) = parse_frontmatter(src).unwrap();
230        let combined = format!("{}\n\n{}", fm.description, body.trim());
231        assert!(combined.starts_with("Short summary"));
232        assert!(combined.contains("Detailed body."));
233    }
234
235    #[test]
236    fn empty_body_after_frontmatter_yields_no_memories() {
237        let src = "---\nname: t\ndescription: d\nmetadata:\n  type: user\n---\n\n   ";
238        let (_, body) = parse_frontmatter(src).unwrap();
239        assert!(body.trim().is_empty());
240    }
241}