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