1use std::collections::HashSet;
4use std::path::{Component, Path, PathBuf};
5
6use rusqlite::{Connection, OpenFlags, params};
7use serde_json::{Map, Value};
8
9use super::{ImportResult, ImportSource, finish_result, process_value, push_error};
10
11const MAX_SESSIONS: i64 = 1_000;
12const MAX_SESSION_ROWS_SCANNED: i64 = 10_000;
13const MAX_PARTS: i64 = 10_000;
14
15#[must_use]
17pub fn import() -> ImportResult {
18 let Ok(project_root) = std::env::current_dir() else {
19 return ImportResult::default();
20 };
21 let Some(data_dir) = dirs::data_dir() else {
22 return ImportResult::default();
23 };
24 import_from_db(
25 &data_dir.join("opencode").join("opencode.db"),
26 &project_root,
27 )
28}
29
30#[must_use]
32pub fn import_from_db(db_path: &Path, project_root: &Path) -> ImportResult {
33 if !db_path.is_file() {
34 return ImportResult::default();
35 }
36
37 let mut result = ImportResult::default();
38 let Ok(connection) = Connection::open_with_flags(db_path, OpenFlags::SQLITE_OPEN_READ_ONLY)
39 else {
40 push_error(
41 &mut result,
42 "OpenCode history database could not be opened".to_owned(),
43 );
44 return result;
45 };
46
47 let project_root = canonical_or_lexical(project_root);
48 let mut session_ids = Vec::new();
49 let Ok(mut statement) = connection.prepare(
50 "SELECT s.id, p.worktree
51 FROM session s JOIN project p ON p.id = s.project_id
52 ORDER BY s.time_updated DESC, s.id
53 LIMIT ?1",
54 ) else {
55 push_error(
56 &mut result,
57 "OpenCode history schema is not supported".to_owned(),
58 );
59 return result;
60 };
61 let Ok(rows) = statement.query_map([MAX_SESSION_ROWS_SCANNED], |row| {
62 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
63 }) else {
64 push_error(
65 &mut result,
66 "OpenCode sessions could not be read".to_owned(),
67 );
68 return result;
69 };
70 for row in rows {
71 match row {
72 Ok((id, worktree)) if canonical_or_lexical(Path::new(&worktree)) == project_root => {
73 session_ids.push(id);
74 if session_ids.len() >= MAX_SESSIONS as usize {
75 break;
76 }
77 }
78 Ok(_) => {}
79 Err(_) => push_error(
80 &mut result,
81 "OpenCode contains a malformed session row".to_owned(),
82 ),
83 }
84 }
85 drop(statement);
86 result.sessions_found = session_ids.len();
87
88 let mut touched = HashSet::new();
89 let mut seen = HashSet::new();
90 let mut parts_remaining = MAX_PARTS;
91 for session_id in session_ids {
92 if parts_remaining == 0 {
93 break;
94 }
95 let Ok(mut statement) = connection.prepare(
96 "SELECT m.data, p.data
97 FROM message m JOIN part p ON p.message_id = m.id
98 WHERE m.session_id = ?1
99 ORDER BY p.time_created, p.id
100 LIMIT ?2",
101 ) else {
102 push_error(
103 &mut result,
104 "OpenCode messages could not be read".to_owned(),
105 );
106 continue;
107 };
108 let Ok(rows) = statement.query_map(params![session_id, parts_remaining], |row| {
109 Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
110 }) else {
111 push_error(
112 &mut result,
113 "OpenCode messages could not be read".to_owned(),
114 );
115 continue;
116 };
117 for row in rows {
118 parts_remaining -= 1;
119 let Ok(row) = row else {
120 push_error(
121 &mut result,
122 "OpenCode contains a malformed history row".to_owned(),
123 );
124 continue;
125 };
126 let (Ok(message), Ok(mut part)) = (
127 serde_json::from_str::<Value>(&row.0),
128 serde_json::from_str::<Value>(&row.1),
129 ) else {
130 push_error(
131 &mut result,
132 "OpenCode contains a malformed history row".to_owned(),
133 );
134 continue;
135 };
136 if let Some(safe_part) = importable_part(&message, &mut part, &project_root) {
137 process_value(
138 ImportSource::OpenCode,
139 &format!("opencode:{session_id}"),
140 &safe_part,
141 &mut result,
142 &mut touched,
143 &mut seen,
144 );
145 }
146 }
147 }
148 finish_result(&mut result, &touched);
149 result
150}
151
152fn importable_part(message: &Value, part: &mut Value, project_root: &Path) -> Option<Value> {
153 let part_type = part.get("type")?.as_str()?.to_owned();
154 let mut safe_part = Map::new();
155 safe_part.insert("type".to_owned(), Value::String(part_type.clone()));
156
157 match part_type.as_str() {
158 "text" => {
159 let text = safe_text(part.get("text")?.as_str()?)?;
160 safe_part.insert("text".to_owned(), Value::String(text));
161 }
162 "tool" => {
163 let state = part.get("state")?.as_object()?;
164 let mut safe_state = Map::new();
165 if let Some(error) = state
166 .get("error")
167 .and_then(Value::as_str)
168 .and_then(safe_tool_error)
169 {
170 safe_state.insert("error".to_owned(), Value::String(error));
171 }
172 if let Some(input) = state.get("input").and_then(Value::as_object) {
173 let mut safe_input = Map::new();
174 for key in ["file_path", "filePath", "path", "filename", "file_name"] {
175 if let Some(path) = input
176 .get(key)
177 .and_then(Value::as_str)
178 .and_then(|path| project_relative(Path::new(path), project_root))
179 {
180 safe_input.insert(key.to_owned(), Value::String(path));
181 }
182 }
183 if !safe_input.is_empty() {
184 safe_state.insert("input".to_owned(), Value::Object(safe_input));
185 }
186 }
187 if safe_state.is_empty() {
188 return None;
189 }
190 safe_part.insert("state".to_owned(), Value::Object(safe_state));
191 }
192 "patch" => {
193 let files = part
194 .get("files")
195 .and_then(Value::as_array)?
196 .iter()
197 .filter_map(Value::as_str)
198 .filter_map(|path| project_relative(Path::new(path), project_root))
199 .map(|path| serde_json::json!({ "file_path": path }))
200 .collect::<Vec<_>>();
201 if files.is_empty() {
202 return None;
203 }
204 safe_part.insert("files".to_owned(), Value::Array(files));
205 }
206 _ => return None,
207 }
208
209 let mut combined = Map::new();
210 combined.insert(
211 "role".to_owned(),
212 message
213 .get("role")
214 .cloned()
215 .unwrap_or(Value::String("unknown".to_owned())),
216 );
217 combined.insert("part".to_owned(), Value::Object(safe_part));
218 Some(Value::Object(combined))
219}
220
221fn safe_text(text: &str) -> Option<String> {
222 let safe = text
223 .split(['\n', '.', '!', '?'])
224 .map(str::trim)
225 .filter(|snippet| !contains_sensitive_material(snippet))
226 .collect::<Vec<_>>()
227 .join(". ");
228 (!safe.is_empty()).then_some(safe)
229}
230
231fn safe_tool_error(error: &str) -> Option<String> {
232 let error = error.trim();
233 (!error.is_empty() && !contains_sensitive_material(error)).then(|| error.to_owned())
234}
235
236fn contains_sensitive_material(text: &str) -> bool {
237 let lower = text.to_ascii_lowercase();
238 let has_secret_marker = [
239 "api key",
240 "api-key",
241 "api_key",
242 "apikey",
243 "access token",
244 "access-token",
245 "access_token",
246 "authorization:",
247 "bearer ",
248 "password",
249 "passwd",
250 "private key",
251 "secret",
252 "token ",
253 "token=",
254 "token:",
255 ]
256 .iter()
257 .any(|marker| lower.contains(marker));
258 has_secret_marker || contains_absolute_path(text)
259}
260
261fn contains_absolute_path(text: &str) -> bool {
262 text.char_indices().any(|(index, character)| {
263 if character == '/' {
264 let previous = text[..index].chars().next_back();
265 let next = text[index + 1..].chars().next();
266 let starts_path = previous.is_none_or(|character| {
267 character.is_whitespace()
268 || matches!(character, '`' | '\'' | '"' | '(' | '[' | '{' | '=' | ':')
269 });
270 let is_url = previous == Some(':') && next == Some('/');
271 starts_path && next.is_some_and(|character| character != '/') && !is_url
272 } else {
273 let candidate = &text[index..];
274 looks_like_windows_absolute(candidate)
275 && text[..index].chars().next_back().is_none_or(|character| {
276 character.is_whitespace()
277 || matches!(character, '`' | '\'' | '"' | '(' | '[' | '{' | '=' | ':')
278 })
279 }
280 })
281}
282
283fn looks_like_windows_absolute(path: &str) -> bool {
284 let bytes = path.as_bytes();
285 (bytes.len() >= 3
286 && bytes[0].is_ascii_alphabetic()
287 && bytes[1] == b':'
288 && matches!(bytes[2], b'\\' | b'/'))
289 || path.starts_with("\\\\")
290}
291
292fn existing_path_is_inside(path: &Path, project_root: &Path) -> bool {
300 let mut existing = path;
301 while !existing.exists() {
302 let Some(parent) = existing.parent() else {
303 return false;
304 };
305 existing = parent;
306 }
307 std::fs::canonicalize(existing).is_ok_and(|canonical| canonical.starts_with(project_root))
308}
309
310fn project_relative(path: &Path, project_root: &Path) -> Option<String> {
311 let project_root = &canonical_or_lexical(project_root);
316 let raw = path.to_string_lossy();
317 if cfg!(not(windows)) && looks_like_windows_absolute(&raw) {
318 return None;
319 }
320 let joined = if path.is_absolute() {
321 path.to_path_buf()
322 } else {
323 project_root.join(path)
324 };
325 let normalized = lexical_normalize(&joined)?;
326 if !existing_path_is_inside(&normalized, project_root) {
327 return None;
328 }
329 let relative = normalized.strip_prefix(project_root).ok()?;
330 if relative.as_os_str().is_empty() {
331 return None;
332 }
333 Some(relative.to_string_lossy().replace('\\', "/"))
334}
335
336fn canonical_or_lexical(path: &Path) -> PathBuf {
337 std::fs::canonicalize(path)
338 .ok()
339 .or_else(|| lexical_normalize(path))
340 .unwrap_or_else(|| path.to_path_buf())
341}
342
343fn lexical_normalize(path: &Path) -> Option<PathBuf> {
344 let mut normalized = PathBuf::new();
345 for component in path.components() {
346 match component {
347 Component::CurDir => {}
348 Component::ParentDir => {
349 if !normalized.pop() {
350 return None;
351 }
352 }
353 Component::Prefix(prefix) => normalized.push(prefix.as_os_str()),
354 Component::RootDir => normalized.push(component.as_os_str()),
355 Component::Normal(part) => normalized.push(part),
356 }
357 }
358 Some(normalized)
359}
360
361#[cfg(test)]
362mod tests {
363 use std::path::Path;
364
365 use rusqlite::Connection;
366 use tempfile::tempdir;
367
368 use super::{contains_sensitive_material, import_from_db, project_relative};
369
370 fn create_fixture(path: &Path, current: &Path, other: &Path) {
371 let db = Connection::open(path).unwrap();
372 db.execute_batch(
373 "CREATE TABLE project (id TEXT PRIMARY KEY, worktree TEXT NOT NULL);
374 CREATE TABLE session (id TEXT PRIMARY KEY, project_id TEXT NOT NULL, time_updated INTEGER NOT NULL);
375 CREATE TABLE message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, data TEXT NOT NULL);
376 CREATE TABLE part (id TEXT PRIMARY KEY, message_id TEXT NOT NULL, session_id TEXT NOT NULL, time_created INTEGER NOT NULL, data TEXT NOT NULL);",
377 ).unwrap();
378 db.execute(
379 "INSERT INTO project (id, worktree) VALUES ('p1', ?1), ('p2', ?2)",
380 [current.to_str().unwrap(), other.to_str().unwrap()],
381 )
382 .unwrap();
383 db.execute(
384 "INSERT INTO session (id, project_id, time_updated) VALUES ('s1', 'p1', 2), ('s2', 'p2', 1)",
385 [],
386 )
387 .unwrap();
388 db.execute(
389 "INSERT INTO message (id, session_id, time_created, data) VALUES
390 ('m1', 's1', 1, '{\"role\":\"assistant\"}'), ('m2', 's2', 2, '{\"role\":\"assistant\"}')",
391 [],
392 ).unwrap();
393 db.execute(
394 "INSERT INTO part (id, message_id, session_id, time_created, data) VALUES
395 ('a', 'm1', 's1', 1, '{\"type\":\"text\",\"text\":\"We decided to use a bounded cache.\"}'),
396 ('b', 'm1', 's1', 2, '{\"type\":\"tool\",\"tool\":\"read\",\"state\":{\"status\":\"completed\",\"input\":{\"filePath\":\"src/lib.rs\",\"token\":\"TOP_SECRET\"},\"output\":\"PRIVATE_OUTPUT\"}}'),
397 ('c', 'm1', 's1', 3, '{\"type\":\"tool\",\"tool\":\"bash\",\"state\":{\"status\":\"error\",\"error\":\"Build failed\"}}'),
398 ('d', 'm1', 's1', 4, '{\"type\":\"tool\",\"tool\":\"read\",\"state\":{\"input\":{\"filePath\":\"../secret.txt\"}}}'),
399 ('e', 'm2', 's2', 5, '{\"type\":\"tool\",\"tool\":\"read\",\"state\":{\"input\":{\"filePath\":\"other.txt\"}}}'),
400 ('f', 'm1', 's1', 6, '{\"type\":\"patch\",\"files\":[\"src/patch.rs\",\"../outside.rs\"]}'),
401 ('g', 'm1', 's1', 7, '{\"type\":\"snapshot\",\"path\":\"ignored.txt\"}'),
402 ('h', 'm1', 's1', 8, 'not-json'),
403 ('i', 'm1', 's1', 9, '{\"type\":\"text\",\"text\":\"We decided to use /home/alice/private/key. We chose safe fallback.\"}'),
404 ('j', 'm1', 's1', 10, '{\"type\":\"tool\",\"state\":{\"error\":\"Build failed at /home/alice/private/key token=TOP_SECRET\"}}')",
405 [],
406 ).unwrap();
407 }
408
409 #[test]
410 fn imports_only_current_project_and_filters_unsafe_paths() {
411 let temp = tempdir().unwrap();
412 let current = temp.path().join("current");
413 let other = temp.path().join("other");
414 std::fs::create_dir_all(current.join("src")).unwrap();
415 std::fs::write(current.join("src/lib.rs"), "fixture").unwrap();
416 std::fs::write(current.join("src/patch.rs"), "fixture").unwrap();
417 std::fs::create_dir_all(&other).unwrap();
418 let db = temp.path().join("opencode.db");
419 create_fixture(&db, ¤t, &other);
420
421 let result = import_from_db(&db, ¤t);
422
423 assert_eq!(result.sessions_found, 1);
424 assert_eq!(result.files_touched, 2);
425 assert!(
426 result
427 .facts
428 .iter()
429 .any(|fact| fact.value == "Touched file: src/lib.rs")
430 );
431 assert!(
432 result
433 .facts
434 .iter()
435 .any(|fact| fact.category == "imported-decision")
436 );
437 assert!(
438 result
439 .facts
440 .iter()
441 .any(|fact| fact.value == "Observed error: Build failed")
442 );
443 assert!(
444 result
445 .facts
446 .iter()
447 .any(|fact| fact.value == "Touched file: src/patch.rs")
448 );
449 assert!(
450 result
451 .errors
452 .iter()
453 .any(|error| error.contains("malformed"))
454 );
455 assert!(result.facts.iter().all(|fact| {
456 ![
457 "secret.txt",
458 "outside.rs",
459 "other.txt",
460 "ignored.txt",
461 "TOP_SECRET",
462 "PRIVATE_OUTPUT",
463 "/home/alice/private/key",
464 ]
465 .iter()
466 .any(|private| fact.value.contains(private))
467 && fact.source_session == "opencode:s1"
468 && fact.imported_from.as_deref() == Some("opencode")
469 }));
470 }
471
472 #[test]
473 fn sensitive_material_filter_handles_punctuation_and_marker_variants() {
474 for value in [
475 "read `/home/user/key`",
476 "read (/home/user/key)",
477 "path=/home/user/key",
478 "read \"/home/user/key\"",
479 "API key abc",
480 "api-key=abc",
481 "access_token=abc",
482 "token abc",
483 "read `C:\\Users\\user\\key`",
484 ] {
485 assert!(contains_sensitive_material(value), "not rejected: {value}");
486 }
487 for value in [
488 "We decided to use a bounded cache",
489 "See https://example.com/path",
490 "relative/path.rs changed",
491 ] {
492 assert!(
493 !contains_sensitive_material(value),
494 "false positive: {value}"
495 );
496 }
497 }
498
499 #[test]
500 fn path_filter_rejects_windows_and_symlink_escapes() {
501 let temp = tempdir().unwrap();
502 let project = temp.path().join("project");
503 let outside = temp.path().join("outside");
504 std::fs::create_dir_all(&project).unwrap();
505 std::fs::create_dir_all(&outside).unwrap();
506
507 assert_eq!(
508 project_relative(Path::new("src/new.rs"), &project).as_deref(),
509 Some("src/new.rs")
510 );
511 assert!(project_relative(Path::new("../outside/file.rs"), &project).is_none());
512 assert!(project_relative(Path::new(r"C:\outside\file.rs"), &project).is_none());
513 assert!(project_relative(Path::new(r"\\server\share\file.rs"), &project).is_none());
514
515 #[cfg(unix)]
516 {
517 std::os::unix::fs::symlink(&outside, project.join("link")).unwrap();
518 assert!(project_relative(Path::new("link/file.rs"), &project).is_none());
519 }
520 }
521
522 #[test]
523 fn missing_database_is_empty() {
524 let temp = tempdir().unwrap();
525 let result = import_from_db(&temp.path().join("missing.db"), temp.path());
526 assert_eq!(result.sessions_found, 0);
527 assert!(result.errors.is_empty());
528 }
529}