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