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 = crate::project_slug(&self.base_path.join("projects"), &path);
144
145        let conversation = Conversation {
146            id: Uuid::new_v4(),
147            source: "cursor".to_string(),
148            machine_id: source.machine_id.clone(),
149            started_at: started_at.unwrap_or_else(Utc::now),
150            project_path: project_dir.clone(),
151        };
152
153        let mut memories = memories;
154        for mem in &mut memories {
155            mem.project_path = project_dir.clone();
156        }
157
158        Ok(IngestResult {
159            conversation,
160            memories,
161            entities: Vec::new(),
162            entities_extracted: 0,
163        })
164    }
165}
166
167fn is_memorable(text: &str) -> bool {
168    if text.len() < 100 || text.len() > 5000 {
169        return false;
170    }
171    let code_block_count = text.matches("```").count();
172    if code_block_count > 4 {
173        return false;
174    }
175    let non_code_lines = text
176        .lines()
177        .filter(|l| {
178            let trimmed = l.trim();
179            !trimmed.is_empty()
180                && !trimmed.starts_with("```")
181                && !trimmed.starts_with("  ")
182                && !trimmed.starts_with('\t')
183        })
184        .count();
185    non_code_lines >= 3
186}
187
188fn classify_memory(text: &str) -> MemoryType {
189    let lower = text.to_lowercase();
190
191    let task_markers = [
192        "todo:",
193        "todo ",
194        "fixme",
195        "action item",
196        "remaining:",
197        "left to do",
198        "need to implement",
199        "next step:",
200    ];
201    if task_markers.iter().any(|m| lower.contains(m)) {
202        return MemoryType::Task;
203    }
204
205    let decision_markers = [
206        "decided",
207        "chose",
208        "went with",
209        "picked",
210        "agreed",
211        "choosing",
212        "selected",
213        "switched to",
214        "we'll use",
215    ];
216    if decision_markers.iter().any(|m| lower.contains(m)) {
217        return MemoryType::Decision;
218    }
219
220    let architecture_markers = [
221        "architecture",
222        "data model",
223        "schema design",
224        "the approach is",
225        "system design",
226        "design pattern",
227        "data flow",
228    ];
229    if architecture_markers.iter().any(|m| lower.contains(m)) {
230        return MemoryType::Architecture;
231    }
232
233    let debugging_markers = [
234        "root cause",
235        "the bug",
236        "the issue is",
237        "the problem is",
238        "stack trace",
239        "error was",
240        "the fix is",
241        "debugging",
242    ];
243    if debugging_markers.iter().any(|m| lower.contains(m)) {
244        return MemoryType::Debugging;
245    }
246
247    if lower.contains('?') {
248        let interrogative = [
249            "how ",
250            "what ",
251            "why ",
252            "whether ",
253            "should we",
254            "could we",
255            "where ",
256            "when ",
257        ];
258        if interrogative.iter().any(|m| lower.contains(m)) {
259            return MemoryType::Question;
260        }
261    }
262
263    let procedural_markers = [
264        "to do this",
265        "steps:",
266        "step 1",
267        "first,",
268        "then,",
269        "finally,",
270        "run ",
271        "install ",
272        "execute",
273    ];
274    if procedural_markers.iter().any(|m| lower.contains(m)) {
275        return MemoryType::Procedural;
276    }
277
278    let episodic_markers = [
279        "migrated",
280        "deployed",
281        "shipped",
282        "found that",
283        "discovered",
284        "realized",
285        "confirmed",
286        "concluded",
287    ];
288    if episodic_markers.iter().any(|m| lower.contains(m)) {
289        return MemoryType::Episodic;
290    }
291
292    MemoryType::Semantic
293}