lean_ctx_ext/core/import/
codex.rs1use std::collections::HashSet;
5use std::path::{Path, PathBuf};
6
7use rusqlite::{Connection, types::ValueRef};
8use serde_json::Value;
9
10use super::database::{DatabaseSnapshot, snapshot_history_database};
11use super::{
12 ImportResult, ImportSource, SourceRefusal, finish_result, home_dir, push_error, read_json_file,
13 read_jsonl_files, session_id, staging,
14};
15
16const MAX_SQLITE_ROWS_PER_TABLE: usize = 10_000;
17const MAX_SCAN_DEPTH: usize = 8;
18
19#[must_use]
21pub fn import() -> ImportResult {
22 let Some(home) = home_dir() else {
23 return ImportResult::default();
24 };
25 import_from_root(&home.join(".codex"))
26}
27
28#[must_use]
30pub fn import_from_root(root: &Path) -> ImportResult {
31 if !root.exists() {
32 return ImportResult::default();
33 }
34
35 let mut jsonl = Vec::new();
36 let mut json = Vec::new();
37 let mut sqlite = Vec::new();
38 let mut errors = Vec::new();
39 collect_files(root, 0, &mut jsonl, &mut json, &mut sqlite, &mut errors);
40 jsonl.sort();
41 json.sort();
42 sqlite.sort();
43
44 let mut result = read_jsonl_files(ImportSource::Codex, root, jsonl);
45 for path in json {
46 result.merge(read_json_file(ImportSource::Codex, root, &path));
47 }
48 for path in sqlite {
49 match snapshot_history_database(root, &path) {
59 Ok(snapshot) => result.merge(read_sqlite_file(root, &snapshot)),
60 Err(refusal) => result.refuse(refusal),
61 }
62 }
63 for error in errors {
64 push_error(&mut result, error);
65 }
66 result
67}
68
69fn collect_files(
70 dir: &Path,
71 depth: usize,
72 jsonl: &mut Vec<PathBuf>,
73 json: &mut Vec<PathBuf>,
74 sqlite: &mut Vec<PathBuf>,
75 errors: &mut Vec<String>,
76) {
77 if depth > MAX_SCAN_DEPTH {
78 return;
79 }
80 let entries = match std::fs::read_dir(dir) {
81 Ok(entries) => entries,
82 Err(error) => {
83 errors.push(format!("{}: {error}", dir.display()));
84 return;
85 }
86 };
87 for entry in entries {
88 let entry = match entry {
89 Ok(entry) => entry,
90 Err(error) => {
91 errors.push(format!("{}: {error}", dir.display()));
92 continue;
93 }
94 };
95 let path = entry.path();
96 if path.is_dir() {
97 collect_files(&path, depth + 1, jsonl, json, sqlite, errors);
98 } else if path.is_file() {
99 match path.extension().and_then(|extension| extension.to_str()) {
100 Some("jsonl") => jsonl.push(path),
101 Some("json") if is_named_session_file(&path) => json.push(path),
102 Some("sqlite" | "sqlite3" | "db") => sqlite.push(path),
103 _ => {}
104 }
105 }
106 }
107}
108
109fn is_named_session_file(path: &Path) -> bool {
110 let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
111 return false;
112 };
113 let name = name.to_ascii_lowercase();
114 ["history", "session", "rollout", "transcript"]
115 .iter()
116 .any(|marker| name.contains(marker))
117}
118
119fn read_sqlite_file(root: &Path, snapshot: &DatabaseSnapshot) -> ImportResult {
128 let path = snapshot.source_path();
131 let (pending, read) =
132 staging::read_database(root, path, |pending| read_rows(snapshot, pending));
133 let session = session_id(ImportSource::Codex, path, pending.rules());
134 let mut result = ImportResult::default();
135 let mut touched = HashSet::new();
136 let mut seen = HashSet::new();
137 match pending.settle(
138 read,
139 ImportSource::Codex,
140 &session,
141 &mut result,
142 &mut touched,
143 &mut seen,
144 ) {
145 Ok(()) => result.sessions_found = 1,
146 Err(refusal) => {
149 let label = path.display().to_string();
150 push_error(&mut result, staging::not_imported(&label, refusal));
151 }
152 }
153 finish_result(&mut result, &touched);
154 result
155}
156
157fn read_rows(
160 snapshot: &DatabaseSnapshot,
161 pending: &mut staging::Pending,
162) -> Result<(), SourceRefusal> {
163 let unreadable = |_: rusqlite::Error| SourceRefusal::DatabaseUnreadable;
164 let connection = snapshot.open().map_err(unreadable)?;
165 for table in tables(&connection).map_err(unreadable)? {
166 let query = format!(
167 "SELECT * FROM {} LIMIT {MAX_SQLITE_ROWS_PER_TABLE}",
168 quote_identifier(&table)
169 );
170 let mut statement = connection.prepare(&query).map_err(unreadable)?;
171 let columns = statement.column_count();
172 let mut rows = statement.query([]).map_err(unreadable)?;
173 while let Some(row) = rows.next().map_err(unreadable)? {
174 for column in 0..columns {
175 let Ok(ValueRef::Text(bytes)) = row.get_ref(column) else {
176 continue;
177 };
178 let text = String::from_utf8_lossy(bytes);
179 let original = serde_json::from_str::<Value>(&text)
180 .unwrap_or_else(|_| Value::String(text.into_owned()));
181 let Some(value) = pending.admit(original) else {
185 continue;
186 };
187 staging::select(&value, |found| pending.stage(found));
188 }
189 }
190 }
191 Ok(())
192}
193
194fn tables(connection: &Connection) -> rusqlite::Result<Vec<String>> {
195 let mut statement = connection.prepare(
196 "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",
197 )?;
198 statement
199 .query_map([], |row| row.get(0))?
200 .collect::<rusqlite::Result<Vec<String>>>()
201}
202
203fn quote_identifier(identifier: &str) -> String {
204 format!("\"{}\"", identifier.replace('\"', "\"\""))
205}