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                if let Some(ts) = msg.get("timestamp").and_then(|t| t.as_str()) {
58                    first_timestamp = DateTime::parse_from_rfc3339(ts)
59                        .map(|dt| dt.with_timezone(&Utc))
60                        .ok();
61                }
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                    if is_memorable(text) {
88                        let memory_type = classify_memory(text);
89                        let memory = Memory::new(
90                            text.to_string(),
91                            memory_type,
92                            "cursor".to_string(),
93                            source_id.clone(),
94                        );
95                        memories.push(memory);
96                    }
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    let decision_markers = [
190        "decided",
191        "chose",
192        "went with",
193        "picked",
194        "agreed",
195        "choosing",
196        "selected",
197    ];
198    let procedural_markers = [
199        "to do this",
200        "steps:",
201        "step 1",
202        "first,",
203        "then,",
204        "finally,",
205        "run ",
206        "install ",
207        "execute",
208    ];
209
210    if decision_markers.iter().any(|m| lower.contains(m)) {
211        MemoryType::Episodic
212    } else if procedural_markers.iter().any(|m| lower.contains(m)) {
213        MemoryType::Procedural
214    } else {
215        MemoryType::Semantic
216    }
217}