Skip to main content

second_brain_adapters/
cursor.rs

1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use chrono::{DateTime, Utc};
5use uuid::Uuid;
6
7use second_brain_core::schema::{Conversation, Memory, MemoryType};
8
9use crate::{Adapter, ConversationSource, IngestResult};
10
11pub struct CursorAdapter {
12    base_path: PathBuf,
13    machine_id: String,
14}
15
16impl CursorAdapter {
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(".cursor");
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    fn parse_conversation_file(
34        &self,
35        path: &PathBuf,
36    ) -> Result<(Vec<Memory>, Option<DateTime<Utc>>)> {
37        let content = std::fs::read_to_string(path)
38            .with_context(|| format!("reading conversation file: {}", path.display()))?;
39
40        let mut memories = Vec::new();
41        let mut first_timestamp: Option<DateTime<Utc>> = None;
42        let source_id = path.to_string_lossy().to_string();
43
44        for line in content.lines() {
45            if line.trim().is_empty() {
46                continue;
47            }
48
49            let msg: serde_json::Value = match serde_json::from_str(line) {
50                Ok(v) => v,
51                Err(_) => continue,
52            };
53
54            let role = msg.get("role").and_then(|r| r.as_str()).unwrap_or("");
55
56            if first_timestamp.is_none()
57                && let Some(ts) = msg.get("timestamp").and_then(|t| t.as_str())
58            {
59                first_timestamp = DateTime::parse_from_rfc3339(ts)
60                    .map(|dt| dt.with_timezone(&Utc))
61                    .ok();
62            }
63
64            if role != "assistant" {
65                continue;
66            }
67
68            let message = match msg.get("message") {
69                Some(m) => m,
70                None => continue,
71            };
72
73            let content_blocks = match message.get("content").and_then(|c| c.as_array()) {
74                Some(blocks) => blocks,
75                None => continue,
76            };
77
78            for block in content_blocks {
79                let block_type = block.get("type").and_then(|t| t.as_str()).unwrap_or("");
80
81                let text = match block_type {
82                    "text" => block.get("text").and_then(|t| t.as_str()),
83                    _ => None,
84                };
85
86                if let Some(text) = text
87                    && is_memorable(text)
88                {
89                    let memory_type = classify_memory(text);
90                    let memory = Memory::new(
91                        text.to_string(),
92                        memory_type,
93                        "cursor".to_string(),
94                        source_id.clone(),
95                    );
96                    memories.push(memory);
97                }
98            }
99        }
100
101        Ok((memories, first_timestamp))
102    }
103}
104
105impl Adapter for CursorAdapter {
106    fn name(&self) -> &str {
107        "cursor"
108    }
109
110    fn discover_conversations(&self) -> Result<Vec<ConversationSource>> {
111        let projects_dir = self.base_path.join("projects");
112        let mut sources = Vec::new();
113
114        if !projects_dir.exists() {
115            return Ok(sources);
116        }
117
118        let mut dirs = vec![projects_dir];
119        while let Some(dir) = dirs.pop() {
120            for entry in std::fs::read_dir(&dir)? {
121                let entry = entry?;
122                let path = entry.path();
123                if path.is_dir() {
124                    dirs.push(path);
125                } else if path.extension().is_some_and(|e| e == "jsonl") {
126                    sources.push(ConversationSource {
127                        id: path.to_string_lossy().to_string(),
128                        path: path.to_string_lossy().to_string(),
129                        source_name: "cursor".to_string(),
130                        machine_id: self.machine_id.clone(),
131                    });
132                }
133            }
134        }
135
136        Ok(sources)
137    }
138
139    fn ingest_conversation(&self, source: &ConversationSource) -> Result<IngestResult> {
140        let path = PathBuf::from(&source.path);
141        let (memories, started_at) = self.parse_conversation_file(&path)?;
142
143        let project_dir = path
144            .parent()
145            .and_then(|p| p.parent())
146            .and_then(|p| p.parent())
147            .and_then(|p| p.file_name().map(|n| n.to_string_lossy().to_string()));
148
149        let conversation = Conversation {
150            id: Uuid::new_v4(),
151            source: "cursor".to_string(),
152            machine_id: source.machine_id.clone(),
153            started_at: started_at.unwrap_or_else(Utc::now),
154            project_path: project_dir,
155        };
156
157        Ok(IngestResult {
158            conversation,
159            memories,
160            entities: Vec::new(),
161            entities_extracted: 0,
162        })
163    }
164}
165
166fn is_memorable(text: &str) -> bool {
167    if text.len() < 100 || text.len() > 5000 {
168        return false;
169    }
170    let code_block_count = text.matches("```").count();
171    if code_block_count > 4 {
172        return false;
173    }
174    let non_code_lines = text
175        .lines()
176        .filter(|l| {
177            let trimmed = l.trim();
178            !trimmed.is_empty()
179                && !trimmed.starts_with("```")
180                && !trimmed.starts_with("  ")
181                && !trimmed.starts_with('\t')
182        })
183        .count();
184    non_code_lines >= 3
185}
186
187fn classify_memory(text: &str) -> MemoryType {
188    let lower = text.to_lowercase();
189
190    let task_markers = [
191        "todo:",
192        "todo ",
193        "fixme",
194        "action item",
195        "remaining:",
196        "left to do",
197        "need to implement",
198        "next step:",
199    ];
200    if task_markers.iter().any(|m| lower.contains(m)) {
201        return MemoryType::Task;
202    }
203
204    let decision_markers = [
205        "decided",
206        "chose",
207        "went with",
208        "picked",
209        "agreed",
210        "choosing",
211        "selected",
212        "switched to",
213        "we'll use",
214    ];
215    if decision_markers.iter().any(|m| lower.contains(m)) {
216        return MemoryType::Decision;
217    }
218
219    let architecture_markers = [
220        "architecture",
221        "data model",
222        "schema design",
223        "the approach is",
224        "system design",
225        "design pattern",
226        "data flow",
227    ];
228    if architecture_markers.iter().any(|m| lower.contains(m)) {
229        return MemoryType::Architecture;
230    }
231
232    let debugging_markers = [
233        "root cause",
234        "the bug",
235        "the issue is",
236        "the problem is",
237        "stack trace",
238        "error was",
239        "the fix is",
240        "debugging",
241    ];
242    if debugging_markers.iter().any(|m| lower.contains(m)) {
243        return MemoryType::Debugging;
244    }
245
246    if lower.contains('?') {
247        let interrogative = [
248            "how ",
249            "what ",
250            "why ",
251            "whether ",
252            "should we",
253            "could we",
254            "where ",
255            "when ",
256        ];
257        if interrogative.iter().any(|m| lower.contains(m)) {
258            return MemoryType::Question;
259        }
260    }
261
262    let procedural_markers = [
263        "to do this",
264        "steps:",
265        "step 1",
266        "first,",
267        "then,",
268        "finally,",
269        "run ",
270        "install ",
271        "execute",
272    ];
273    if procedural_markers.iter().any(|m| lower.contains(m)) {
274        return MemoryType::Procedural;
275    }
276
277    let episodic_markers = [
278        "migrated",
279        "deployed",
280        "shipped",
281        "found that",
282        "discovered",
283        "realized",
284        "confirmed",
285        "concluded",
286    ];
287    if episodic_markers.iter().any(|m| lower.contains(m)) {
288        return MemoryType::Episodic;
289    }
290
291    MemoryType::Semantic
292}