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