complete secondary import migrations

This commit is contained in:
charlesgong-openai
2026-07-09 20:14:50 -04:00
parent 00e21e5036
commit daa735cfea
18 changed files with 1250 additions and 102 deletions
@@ -0,0 +1,182 @@
use crate::ExternalAgentSessionMigration;
use crate::ledger::load_import_ledger;
use crate::ledger::save_import_ledger;
use crate::now_unix_seconds;
use crate::records::summarize_session_with_cwd;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
use std::time::Duration;
const SESSION_IMPORT_MAX_COUNT: usize = 50;
const SESSION_IMPORT_MAX_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
pub fn detect_recent_cursor_sessions(
external_agent_home: &Path,
codex_home: &Path,
) -> io::Result<Vec<ExternalAgentSessionMigration>> {
let projects_root = external_agent_home.join("projects");
if !projects_root.is_dir() {
return Ok(Vec::new());
}
let now = now_unix_seconds();
let mut ledger = load_import_ledger(codex_home)?;
let source_states = ledger.source_states();
let mut candidates = BinaryHeap::with_capacity(SESSION_IMPORT_MAX_COUNT + 1);
for project_entry in fs::read_dir(projects_root)? {
let Ok(project_entry) = project_entry else {
continue;
};
let project_storage = project_entry.path();
if !project_storage.is_dir() {
continue;
}
let Some(cwd) = cursor_project_cwd(&project_storage) else {
continue;
};
for path in cursor_transcript_files(&project_storage.join("agent-transcripts")) {
let Ok(metadata) = fs::metadata(&path) else {
continue;
};
let Ok(modified_at) = metadata.modified() else {
continue;
};
let Ok(modified_at) = modified_at.duration_since(std::time::UNIX_EPOCH) else {
continue;
};
if (modified_at.as_secs() as i64)
< now.saturating_sub(SESSION_IMPORT_MAX_AGE.as_secs() as i64)
{
continue;
}
let Ok(modified_at_nanos) = i64::try_from(modified_at.as_nanos()) else {
continue;
};
let Ok(source_path) = fs::canonicalize(&path) else {
continue;
};
if let Some(state) = source_states.get(source_path.as_path())
&& (state.source_modified_at == Some(modified_at_nanos)
|| state.source_modified_at.is_none()
&& modified_at.as_secs() as i64 <= state.imported_at)
{
continue;
}
candidates.push((Reverse(modified_at_nanos), path, cwd.clone()));
if candidates.len() > SESSION_IMPORT_MAX_COUNT {
candidates.pop();
}
}
}
drop(source_states);
let mut migrations = Vec::new();
let mut ledger_changed = false;
for (modified_at, path, cwd) in candidates.into_sorted_vec() {
match ledger.refresh_current_source(&path, modified_at.0) {
Ok(false) => {}
Ok(true) => {
ledger_changed = true;
continue;
}
Err(_) => continue,
}
let Ok(Some(summary)) = summarize_session_with_cwd(&path, Some(&cwd)) else {
continue;
};
migrations.push(summary.migration);
}
if ledger_changed {
save_import_ledger(codex_home, &ledger)?;
}
Ok(migrations)
}
fn cursor_transcript_files(transcripts_root: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
let mut pending = vec![transcripts_root.to_path_buf()];
while let Some(directory) = pending.pop() {
let Ok(entries) = fs::read_dir(directory) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
if entry.file_name() != "subagents" {
pending.push(path);
}
} else if file_type.is_file()
&& path.extension().and_then(|extension| extension.to_str()) == Some("jsonl")
{
files.push(path);
}
}
}
files.sort();
files
}
fn cursor_project_cwd(project_storage: &Path) -> Option<PathBuf> {
let encoded = project_storage.file_name()?.to_str()?;
decode_cursor_project_path(encoded)
}
#[cfg(not(windows))]
fn decode_cursor_project_path(encoded: &str) -> Option<PathBuf> {
decode_cursor_project_path_from(encoded, Path::new("/"), /*depth*/ 0).or_else(|| {
encoded.strip_prefix('-').and_then(|encoded| {
decode_cursor_project_path_from(encoded, Path::new("/"), /*depth*/ 0)
})
})
}
#[cfg(windows)]
fn decode_cursor_project_path(encoded: &str) -> Option<PathBuf> {
let (drive, remaining) = encoded.split_once('-')?;
if drive.len() != 1 || !drive.as_bytes()[0].is_ascii_alphabetic() {
return None;
}
let base = PathBuf::from(format!("{drive}:\\"));
decode_cursor_project_path_from(remaining, &base, /*depth*/ 0).or_else(|| {
remaining.strip_prefix('-').and_then(|remaining| {
decode_cursor_project_path_from(remaining, &base, /*depth*/ 0)
})
})
}
fn decode_cursor_project_path_from(encoded: &str, base: &Path, depth: usize) -> Option<PathBuf> {
if encoded.is_empty() || depth > 32 {
return None;
}
let whole = base.join(encoded);
if whole.is_dir() {
return Some(whole);
}
for (index, _) in encoded.match_indices('-') {
let segment = &encoded[..index];
if segment.is_empty() {
continue;
}
let candidate = base.join(segment);
if !candidate.is_dir() {
continue;
}
if let Some(path) =
decode_cursor_project_path_from(&encoded[index + 1..], &candidate, depth + 1)
{
return Some(path);
}
}
None
}
#[cfg(test)]
#[path = "detect_cursor_tests.rs"]
mod tests;
@@ -0,0 +1,51 @@
use super::*;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
#[test]
fn detects_cursor_transcript_with_project_cwd() {
let root = TempDir::new().expect("tempdir");
let project_root = root.path().join("workspace-with-dashes");
fs::create_dir_all(&project_root).expect("project root");
let external_agent_home = root.path().join(".cursor");
let encoded_project = encode_project_path(&project_root);
let session_id = "a-session";
let transcript = external_agent_home
.join("projects")
.join(encoded_project)
.join("agent-transcripts")
.join(session_id)
.join(format!("{session_id}.jsonl"));
fs::create_dir_all(transcript.parent().expect("transcript parent"))
.expect("transcript directory");
fs::write(
&transcript,
concat!(
"{\"role\":\"user\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"first request\"}]}}\n",
"{\"role\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"first answer\"}]}}\n"
),
)
.expect("transcript");
let sessions =
detect_recent_cursor_sessions(&external_agent_home, root.path()).expect("detect sessions");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: transcript,
cwd: project_root,
title: Some("first request".to_string()),
}]
);
}
#[cfg(not(windows))]
fn encode_project_path(path: &Path) -> String {
path.to_string_lossy().replace('/', "-")
}
#[cfg(windows)]
fn encode_project_path(path: &Path) -> String {
path.to_string_lossy().replace([':', '\\'], "-")
}
@@ -1,7 +1,7 @@
use crate::ConversationMessage;
use crate::ImportedExternalAgentSession;
use crate::MessageRole;
use crate::records::read_session_import;
use crate::records::read_session_import_with_cwd;
use crate::summarize_for_label;
use crate::title::IMPORTED_SESSION_FALLBACK_TITLE;
use crate::title::SessionTitleCandidates;
@@ -26,15 +26,16 @@ const EXTERNAL_SESSION_IMPORTED_MARKER: &str = "<EXTERNAL SESSION IMPORTED>";
#[cfg(test)]
fn load_session_for_import(path: &Path) -> io::Result<Option<ImportedExternalAgentSession>> {
Ok(
load_session_for_import_with_content_sha256(path)?
load_session_for_import_with_content_sha256(path, /*fallback_cwd*/ None)?
.map(|(session, _content_sha256)| session),
)
}
pub(crate) fn load_session_for_import_with_content_sha256(
path: &Path,
fallback_cwd: Option<&Path>,
) -> io::Result<Option<(ImportedExternalAgentSession, String)>> {
let parsed = read_session_import(path)?;
let parsed = read_session_import_with_cwd(path, fallback_cwd)?;
let Some(cwd) = parsed.cwd else {
return Ok(None);
};
+5 -2
View File
@@ -1,6 +1,7 @@
//! Parsing and export helpers for external-agent session histories.
mod detect;
mod detect_cursor;
mod export;
mod ledger;
mod records;
@@ -12,6 +13,7 @@ use std::path::Path;
use std::path::PathBuf;
pub use detect::detect_recent_sessions;
pub use detect_cursor::detect_recent_cursor_sessions;
use export::load_session_for_import_with_content_sha256;
pub use ledger::CompletedExternalAgentSessionImport;
pub use ledger::has_current_session_been_imported;
@@ -52,7 +54,7 @@ pub fn prepare_validated_session_import(
return Ok(None);
}
let Some((source_path, imported_session, source_content_sha256)) =
load_importable_session(&session.path)?
load_importable_session(&session.path, &session.cwd)?
else {
return Ok(None);
};
@@ -65,10 +67,11 @@ pub fn prepare_validated_session_import(
fn load_importable_session(
path: &Path,
fallback_cwd: &Path,
) -> io::Result<Option<(PathBuf, ImportedExternalAgentSession, String)>> {
let source_path = std::fs::canonicalize(path)?;
let Some((imported_session, source_content_sha256)) =
load_session_for_import_with_content_sha256(&source_path)?
load_session_for_import_with_content_sha256(&source_path, Some(fallback_cwd))?
else {
return Ok(None);
};
@@ -34,9 +34,17 @@ pub(super) struct ParsedSessionImport {
}
pub fn summarize_session(path: &Path) -> io::Result<Option<SessionSummary>> {
summarize_session_with_cwd(path, /*fallback_cwd*/ None)
}
pub(crate) fn summarize_session_with_cwd(
path: &Path,
fallback_cwd: Option<&Path>,
) -> io::Result<Option<SessionSummary>> {
let file = File::open(path)?;
let fallback_timestamp = fallback_cwd.and_then(|_| file_modified_at_seconds(&file));
let reader = BufReader::new(file);
let mut cwd = None;
let mut cwd = fallback_cwd.map(Path::to_path_buf);
let mut custom_title = None;
let mut ai_title = None;
let mut fallback_title = None;
@@ -65,7 +73,8 @@ pub fn summarize_session(path: &Path) -> io::Result<Option<SessionSummary>> {
if let Some(title) = ai_title_from_record(&record) {
ai_title = Some(title.to_string());
}
let Some(message) = conversation_message_from_owned_record(&mut record) else {
let Some(message) = conversation_message_from_owned_record(&mut record, fallback_timestamp)
else {
continue;
};
saw_message = true;
@@ -107,10 +116,19 @@ pub fn summarize_session(path: &Path) -> io::Result<Option<SessionSummary>> {
}))
}
#[cfg(test)]
pub(super) fn read_session_import(path: &Path) -> io::Result<ParsedSessionImport> {
read_session_import_with_cwd(path, /*fallback_cwd*/ None)
}
pub(super) fn read_session_import_with_cwd(
path: &Path,
fallback_cwd: Option<&Path>,
) -> io::Result<ParsedSessionImport> {
let file = File::open(path)?;
let fallback_timestamp = fallback_cwd.and_then(|_| file_modified_at_seconds(&file));
let mut reader = BufReader::new(file);
let mut cwd = None;
let mut cwd = fallback_cwd.map(Path::to_path_buf);
let mut custom_title = None;
let mut ai_title = None;
let mut messages = Vec::new();
@@ -141,7 +159,9 @@ pub(super) fn read_session_import(path: &Path) -> io::Result<ParsedSessionImport
if let Some(title) = ai_title_from_record(&record) {
ai_title = Some(title.to_string());
}
if let Some(message) = conversation_message_from_owned_record(&mut record) {
if let Some(message) =
conversation_message_from_owned_record(&mut record, fallback_timestamp)
{
messages.push(message);
}
}
@@ -170,8 +190,14 @@ fn title_from_record<'a>(record: &'a JsonValue, record_type: &str, field: &str)
.filter(|title| !title.is_empty())
}
fn conversation_message_from_owned_record(record: &mut JsonValue) -> Option<ConversationMessage> {
let record_type = record.get("type")?.as_str()?;
fn conversation_message_from_owned_record(
record: &mut JsonValue,
fallback_timestamp: Option<i64>,
) -> Option<ConversationMessage> {
let record_type = record
.get("type")
.or_else(|| record.get("role"))?
.as_str()?;
if record_type != "assistant" && record_type != "user" {
return None;
}
@@ -185,7 +211,14 @@ fn conversation_message_from_owned_record(record: &mut JsonValue) -> Option<Conv
let timestamp = record
.get("timestamp")
.and_then(JsonValue::as_str)
.and_then(parse_timestamp);
.and_then(parse_timestamp)
.or_else(|| {
record
.get("timestamp_ms")
.and_then(JsonValue::as_i64)
.map(|value| value / 1_000)
})
.or(fallback_timestamp);
let content = record.get_mut("message")?.get_mut("content")?.take();
let extracted = match content {
JsonValue::String(text) => {
@@ -210,6 +243,16 @@ fn conversation_message_from_owned_record(record: &mut JsonValue) -> Option<Conv
})
}
fn file_modified_at_seconds(file: &File) -> Option<i64> {
file.metadata()
.ok()?
.modified()
.ok()?
.duration_since(std::time::UNIX_EPOCH)
.ok()
.and_then(|duration| i64::try_from(duration.as_secs()).ok())
}
struct ExtractedMessage {
text: String,
only_tool_result: bool,