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
@@ -20,6 +20,7 @@ use codex_core_plugins::marketplace_add::is_local_marketplace_source;
use codex_external_agent_migration::count_missing_subagents;
use codex_external_agent_migration::missing_subagent_names;
use codex_external_agent_sessions::ExternalAgentSessionMigration;
use codex_external_agent_sessions::detect_recent_cursor_sessions;
use codex_external_agent_sessions::detect_recent_sessions;
use codex_plugin::PluginId;
use codex_protocol::protocol::Product;
@@ -479,7 +480,7 @@ impl ExternalAgentConfigService {
let cwd = repo_root.map(Path::to_path_buf);
let source_settings = self.source_settings(repo_root);
let settings = if self.source.supports(SourceFeature::Config) {
effective_external_settings(&source_settings)?
self.effective_source_settings(repo_root)?
} else {
None
};
@@ -488,7 +489,7 @@ impl ExternalAgentConfigService {
|repo_root| repo_root.join(".codex").join("config.toml"),
);
if let Some(settings) = settings.as_ref() {
let migrated = build_config_from_external(settings)?;
let migrated = build_config_from_external(settings, self.source)?;
if !is_empty_toml_table(&migrated) {
let mut should_include = true;
if target_config.exists() {
@@ -719,9 +720,7 @@ impl ExternalAgentConfigService {
);
}
if self.source.supports(SourceFeature::Plugins)
&& let Some(settings) = settings.as_ref()
{
if self.source.supports(SourceFeature::Plugins) {
match ConfigBuilder::default()
.codex_home(self.codex_home.clone())
.fallback_cwd(Some(self.codex_home.clone()))
@@ -748,14 +747,26 @@ impl ExternalAgentConfigService {
&config,
&PluginsManager::new(self.codex_home.clone()),
)?;
if let Some(item) = self.detect_plugin_migration(
source_settings.as_path(),
repo_root.unwrap_or(self.external_agent_home.as_path()),
cwd.clone(),
settings,
&configured_plugin_ids,
&configured_marketplace_plugins,
) {
let item = match self.source {
ExternalAgentSource::Cl => settings.as_ref().and_then(|settings| {
self.detect_plugin_migration(
source_settings.as_path(),
repo_root.unwrap_or(self.external_agent_home.as_path()),
cwd.clone(),
settings,
&configured_plugin_ids,
&configured_marketplace_plugins,
)
}),
ExternalAgentSource::Cu if repo_root.is_none() => self
.detect_cursor_plugin_migration(
cwd.clone(),
&configured_plugin_ids,
&configured_marketplace_plugins,
)?,
ExternalAgentSource::Cu => None,
};
if let Some(item) = item {
items.push(item);
}
}
@@ -770,7 +781,14 @@ impl ExternalAgentConfigService {
}
if repo_root.is_none() && self.source.supports(SourceFeature::Sessions) {
let sessions = detect_recent_sessions(&self.external_agent_home, &self.codex_home)?;
let sessions = match self.source {
ExternalAgentSource::Cl => {
detect_recent_sessions(&self.external_agent_home, &self.codex_home)?
}
ExternalAgentSource::Cu => {
detect_recent_cursor_sessions(&self.external_agent_home, &self.codex_home)?
}
};
if !sessions.is_empty() {
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Sessions,
@@ -810,7 +828,19 @@ impl ExternalAgentConfigService {
}
fn source_settings(&self, repo_root: Option<&Path>) -> PathBuf {
self.source_config_dir(repo_root).join("settings.json")
self.source_config_dir(repo_root)
.join(self.source.settings_file_name(repo_root.is_some()))
}
fn effective_source_settings(&self, repo_root: Option<&Path>) -> io::Result<Option<JsonValue>> {
let source_settings = self.source_settings(repo_root);
match self.source {
ExternalAgentSource::Cl => effective_external_settings(&source_settings),
ExternalAgentSource::Cu => source_cu::effective_settings(
self.source_config_dir(repo_root).as_path(),
&source_settings,
),
}
}
fn build_mcp_config(
@@ -849,8 +879,8 @@ impl ExternalAgentConfigService {
source_settings: Option<JsonValue>,
) -> io::Result<Option<JsonValue>> {
if repo_root.is_some() && source_settings.is_none() {
let home_settings = self.external_agent_home.join("settings.json");
match effective_external_settings(&home_settings) {
let home_settings = self.source_settings(/*repo_root*/ None);
match self.effective_source_settings(/*repo_root*/ None) {
Ok(settings) => Ok(settings),
Err(err) => {
tracing::warn!(
@@ -908,16 +938,86 @@ impl ExternalAgentConfigService {
})
}
fn detect_cursor_plugin_migration(
&self,
cwd: Option<PathBuf>,
configured_plugin_ids: &HashSet<String>,
configured_marketplace_plugins: &BTreeMap<String, HashSet<String>>,
) -> io::Result<Option<ExternalAgentConfigMigrationItem>> {
let mut plugins = Vec::new();
for marketplace in source_cu::cached_marketplace_plugins(&self.external_agent_home)? {
let configured_marketplace = configured_marketplace_plugins.get(&marketplace.name);
let plugin_names = marketplace
.plugin_names
.into_iter()
.filter(|plugin_name| {
!configured_plugin_ids.contains(&format!("{plugin_name}@{}", marketplace.name))
&& !configured_marketplace
.is_some_and(|plugins| plugins.contains(plugin_name))
})
.collect::<Vec<_>>();
if !plugin_names.is_empty() {
plugins.push(PluginsMigration {
marketplace_name: marketplace.name,
plugin_names,
});
}
}
if plugins.is_empty() {
return Ok(None);
}
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Plugins,
/*skills_count*/ None,
);
Ok(Some(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Plugins,
description: format!(
"Migrate cached plugins from {}",
self.external_agent_home.join("plugins/cache").display()
),
cwd,
details: Some(MigrationDetails {
plugins,
..Default::default()
}),
}))
}
fn cursor_marketplace_import_sources(
&self,
) -> io::Result<BTreeMap<String, MarketplaceImportSource>> {
Ok(
source_cu::cached_marketplace_plugins(&self.external_agent_home)?
.into_iter()
.map(|marketplace| {
(
marketplace.name,
MarketplaceImportSource {
source: marketplace.source.display().to_string(),
ref_name: None,
},
)
})
.collect(),
)
}
fn partition_plugin_migration_details(
&self,
cwd: Option<&Path>,
details: MigrationDetails,
) -> io::Result<(Option<MigrationDetails>, Option<MigrationDetails>)> {
let source_settings = self.source_settings(cwd);
let source_root = cwd.unwrap_or(self.external_agent_home.as_path());
let import_sources = effective_external_settings(&source_settings)?
.map(|settings| self.marketplace_import_sources(&settings, source_root))
.unwrap_or_default();
let import_sources = match self.source {
ExternalAgentSource::Cl => {
let source_root = cwd.unwrap_or(self.external_agent_home.as_path());
self.effective_source_settings(cwd)?
.map(|settings| self.marketplace_import_sources(&settings, source_root))
.unwrap_or_default()
}
ExternalAgentSource::Cu => self.cursor_marketplace_import_sources()?,
};
let mut local_plugins = Vec::new();
let mut remote_plugins = Vec::new();
@@ -978,11 +1078,15 @@ impl ExternalAgentConfigService {
if let Some(analytics_events_client) = self.analytics_events_client.clone() {
plugins_manager.set_analytics_events_client(analytics_events_client);
}
let source_settings = self.source_settings(cwd);
let source_root = cwd.unwrap_or(self.external_agent_home.as_path());
let import_sources = effective_external_settings(&source_settings)?
.map(|settings| self.marketplace_import_sources(&settings, source_root))
.unwrap_or_default();
let import_sources = match self.source {
ExternalAgentSource::Cl => {
let source_root = cwd.unwrap_or(self.external_agent_home.as_path());
self.effective_source_settings(cwd)?
.map(|settings| self.marketplace_import_sources(&settings, source_root))
.unwrap_or_default()
}
ExternalAgentSource::Cu => self.cursor_marketplace_import_sources()?,
};
for plugin_group in plugins {
let marketplace_name = plugin_group.marketplace_name.clone();
let plugin_names = plugin_group.plugin_names;
@@ -1215,14 +1319,14 @@ impl ExternalAgentConfigService {
return Ok(None);
} else {
(
self.external_agent_home.join("settings.json"),
self.source_settings(/*repo_root*/ None),
self.codex_home.join("config.toml"),
)
};
let Some(settings) = effective_external_settings(&source_settings)? else {
let Some(settings) = self.effective_source_settings(repo_root.as_deref())? else {
return Ok(None);
};
let migrated = build_config_from_external(&settings)?;
let migrated = build_config_from_external(&settings, self.source)?;
if is_empty_toml_table(&migrated) {
return Ok(None);
}
@@ -1261,21 +1365,15 @@ impl ExternalAgentConfigService {
fn import_mcp_server_config(&self, cwd: Option<&Path>) -> io::Result<Vec<String>> {
let repo_root = find_repo_root(cwd)?;
let (source_settings, target_config) = if let Some(repo_root) = repo_root.as_ref() {
(
self.source_settings(Some(repo_root)),
repo_root.join(".codex").join("config.toml"),
)
let target_config = if let Some(repo_root) = repo_root.as_ref() {
repo_root.join(".codex").join("config.toml")
} else if cwd.is_some_and(|cwd| !cwd.as_os_str().is_empty()) {
return Ok(Vec::new());
} else {
(
self.external_agent_home.join("settings.json"),
self.codex_home.join("config.toml"),
)
self.codex_home.join("config.toml")
};
let settings = if self.source.supports(SourceFeature::Config) {
effective_external_settings(&source_settings)?
self.effective_source_settings(repo_root.as_deref())?
} else {
None
};
@@ -1840,7 +1938,10 @@ fn is_non_empty_text_file(path: &Path) -> io::Result<bool> {
Ok(!fs::read_to_string(path)?.trim().is_empty())
}
fn build_config_from_external(settings: &JsonValue) -> io::Result<TomlValue> {
fn build_config_from_external(
settings: &JsonValue,
source: ExternalAgentSource,
) -> io::Result<TomlValue> {
let Some(settings_obj) = settings.as_object() else {
return Err(invalid_data_error(
"external agent settings root must be an object",
@@ -1864,17 +1965,22 @@ fn build_config_from_external(settings: &JsonValue) -> io::Result<TomlValue> {
);
}
if let Some(sandbox_enabled) = settings_obj
.get("sandbox")
.and_then(JsonValue::as_object)
.and_then(|sandbox| sandbox.get("enabled"))
.and_then(JsonValue::as_bool)
&& sandbox_enabled
{
root.insert(
"sandbox_mode".to_string(),
TomlValue::String("workspace-write".to_string()),
);
match source {
ExternalAgentSource::Cl => {
if settings_obj
.get("sandbox")
.and_then(JsonValue::as_object)
.and_then(|sandbox| sandbox.get("enabled"))
.and_then(JsonValue::as_bool)
== Some(true)
{
root.insert(
"sandbox_mode".to_string(),
TomlValue::String("workspace-write".to_string()),
);
}
}
ExternalAgentSource::Cu => source_cu::append_sandbox_config(&mut root, settings_obj),
}
Ok(TomlValue::Table(root))
@@ -53,7 +53,15 @@ impl ExternalAgentSource {
(
Self::Cu,
SourceFeature::Config | SourceFeature::Plugins | SourceFeature::Sessions,
) => false,
) => true,
}
}
pub(super) fn settings_file_name(self, project_scope: bool) -> &'static str {
match (self, project_scope) {
(Self::Cl, _) => "settings.json",
(Self::Cu, false) => source_cu::HOME_CONFIG_FILE,
(Self::Cu, true) => source_cu::PROJECT_CONFIG_FILE,
}
}
@@ -159,14 +167,14 @@ impl ExternalAgentSource {
) -> io::Result<Vec<String>> {
match self {
Self::Cl => source_cl::source_hook_event_names(source_dir, target_hooks),
Self::Cu => Ok(Vec::new()),
Self::Cu => source_cu::source_hook_event_names(source_dir, target_hooks),
}
}
pub(super) fn import_hooks(self, source_dir: &Path, target_hooks: &Path) -> io::Result<bool> {
match self {
Self::Cl => source_cl::import_source_hooks(source_dir, target_hooks),
Self::Cu => Ok(false),
Self::Cu => source_cu::import_source_hooks(source_dir, target_hooks),
}
}
@@ -3,9 +3,13 @@ use codex_external_agent_migration::CommandMigrationProfile;
use codex_external_agent_migration::RewriteProfile;
use codex_external_agent_migration::build_mcp_config_from_json_file;
use codex_external_agent_migration::count_missing_commands_with_profile;
use codex_external_agent_migration::hook_migration_event_names_from_json_file;
use codex_external_agent_migration::import_commands_with_profile;
use codex_external_agent_migration::import_hooks_from_json_file;
use codex_external_agent_migration::import_subagents_with_rewrite_profile;
use codex_external_agent_migration::missing_command_names_with_profile;
use serde_json::Value as JsonValue;
use std::collections::BTreeSet;
use std::fs;
use std::io;
use std::path::Path;
@@ -17,25 +21,111 @@ use super::source::InstructionSourceGroup;
pub(super) const CONFIG_DIR: &str = ".cursor";
pub(super) const LEGACY_RULES_FILE: &str = ".cursorrules";
pub(super) const REWRITE_PROFILE: RewriteProfile = RewriteProfile::new(
LEGACY_RULES_FILE,
&[
"cursor agent",
"cursor-agent",
"cursor_agent",
"cursoragent",
],
)
.with_case_sensitive_term_variants(&["Cursor"]);
pub(super) const HOME_CONFIG_FILE: &str = "cli-config.json";
pub(super) const PROJECT_CONFIG_FILE: &str = "cli.json";
pub(super) const SANDBOX_CONFIG_FILE: &str = "sandbox.json";
pub(super) const HOOKS_CONFIG_FILE: &str = "hooks.json";
const SANDBOX_SETTINGS_KEY: &str = "__cursorSandbox";
pub(super) const REWRITE_PROFILE: RewriteProfile =
RewriteProfile::new(LEGACY_RULES_FILE, &[]).with_case_sensitive_term_variants(&["Cursor"]);
const COMMAND_MIGRATION_PROFILE: CommandMigrationProfile = CommandMigrationProfile::new(
REWRITE_PROFILE,
CommandDescriptionMode::UseSourceNameFallback,
);
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct CachedMarketplacePlugins {
pub(super) name: String,
pub(super) source: PathBuf,
pub(super) plugin_names: Vec<String>,
}
pub(super) fn build_mcp_config(source_dir: &Path) -> io::Result<TomlValue> {
build_mcp_config_from_json_file(&source_dir.join("mcp.json"))
}
pub(super) fn effective_settings(
source_dir: &Path,
source_settings: &Path,
) -> io::Result<Option<JsonValue>> {
let mut effective = super::read_external_settings(source_settings)?;
let sandbox_settings = super::read_external_settings(&source_dir.join(SANDBOX_CONFIG_FILE))?;
if let Some(sandbox_settings) = sandbox_settings {
let effective = effective.get_or_insert_with(|| JsonValue::Object(serde_json::Map::new()));
let Some(effective) = effective.as_object_mut() else {
return Err(super::invalid_data_error(
"external agent settings root must be an object",
));
};
effective.insert(SANDBOX_SETTINGS_KEY.to_string(), sandbox_settings);
}
Ok(effective)
}
pub(super) fn append_sandbox_config(
root: &mut toml::map::Map<String, TomlValue>,
settings: &serde_json::Map<String, JsonValue>,
) {
let Some(sandbox) = settings
.get(SANDBOX_SETTINGS_KEY)
.and_then(JsonValue::as_object)
else {
return;
};
let sandbox_mode = match sandbox.get("type").and_then(JsonValue::as_str) {
Some("workspace_readwrite") => Some("workspace-write"),
Some("read_only") => Some("read-only"),
_ => None,
};
if let Some(sandbox_mode) = sandbox_mode {
root.insert(
"sandbox_mode".to_string(),
TomlValue::String(sandbox_mode.to_string()),
);
}
if sandbox_mode != Some("workspace-write") {
return;
}
let mut workspace_write = toml::map::Map::new();
if let Some(paths) = sandbox
.get("additionalReadwritePaths")
.and_then(JsonValue::as_array)
{
let paths = paths
.iter()
.filter_map(JsonValue::as_str)
.filter(|path| Path::new(path).is_absolute())
.map(|path| TomlValue::String(path.to_string()))
.collect::<Vec<_>>();
if !paths.is_empty() {
workspace_write.insert("writable_roots".to_string(), TomlValue::Array(paths));
}
}
if sandbox.get("disableTmpWrite").and_then(JsonValue::as_bool) == Some(true) {
workspace_write.insert("exclude_slash_tmp".to_string(), TomlValue::Boolean(true));
workspace_write.insert(
"exclude_tmpdir_env_var".to_string(),
TomlValue::Boolean(true),
);
}
if sandbox
.get("networkPolicy")
.and_then(JsonValue::as_object)
.and_then(|network| network.get("default"))
.and_then(JsonValue::as_str)
== Some("allow")
{
workspace_write.insert("network_access".to_string(), TomlValue::Boolean(true));
}
if !workspace_write.is_empty() {
root.insert(
"sandbox_workspace_write".to_string(),
TomlValue::Table(workspace_write),
);
}
}
pub(super) fn repo_instruction_source_groups(
repo_root: &Path,
) -> io::Result<Vec<InstructionSourceGroup>> {
@@ -101,6 +191,107 @@ pub(super) fn import_source_subagents(
import_subagents_with_rewrite_profile(source_agents, target_agents, REWRITE_PROFILE)
}
pub(super) fn source_hook_event_names(
source_dir: &Path,
target_hooks: &Path,
) -> io::Result<Vec<String>> {
hook_migration_event_names_from_json_file(
source_dir,
&source_dir.join(HOOKS_CONFIG_FILE),
target_hooks,
REWRITE_PROFILE,
)
}
pub(super) fn import_source_hooks(source_dir: &Path, target_hooks: &Path) -> io::Result<bool> {
import_hooks_from_json_file(
source_dir,
&source_dir.join(HOOKS_CONFIG_FILE),
target_hooks,
REWRITE_PROFILE,
)
}
pub(super) fn cached_marketplace_plugins(
external_agent_home: &Path,
) -> io::Result<Vec<CachedMarketplacePlugins>> {
let marketplaces_root = external_agent_home.join("plugins/marketplaces");
let cache_root = external_agent_home.join("plugins/cache");
if !marketplaces_root.is_dir() || !cache_root.is_dir() {
return Ok(Vec::new());
}
let mut marketplaces = Vec::new();
for entry in fs::read_dir(marketplaces_root)? {
let entry = entry?;
if !entry.file_type()?.is_dir() {
continue;
}
let marketplace_root = entry.path();
let manifest_path = marketplace_root.join(".cursor-plugin/marketplace.json");
if !manifest_path.is_file() {
continue;
}
let manifest = match fs::read_to_string(&manifest_path) {
Ok(manifest) => manifest,
Err(err) => {
tracing::warn!(
path = %manifest_path.display(),
error = %err,
"ignoring unreadable external marketplace manifest"
);
continue;
}
};
let manifest: JsonValue = match serde_json::from_str(&manifest) {
Ok(manifest) => manifest,
Err(err) => {
tracing::warn!(
path = %manifest_path.display(),
error = %err,
"ignoring invalid external marketplace manifest"
);
continue;
}
};
let Some(name) = manifest.get("name").and_then(JsonValue::as_str) else {
continue;
};
let available_plugins = manifest
.get("plugins")
.and_then(JsonValue::as_array)
.into_iter()
.flatten()
.filter_map(|plugin| plugin.get("name").and_then(JsonValue::as_str))
.collect::<BTreeSet<_>>();
let cache_marketplace = cache_root.join(entry.file_name());
if !cache_marketplace.is_dir() {
continue;
}
let mut plugin_names = fs::read_dir(cache_marketplace)?
.filter_map(Result::ok)
.filter_map(|plugin| {
plugin
.file_type()
.ok()
.filter(std::fs::FileType::is_dir)
.and_then(|_| plugin.file_name().into_string().ok())
})
.filter(|plugin_name| available_plugins.contains(plugin_name.as_str()))
.collect::<Vec<_>>();
plugin_names.sort();
if !plugin_names.is_empty() {
marketplaces.push(CachedMarketplacePlugins {
name: name.to_string(),
source: marketplace_root,
plugin_names,
});
}
}
marketplaces.sort_by(|left, right| left.name.cmp(&right.name));
Ok(marketplaces)
}
fn instruction_sources(
legacy_rules: Option<PathBuf>,
rules_dir: &Path,
@@ -42,6 +42,9 @@ use super::analytics::wait_for_analytics_event;
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
#[path = "external_agent_config_source_cu.rs"]
mod source_cu_tests;
fn external_agent_home(codex_home: &Path) -> PathBuf {
codex_home.join(concat!(".", "cl", "aude"))
}
@@ -0,0 +1,225 @@
use super::*;
use pretty_assertions::assert_eq;
#[tokio::test]
async fn imports_cursor_config_plugins_hooks_sessions_and_capitalized_text() -> Result<()> {
let root = TempDir::new()?;
let home = root.path().join("home");
let codex_home = home.join(".codex");
let source_dir = home.join(".cursor");
let project_root = root.path().join("workspace-with-dashes");
let writable_root = root.path().join("shared-cache");
std::fs::create_dir_all(&codex_home)?;
std::fs::create_dir_all(&source_dir)?;
std::fs::create_dir_all(&project_root)?;
std::fs::create_dir_all(project_root.join(".git"))?;
std::fs::create_dir_all(&writable_root)?;
std::fs::write(
source_dir.join("cli-config.json"),
r#"{"permissions":{"allow":["Shell(git)"]}}"#,
)?;
std::fs::write(
source_dir.join("sandbox.json"),
serde_json::to_string(&serde_json::json!({
"type": "workspace_readwrite",
"additionalReadwritePaths": [writable_root],
"disableTmpWrite": true,
"networkPolicy": {"default": "allow"}
}))?,
)?;
std::fs::create_dir_all(source_dir.join("skills/release"))?;
std::fs::write(
source_dir.join("skills/release/SKILL.md"),
concat!(
"---\nname: release\ndescription: Release with Cursor\n---\n\n",
"Use Cursor to release. Keep the database cursor and CURSOR acronym unchanged.\n"
),
)?;
std::fs::create_dir_all(source_dir.join("hooks"))?;
std::fs::write(
source_dir.join("hooks/session-start.sh"),
"#!/bin/sh\nexit 0\n",
)?;
std::fs::write(
source_dir.join("hooks.json"),
r#"{
"version": 1,
"hooks": {
"sessionStart": [{
"command": "sh .cursor/hooks/session-start.sh",
"statusMessage": "Starting Cursor context"
}],
"preToolUse": [{
"command": "sh .cursor/hooks/session-start.sh",
"matcher": "Shell"
}],
"afterAgentResponse": [{"command": "echo unsupported"}]
}
}"#,
)?;
let marketplace_root = source_dir.join("plugins/marketplaces/team-tools");
let plugin_root = marketplace_root.join("release-helper");
std::fs::create_dir_all(marketplace_root.join(".cursor-plugin"))?;
std::fs::create_dir_all(plugin_root.join(".cursor-plugin"))?;
std::fs::create_dir_all(plugin_root.join("skills/plugin-release"))?;
std::fs::write(
marketplace_root.join(".cursor-plugin/marketplace.json"),
r#"{
"name": "team-tools",
"plugins": [{"name": "release-helper", "source": "release-helper"}]
}"#,
)?;
std::fs::write(
plugin_root.join(".cursor-plugin/plugin.json"),
r#"{
"name": "release-helper",
"version": "1.0.0",
"skills": "skills"
}"#,
)?;
std::fs::write(
plugin_root.join("skills/plugin-release/SKILL.md"),
"---\nname: plugin-release\ndescription: Release helper\n---\n",
)?;
std::fs::create_dir_all(source_dir.join("plugins/cache/team-tools/release-helper/revision"))?;
let session_id = "11111111-1111-1111-1111-111111111111";
let session_path = source_dir
.join("projects")
.join(encoded_cursor_project_path(&project_root))
.join("agent-transcripts")
.join(session_id)
.join(format!("{session_id}.jsonl"));
std::fs::create_dir_all(session_path.parent().expect("session parent"))?;
std::fs::write(
&session_path,
concat!(
"{\"role\":\"user\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"review the release\"}]}}\n",
"{\"role\":\"assistant\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"release looks good\"}]}}\n"
),
)?;
let home_dir = home.display().to_string();
let mut mcp = TestAppServer::builder()
.with_codex_home(&codex_home)
.with_env_overrides(&[("HOME", Some(home_dir.as_str()))])
.build()
.await?;
timeout(DEFAULT_TIMEOUT, mcp.initialize()).await??;
let request_id = mcp
.send_raw_request(
"externalAgentConfig/detect",
Some(serde_json::json!({
"includeHome": true,
"cwds": [project_root],
"source": "cursor"
})),
)
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let detected: ExternalAgentConfigDetectResponse = to_response(response)?;
let detected_types = detected
.items
.iter()
.map(|item| item.item_type)
.collect::<Vec<_>>();
for expected in [
ExternalAgentConfigMigrationItemType::Config,
ExternalAgentConfigMigrationItemType::Hooks,
ExternalAgentConfigMigrationItemType::Skills,
ExternalAgentConfigMigrationItemType::Plugins,
ExternalAgentConfigMigrationItemType::Sessions,
] {
assert!(detected_types.contains(&expected), "missing {expected:?}");
}
assert_eq!(
detected_types
.iter()
.filter(|item_type| **item_type == ExternalAgentConfigMigrationItemType::Plugins)
.count(),
1
);
let request_id = mcp
.send_raw_request(
"externalAgentConfig/import",
Some(serde_json::json!({
"migrationItems": detected.items,
"source": "cursor"
})),
)
.await?;
let response: JSONRPCResponse = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_response_message(RequestId::Integer(request_id)),
)
.await??;
let response: ExternalAgentConfigImportResponse = to_response(response)?;
let import_id = assert_import_response(response);
let notification = timeout(
DEFAULT_TIMEOUT,
mcp.read_stream_until_notification_message("externalAgentConfig/import/completed"),
)
.await??;
let completed: ExternalAgentConfigImportCompletedNotification =
serde_json::from_value(notification.params.expect("completed params"))?;
assert_eq!(completed.import_id, import_id);
assert!(
completed
.item_type_results
.iter()
.all(|result| result.failures.is_empty()),
"{:#?}",
completed.item_type_results
);
let session_result = completed
.item_type_results
.iter()
.find(|result| result.item_type == ExternalAgentConfigMigrationItemType::Sessions)
.expect("session result");
assert_eq!(session_result.successes.len(), 1);
let config = std::fs::read_to_string(codex_home.join("config.toml"))?;
assert!(config.contains("sandbox_mode = \"workspace-write\""));
assert!(config.contains("network_access = true"));
assert!(config.contains("exclude_slash_tmp = true"));
assert!(config.contains(writable_root.to_string_lossy().as_ref()));
assert!(config.contains(r#"[plugins."release-helper@team-tools"]"#));
let skill = std::fs::read_to_string(home.join(".agents/skills/release/SKILL.md"))?;
assert!(skill.contains("Release with Codex"));
assert!(skill.contains("Use Codex to release"));
assert!(skill.contains("database cursor"));
assert!(skill.contains("CURSOR acronym"));
let hooks = std::fs::read_to_string(codex_home.join("hooks.json"))?;
assert!(hooks.contains("SessionStart"));
assert!(hooks.contains("PreToolUse"));
assert!(hooks.contains("Shell"));
assert!(hooks.contains("Starting Codex context"));
assert!(!hooks.contains("afterAgentResponse"));
assert!(codex_home.join("hooks/session-start.sh").is_file());
Ok(())
}
#[cfg(not(windows))]
fn encoded_cursor_project_path(path: &Path) -> String {
path.to_string_lossy()
.trim_start_matches('/')
.replace('/', "-")
}
#[cfg(windows)]
fn encoded_cursor_project_path(path: &Path) -> String {
path.to_string_lossy().replace([':', '\\'], "-")
}