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