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