aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

View File

@@ -0,0 +1,43 @@
use crate::discover_external_memory_files;
use crate::memory_import::memory_versions;
use crate::memory_import::projects_needing_import;
use crate::memory_import::resources_root;
use crate::model::ExternalAgentConfigMigrationItem;
use crate::model::ExternalAgentConfigMigrationItemType;
use crate::model::MigrationDetails;
use akode_protocol::MemoryVersion;
use std::collections::BTreeSet;
use std::io;
use std::path::Path;
pub(super) fn detect(
codex_home: &Path,
external_agent_home: &Path,
selection: MemoryVersion,
) -> io::Result<Option<ExternalAgentConfigMigrationItem>> {
let memory_files = discover_external_memory_files(external_agent_home)?;
let mut memory = BTreeSet::new();
for version in memory_versions(codex_home, selection)? {
memory.extend(projects_needing_import(
&codex_home.join(version.directory_name()),
&memory_files,
)?);
}
if memory.is_empty() {
return Ok(None);
}
Ok(Some(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Memory,
description: format!(
"Import memory files from {} to {}",
external_agent_home.join("projects").display(),
resources_root(&codex_home.join(MemoryVersion::V2.directory_name())).display()
),
cwd: None,
details: Some(MigrationDetails {
memory: memory.into_iter().collect(),
..Default::default()
}),
}))
}

View File

@@ -0,0 +1,427 @@
mod memory;
pub(crate) mod plugins;
pub(crate) mod sessions;
use crate::config_values::is_empty_toml_table;
use crate::config_values::merge_missing_mcp_servers;
use crate::config_values::merge_missing_toml_values;
use crate::config_values::migrated_mcp_server_names;
use crate::count_missing_subagents;
use crate::migration_source::InstructionSourceGroup;
use crate::migration_source::PluginDetectionContext;
use crate::missing_subagent_names;
use crate::model::ExternalAgentConfigDetectOptions;
use crate::model::ExternalAgentConfigMigrationItem;
use crate::model::ExternalAgentConfigMigrationItemType;
use crate::model::MigrationDetails;
use crate::reporting::emit_migration_metric;
use crate::scope::MigrationScope;
use crate::service::ExternalAgentConfigService;
use crate::service::configured_marketplace_plugins;
use crate::service::missing_subdirectory_names;
use crate::service::named_migrations;
use crate::utils::display_source_paths;
use crate::utils::invalid_data_error;
use crate::utils::is_missing_or_empty_text_file;
use akode_config::types::PluginConfig;
use akode_core::config::ConfigBuilder;
use akode_core::plugins_manager_for_config;
use std::collections::HashMap;
use std::collections::HashSet;
use std::fs;
use std::io;
use std::sync::Arc;
use toml::Value as TomlValue;
const EXTERNAL_AGENT_CONFIG_DETECT_METRIC: &str = "codex.external_agent_config.detect";
impl ExternalAgentConfigService {
pub async fn detect(
&self,
params: ExternalAgentConfigDetectOptions,
) -> io::Result<Vec<ExternalAgentConfigMigrationItem>> {
let mut items = Vec::new();
if params.include_home {
self.detect_migrations(&MigrationScope::home(), &mut items)
.await?;
}
for cwd in params.cwds.as_deref().unwrap_or(&[]) {
let Some(scope) = MigrationScope::from_cwd(Some(cwd))? else {
continue;
};
if scope.is_home() {
continue;
}
self.detect_migrations(&scope, &mut items).await?;
}
if params.include_home
&& params.include_memory
&& self.source.supports_memory()
&& let Some(item) = memory::detect(
&self.codex_home,
&self.external_agent_home,
self.memory_version,
)?
{
items.push(item);
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Memory,
/*skills_count*/ None,
);
}
Ok(items)
}
async fn detect_migrations(
&self,
scope: &MigrationScope,
items: &mut Vec<ExternalAgentConfigMigrationItem>,
) -> io::Result<()> {
let repo_root = scope.repo_root();
let cwd = scope.cwd();
let source_settings = self.source_settings(scope);
let settings = self.effective_source_settings(scope)?;
let target_config = repo_root.map_or_else(
|| self.codex_home.join("config.toml"),
|repo_root| repo_root.join(".akode").join("config.toml"),
);
if let Some(settings) = settings.as_ref() {
let migrated = self.source.build_config(settings)?;
if !is_empty_toml_table(&migrated) {
let mut should_include = true;
if target_config.exists() {
let existing_raw = fs::read_to_string(&target_config)?;
let mut existing = if existing_raw.trim().is_empty() {
TomlValue::Table(Default::default())
} else {
toml::from_str::<TomlValue>(&existing_raw).map_err(|err| {
invalid_data_error(format!("invalid existing config.toml: {err}"))
})?
};
should_include = merge_missing_toml_values(&mut existing, &migrated)?;
}
if should_include {
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Config,
description: format!(
"Migrate {} into {}",
source_settings.display(),
target_config.display()
),
cwd: cwd.clone(),
details: None,
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Config,
/*skills_count*/ None,
);
}
}
}
let mcp_source_path = self
.source
.mcp_source_path(self.source_root(scope), self.source_config_dir(scope));
let migrated_mcp = self.build_mcp_config(scope, settings.clone())?;
let mut mcp_server_names = migrated_mcp_server_names(&migrated_mcp);
if !is_empty_toml_table(&migrated_mcp) {
if target_config.exists() {
let existing_raw = fs::read_to_string(&target_config)?;
let mut existing = if existing_raw.trim().is_empty() {
TomlValue::Table(Default::default())
} else {
toml::from_str::<TomlValue>(&existing_raw).map_err(|err| {
invalid_data_error(format!("invalid existing config.toml: {err}"))
})?
};
mcp_server_names = merge_missing_mcp_servers(&mut existing, &migrated_mcp)?;
}
if !mcp_server_names.is_empty() {
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::McpServerConfig,
description: format!(
"Migrate MCP servers from {} into {}",
mcp_source_path.display(),
target_config.display()
),
cwd: cwd.clone(),
details: Some(MigrationDetails {
mcp_servers: named_migrations(mcp_server_names),
..Default::default()
}),
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::McpServerConfig,
/*skills_count*/ None,
);
}
}
let source_external_agent_dir = self.source_config_dir(scope);
let target_hooks = repo_root.map_or_else(
|| self.codex_home.join("hooks.json"),
|repo_root| repo_root.join(".akode").join("hooks.json"),
);
let hook_event_names = self
.source
.hook_event_names(source_external_agent_dir.as_path(), &target_hooks)?;
if !hook_event_names.is_empty() && is_missing_or_empty_text_file(&target_hooks)? {
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Hooks,
description: format!(
"Migrate hooks from {} to {}",
source_external_agent_dir.display(),
target_hooks.display()
),
cwd: cwd.clone(),
details: Some(MigrationDetails {
hooks: named_migrations(hook_event_names),
..Default::default()
}),
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Hooks,
/*skills_count*/ None,
);
}
let source_skills = self
.source
.skills_dir_names(scope)
.iter()
.map(|directory| source_external_agent_dir.join(*directory))
.filter(|path| path.is_dir())
.collect::<Vec<_>>();
let target_skills = repo_root.map_or_else(
|| self.home_target_skills_dir(),
|repo_root| repo_root.join(".agents").join("skills"),
);
let mut skill_names = Vec::new();
for source_skills_dir in &source_skills {
skill_names.extend(missing_subdirectory_names(
source_skills_dir,
&target_skills,
)?);
}
skill_names.sort();
skill_names.dedup();
let skills_count = skill_names.len();
if skills_count > 0 {
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Skills,
description: format!(
"Migrate skills from {} to {}",
display_source_paths(&source_skills),
target_skills.display()
),
cwd: cwd.clone(),
details: Some(MigrationDetails {
skills: named_migrations(skill_names),
..Default::default()
}),
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Skills,
Some(skills_count),
);
}
let source_commands = source_external_agent_dir.join("commands");
let target_command_skills = repo_root.map_or_else(
|| self.home_target_skills_dir(),
|repo_root| repo_root.join(".agents").join("skills"),
);
let commands_count = self
.source
.count_missing_commands(&source_commands, &target_command_skills)?;
if commands_count > 0 {
let command_names = self
.source
.missing_command_names(&source_commands, &target_command_skills)?;
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Commands,
description: format!(
"Migrate commands from {} to {}",
source_commands.display(),
target_command_skills.display()
),
cwd: cwd.clone(),
details: Some(MigrationDetails {
commands: named_migrations(command_names),
..Default::default()
}),
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Commands,
Some(commands_count),
);
}
let source_subagents = source_external_agent_dir.join("agents");
let target_subagents = repo_root.map_or_else(
|| self.codex_home.join("agents"),
|repo_root| repo_root.join(".akode").join("agents"),
);
let subagents_count = count_missing_subagents(&source_subagents, &target_subagents)?;
if subagents_count > 0 {
let subagent_names = missing_subagent_names(&source_subagents, &target_subagents)?;
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Subagents,
description: format!(
"Migrate subagents from {} to {}",
source_subagents.display(),
target_subagents.display()
),
cwd: cwd.clone(),
details: Some(MigrationDetails {
subagents: named_migrations(subagent_names),
..Default::default()
}),
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Subagents,
Some(subagents_count),
);
}
let instruction_source_groups = if let Some(repo_root) = repo_root {
self.repo_agents_md_source_groups(repo_root)?
} else {
let sources = self.home_agents_md_sources()?;
(!sources.is_empty())
.then(|| InstructionSourceGroup {
scope: self.codex_home.clone(),
sources,
})
.into_iter()
.collect()
};
for group in instruction_source_groups {
let target_agents_md = group.scope.join("AGENTS.md");
if !is_missing_or_empty_text_file(&target_agents_md)? {
continue;
}
let item_cwd = repo_root.is_some().then(|| group.scope.clone());
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::AgentsMd,
description: format!(
"Migrate {} to {}",
display_source_paths(&group.sources),
target_agents_md.display()
),
cwd: item_cwd,
details: None,
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::AgentsMd,
/*skills_count*/ None,
);
}
// Plugin import persists user-global enabled state, so repository-controlled
// settings must never be treated as plugin installation authority.
if scope.is_home() && self.source.supports_plugin_migration(settings.as_ref()) {
match ConfigBuilder::default()
.codex_home(self.codex_home.clone())
.fallback_cwd(Some(self.codex_home.clone()))
.build()
.await
{
Ok(config) => {
let configured_plugin_ids = config
.config_layer_stack
.get_active_user_layer()
.and_then(|user_layer| user_layer.config.get("plugins"))
.and_then(|plugins| {
match plugins.clone().try_into::<HashMap<String, PluginConfig>>() {
Ok(plugins) => Some(plugins),
Err(err) => {
tracing::warn!("invalid plugins config: {err}");
None
}
}
})
.map(|plugins| plugins.into_keys().collect::<HashSet<_>>())
.unwrap_or_default();
let configured_marketplace_plugins = configured_marketplace_plugins(
&config,
&plugins_manager_for_config(&config, Arc::clone(&self.auth_manager)),
)?;
let source_root = repo_root.unwrap_or(self.external_agent_home.as_path());
if let Some(detected) =
self.source.plugin_migration(PluginDetectionContext {
external_agent_home: self.external_agent_home.as_path(),
source_settings: source_settings.as_path(),
source_root,
repo_root,
settings: settings.as_ref(),
configured_plugin_ids: &configured_plugin_ids,
configured_marketplace_plugins: &configured_marketplace_plugins,
})?
{
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Plugins,
/*skills_count*/ None,
);
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Plugins,
description: detected.description,
cwd: cwd.clone(),
details: Some(detected.details),
});
}
}
Err(err) => {
tracing::warn!(
error = %err,
settings_path = %source_settings.display(),
"skipping external agent plugin migration detection because config load failed"
);
}
}
}
if scope.is_home() {
let sessions = self.source.recent_sessions(
&self.external_agent_home,
&self.codex_home,
self.session_import_limits,
)?;
if !sessions.is_empty() {
items.push(ExternalAgentConfigMigrationItem {
item_type: ExternalAgentConfigMigrationItemType::Sessions,
description: format!(
"Migrate recent sessions from {}",
self.external_agent_home.join("projects").display()
),
cwd: None,
details: Some(MigrationDetails {
sessions,
..Default::default()
}),
});
emit_migration_metric(
EXTERNAL_AGENT_CONFIG_DETECT_METRIC,
ExternalAgentConfigMigrationItemType::Sessions,
/*skills_count*/ None,
);
}
}
Ok(())
}
}

View File

@@ -0,0 +1,76 @@
use crate::migration_source::DetectedSourcePlugins;
use crate::migration_source::PluginDetectionContext;
use crate::model::MigrationDetails;
use crate::model::PluginsMigration;
use crate::source_cla;
use crate::source_cur;
use serde_json::Value as JsonValue;
use std::io;
pub(crate) fn detect_cla_plugins(
context: &PluginDetectionContext<'_>,
) -> Option<DetectedSourcePlugins> {
let settings = context.settings?;
let import_sources = source_cla::marketplace_import_sources(
settings,
context.external_agent_home,
context.source_root,
);
let details = source_cla::extract_plugin_migration_details(
settings,
&import_sources,
context.configured_plugin_ids,
context.configured_marketplace_plugins,
)?;
Some(DetectedSourcePlugins {
description: format!(
"Migrate enabled plugins from {}",
context.source_settings.display()
),
details,
})
}
pub(crate) fn can_detect_cla_plugins(settings: Option<&JsonValue>) -> bool {
settings.is_some()
}
pub(crate) fn detect_cur_plugins(
context: &PluginDetectionContext<'_>,
) -> io::Result<Option<DetectedSourcePlugins>> {
let mut plugins = Vec::new();
for marketplace in source_cur::cached_marketplace_plugins(context.external_agent_home)? {
let configured_marketplace = context
.configured_marketplace_plugins
.get(&marketplace.name);
let plugin_names = marketplace
.plugin_names
.into_iter()
.filter(|plugin_name| {
!context
.configured_plugin_ids
.contains(&format!("{plugin_name}@{}", marketplace.name))
&& configured_marketplace.is_none_or(|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);
}
Ok(Some(DetectedSourcePlugins {
description: format!(
"Migrate cached plugins from {}",
context.external_agent_home.join("plugins/cache").display()
),
details: MigrationDetails {
plugins,
..Default::default()
},
}))
}

View File

@@ -0,0 +1,485 @@
use super::common::SessionFileCandidate;
use super::common::detect_recent_sessions;
use crate::model::ExternalAgentSessionImportLimits;
use crate::sessions::ExternalAgentSessionMigration;
use crate::sessions::SessionRecordFormat;
use std::fs;
use std::io;
use std::path::Path;
pub fn detect_recent_cla_sessions(
external_agent_home: &Path,
codex_home: &Path,
) -> io::Result<Vec<ExternalAgentSessionMigration>> {
detect_recent_cla_sessions_with_limits(
external_agent_home,
codex_home,
ExternalAgentSessionImportLimits::default(),
)
}
pub(crate) fn detect_recent_cla_sessions_with_limits(
external_agent_home: &Path,
codex_home: &Path,
limits: ExternalAgentSessionImportLimits,
) -> io::Result<Vec<ExternalAgentSessionMigration>> {
let projects_root = external_agent_home.join("projects");
if !projects_root.is_dir() {
return Ok(Vec::new());
}
let mut candidates = Vec::new();
for project_entry in fs::read_dir(projects_root)? {
let Ok(project_entry) = project_entry else {
continue;
};
let project_path = project_entry.path();
if !project_path.is_dir() {
continue;
}
let Ok(entries) = fs::read_dir(project_path) else {
continue;
};
for entry in entries {
let Ok(entry) = entry else {
continue;
};
let path = entry.path();
if path.extension().and_then(|value| value.to_str()) != Some("jsonl") {
continue;
}
candidates.push(SessionFileCandidate {
path,
fallback_cwd: None,
record_format: SessionRecordFormat::Cla,
});
}
}
detect_recent_sessions(
codex_home, candidates, /*require_existing_cwd*/ true, limits,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sessions::ledger::record_imported_session;
use akode_protocol::ThreadId;
use pretty_assertions::assert_eq;
use serde_json::Value as JsonValue;
use std::fs::FileTimes;
use std::fs::OpenOptions;
use std::path::Path;
use std::time::Duration;
use std::time::SystemTime;
use tempfile::TempDir;
#[test]
fn detects_recent_sessions_with_existing_roots() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[
record("user", "hello there", project_root.as_path()),
record("assistant", "ack", project_root.as_path()),
],
);
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: session_path,
cwd: project_root,
title: Some("hello there".to_string()),
}]
);
}
#[test]
fn detects_only_the_continuation_of_a_backgrounded_session() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let original = record("user", "plan a vacation", &project_root);
write_session(
&external_agent_home,
&project_root,
"original.jsonl",
&[
original.clone(),
serde_json::json!({
"type": "continued-in",
"sessionId": "original",
"continuedInSessionId": "background",
}),
],
);
let continuation = write_session(
&external_agent_home,
&project_root,
"background.jsonl",
&[
original,
record("assistant", "Here is your itinerary", &project_root),
],
);
assert_eq!(
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect"),
vec![ExternalAgentSessionMigration {
path: continuation,
cwd: project_root,
title: Some("plan a vacation".to_string()),
}]
);
}
#[test]
fn prefers_latest_custom_title_over_first_user_message() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[
record("user", "hello there", project_root.as_path()),
custom_title_record("first title"),
custom_title_record("final title"),
],
);
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: session_path,
cwd: project_root,
title: Some("final title".to_string()),
}]
);
}
#[test]
fn detects_ai_title_over_first_user_message() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[
record("user", "hello there", project_root.as_path()),
ai_title_record("generated by source app"),
],
);
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: session_path,
cwd: project_root,
title: Some("generated by source app".to_string()),
}]
);
}
#[test]
fn prefers_custom_title_over_later_ai_title() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[
record("user", "hello there", project_root.as_path()),
custom_title_record("custom title"),
ai_title_record("generated title"),
],
);
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: session_path,
cwd: project_root,
title: Some("custom title".to_string()),
}]
);
}
#[test]
fn uses_file_modification_time_for_recency() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[record_at(
"user",
"hello",
&project_root,
"2020-01-01T00:00:00Z",
)],
);
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: session_path,
cwd: project_root,
title: Some("hello".to_string()),
}]
);
}
#[test]
fn ignores_sessions_with_old_file_modification_time() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[record("user", "hello", &project_root)],
);
set_modified_at(
&session_path,
SystemTime::UNIX_EPOCH + Duration::from_secs(/*secs*/ 1),
);
assert!(
detect_recent_cla_sessions(&external_agent_home, root.path())
.expect("detect")
.is_empty()
);
}
#[test]
fn detects_sessions_in_batches() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
let modified_at = SystemTime::now();
let mut expected = Vec::new();
let default_limits = ExternalAgentSessionImportLimits::default();
for index in 0..=default_limits.max_sessions {
let file_name = format!("{index:02}-session.jsonl");
let title = format!("session {index}");
let path = write_session(
&external_agent_home,
&project_root,
&file_name,
&[record_at("user", &title, &project_root, &timestamp)],
);
set_modified_at(
&path,
modified_at - Duration::from_secs(/*secs*/ index as u64),
);
expected.push(ExternalAgentSessionMigration {
path,
cwd: project_root.clone(),
title: Some(title),
});
}
let oldest_session = expected.pop().expect("oldest session");
let mut all_sessions = expected.clone();
all_sessions.push(oldest_session.clone());
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(sessions, expected);
for session in sessions {
record_imported_session(root.path(), &session.path, ThreadId::new())
.expect("record import");
}
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(sessions, vec![oldest_session.clone()]);
for session in sessions {
record_imported_session(root.path(), &session.path, ThreadId::new())
.expect("record import");
}
let changed_at = SystemTime::now()
+ Duration::from_secs(/*secs*/ default_limits.max_sessions as u64 + 1);
for (index, session) in all_sessions.iter().enumerate() {
let title = session.title.as_deref().expect("session title");
std::fs::write(
&session.path,
jsonl(&[
record("user", title, &project_root),
record("assistant", "updated", &project_root),
]),
)
.expect("update session");
set_modified_at(
&session.path,
changed_at - Duration::from_secs(/*secs*/ index as u64),
);
}
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(sessions, expected);
for session in sessions {
record_imported_session(root.path(), &session.path, ThreadId::new())
.expect("record import");
}
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(sessions, vec![oldest_session]);
}
#[test]
fn skips_already_imported_current_session_versions() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[record("user", "hello there", project_root.as_path())],
);
record_imported_session(root.path(), &session_path, ThreadId::new())
.expect("record import");
assert!(
detect_recent_cla_sessions(&external_agent_home, root.path())
.expect("detect")
.is_empty()
);
}
#[test]
fn redetects_sessions_when_source_contents_change_after_import() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let project_root = root.path().join("repo");
let session_path = write_session(
&external_agent_home,
&project_root,
"session.jsonl",
&[record("user", "hello there", project_root.as_path())],
);
record_imported_session(root.path(), &session_path, ThreadId::new())
.expect("record import");
std::fs::write(
&session_path,
jsonl(&[
record("user", "hello there", project_root.as_path()),
record("assistant", "new reply", project_root.as_path()),
]),
)
.expect("update session");
set_modified_at(
&session_path,
SystemTime::now() + Duration::from_secs(/*secs*/ 1),
);
let sessions =
detect_recent_cla_sessions(&external_agent_home, root.path()).expect("detect");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: session_path,
cwd: project_root,
title: Some("hello there".to_string()),
}]
);
}
fn write_session(
external_agent_home: &Path,
project_root: &Path,
file_name: &str,
records: &[JsonValue],
) -> std::path::PathBuf {
let projects_dir = external_agent_home.join("projects").join("repo");
std::fs::create_dir_all(project_root).expect("project root");
std::fs::create_dir_all(&projects_dir).expect("projects dir");
let session_path = projects_dir.join(file_name);
std::fs::write(&session_path, jsonl(records)).expect("session");
session_path
}
fn set_modified_at(path: &Path, modified_at: SystemTime) {
OpenOptions::new()
.write(true)
.open(path)
.expect("open session")
.set_times(FileTimes::new().set_modified(modified_at))
.expect("set session modified time");
}
fn record(role: &str, text: &str, cwd: &Path) -> JsonValue {
let timestamp = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
record_at(role, text, cwd, &timestamp)
}
fn record_at(role: &str, text: &str, cwd: &Path, timestamp: &str) -> JsonValue {
serde_json::json!({
"type": role,
"cwd": cwd,
"timestamp": timestamp,
"message": { "content": text }
})
}
fn custom_title_record(title: &str) -> JsonValue {
serde_json::json!({
"type": "custom-title",
"customTitle": title,
})
}
fn ai_title_record(title: &str) -> JsonValue {
serde_json::json!({
"type": "ai-title",
"aiTitle": title,
})
}
fn jsonl(records: &[JsonValue]) -> String {
records
.iter()
.map(JsonValue::to_string)
.collect::<Vec<_>>()
.join("\n")
}
}

View File

@@ -0,0 +1,101 @@
use crate::model::ExternalAgentSessionImportLimits;
use crate::sessions::ExternalAgentSessionMigration;
use crate::sessions::SessionRecordFormat;
use crate::sessions::ledger::load_import_ledger;
use crate::sessions::ledger::save_import_ledger;
use crate::sessions::now_unix_seconds;
use crate::sessions::records_cla;
use crate::sessions::records_cur;
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
pub(super) struct SessionFileCandidate {
pub path: PathBuf,
pub fallback_cwd: Option<PathBuf>,
pub record_format: SessionRecordFormat,
}
pub(super) fn detect_recent_sessions(
codex_home: &Path,
candidates: impl IntoIterator<Item = SessionFileCandidate>,
require_existing_cwd: bool,
limits: ExternalAgentSessionImportLimits,
) -> io::Result<Vec<ExternalAgentSessionMigration>> {
let now = now_unix_seconds();
let mut ledger = load_import_ledger(codex_home)?;
let source_states = ledger.source_states();
let mut recent = BinaryHeap::new();
for candidate in candidates {
let Ok(metadata) = fs::metadata(&candidate.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(limits.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(&candidate.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;
}
recent.push((
Reverse(modified_at_nanos),
candidate.path,
candidate.fallback_cwd,
candidate.record_format,
));
if recent.len() > limits.max_sessions {
recent.pop();
}
}
drop(source_states);
let mut migrations = Vec::new();
let mut ledger_changed = false;
for (modified_at, path, fallback_cwd, record_format) in recent.into_sorted_vec() {
match ledger.refresh_current_source(&path, modified_at.0) {
Ok(false) => {}
Ok(true) => {
ledger_changed = true;
continue;
}
Err(_) => continue,
}
let summary = match record_format {
SessionRecordFormat::Cla => records_cla::summarize_session(&path),
SessionRecordFormat::Cur => {
records_cur::summarize_session(&path, fallback_cwd.as_deref())
}
};
let Ok(Some(summary)) = summary else {
continue;
};
if require_existing_cwd && !summary.migration.cwd.is_dir() {
continue;
}
migrations.push(summary.migration);
}
if ledger_changed {
save_import_ledger(codex_home, &ledger)?;
}
Ok(migrations)
}

View File

@@ -0,0 +1,234 @@
use serde::Deserialize;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fs;
use std::io::BufRead;
use std::path::Path;
use std::path::PathBuf;
use crate::model::DetectedConnectorCandidate;
use crate::model::DetectedConnectorSource;
use crate::sessions::ExternalAgentSessionMigration;
const SESSION_MANIFESTS_DIR: &str = "claude-code-sessions";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportedSessionConnectorAttribution {
pub session_id: String,
pub server_ids: BTreeSet<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct SessionManifest {
cli_session_id: Option<String>,
#[serde(default)]
remote_mcp_servers_config: Vec<RemoteMcpServerConfig>,
}
#[derive(Deserialize)]
struct RemoteMcpServerConfig {
name: Option<String>,
uuid: Option<String>,
}
pub(crate) fn detect_cla_session_connectors(
sessions: &[ExternalAgentSessionMigration],
connector_metadata_roots: &[PathBuf],
) -> Vec<DetectedConnectorCandidate> {
super::aggregate_session_connector_candidates(detect_cla_session_connectors_by_source_path(
sessions,
connector_metadata_roots,
))
}
pub(crate) fn detect_cla_session_connectors_by_source_path(
sessions: &[ExternalAgentSessionMigration],
connector_metadata_roots: &[PathBuf],
) -> BTreeMap<PathBuf, Vec<DetectedConnectorCandidate>> {
let session_attributions_by_source_path = sessions
.iter()
.filter_map(|session| {
let source_path = fs::canonicalize(&session.path).ok()?;
let attribution = session_connector_attribution(session)?;
Some((source_path, attribution))
})
.collect::<BTreeMap<_, _>>();
let connector_names_by_source_path = detect_imported_cla_session_connectors_by_source_path(
&session_attributions_by_source_path,
connector_metadata_roots,
);
connector_names_by_source_path
.into_iter()
.filter_map(|(source_path, names)| {
let candidates = names
.into_iter()
.map(|name| DetectedConnectorCandidate {
name,
session_count: 1,
source: DetectedConnectorSource::RemoteMcpServersConfig,
})
.collect::<Vec<_>>();
(!candidates.is_empty()).then_some((source_path, candidates))
})
.collect()
}
pub fn detect_imported_cla_session_connectors_by_source_path(
session_attributions_by_source_path: &BTreeMap<PathBuf, ImportedSessionConnectorAttribution>,
connector_metadata_roots: &[PathBuf],
) -> BTreeMap<PathBuf, Vec<String>> {
detect_connector_names_by_key(
session_attributions_by_source_path
.iter()
.map(|(source_path, attribution)| (source_path.clone(), attribution)),
connector_metadata_roots,
)
}
pub fn detect_imported_cla_session_connectors(
session_attributions: &[ImportedSessionConnectorAttribution],
connector_metadata_roots: &[PathBuf],
) -> BTreeMap<String, Vec<String>> {
detect_connector_names_by_key(
session_attributions
.iter()
.map(|attribution| (attribution.session_id.clone(), attribution)),
connector_metadata_roots,
)
}
fn detect_connector_names_by_key<'a, Key>(
keyed_attributions: impl IntoIterator<Item = (Key, &'a ImportedSessionConnectorAttribution)>,
connector_metadata_roots: &[PathBuf],
) -> BTreeMap<Key, Vec<String>>
where
Key: Clone + Ord,
{
// Session IDs come from file stems and can repeat across projects, so
// preserve the caller's key while matching shared manifest metadata.
let mut attributions_by_session_id = BTreeMap::<String, Vec<(Key, BTreeSet<String>)>>::new();
for (key, attribution) in keyed_attributions {
attributions_by_session_id
.entry(attribution.session_id.clone())
.or_default()
.push((key, attribution.server_ids.clone()));
}
if attributions_by_session_id.is_empty() {
return BTreeMap::new();
}
let mut connector_names_by_key = BTreeMap::<Key, BTreeMap<String, String>>::new();
for metadata_root in connector_metadata_roots {
let manifests_root = metadata_root.join(SESSION_MANIFESTS_DIR);
for manifest_path in json_files_recursively(&manifests_root) {
let Some(manifest) = read_session_manifest(&manifest_path) else {
continue;
};
let Some(session_id) = manifest.cli_session_id else {
continue;
};
let Some(keyed_attributions) = attributions_by_session_id.get(&session_id) else {
continue;
};
for server in &manifest.remote_mcp_servers_config {
let Some(name) =
crate::sessions::normalized_connector_display_name(server.name.as_deref())
else {
continue;
};
for (key, attributed_server_ids) in keyed_attributions {
if attributed_server_ids.is_empty() {
continue;
}
// Depending on the source client, attributionMcpServer contains either the
// manifest UUID or its configured server name.
let matches_uuid = server
.uuid
.as_deref()
.is_some_and(|uuid| attributed_server_ids.contains(uuid));
let matches_name = attributed_server_ids
.iter()
.any(|server_id| server_id.eq_ignore_ascii_case(&name));
if !matches_uuid && !matches_name {
continue;
}
connector_names_by_key
.entry(key.clone())
.or_default()
.entry(name.to_lowercase())
.or_insert_with(|| name.clone());
}
}
}
}
connector_names_by_key
.into_iter()
.map(|(key, names)| (key, names.into_values().collect()))
.collect()
}
fn session_connector_attribution(
session: &ExternalAgentSessionMigration,
) -> Option<ImportedSessionConnectorAttribution> {
let session_id = session
.path
.file_stem()
.and_then(|stem| stem.to_str())
.map(str::trim)
.filter(|session_id| !session_id.is_empty())?
.to_string();
let file = fs::File::open(&session.path).ok()?;
let server_ids = std::io::BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| serde_json::from_str::<JsonValue>(line.trim()).ok())
.filter_map(|record| {
record
.get("attributionMcpServer")
.and_then(JsonValue::as_str)
.map(str::trim)
.filter(|server_id| !server_id.is_empty())
.map(ToOwned::to_owned)
})
.collect::<BTreeSet<_>>();
(!server_ids.is_empty()).then_some(ImportedSessionConnectorAttribution {
session_id,
server_ids,
})
}
fn read_session_manifest(path: &Path) -> Option<SessionManifest> {
let contents = fs::read_to_string(path).ok()?;
serde_json::from_str(&contents).ok()
}
fn json_files_recursively(root: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
let mut pending = vec![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 Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
pending.push(entry.path());
} else if file_type.is_file()
&& entry.path().extension().and_then(|value| value.to_str()) == Some("json")
{
files.push(entry.path());
}
}
}
files
}
#[cfg(test)]
#[path = "connectors_cla_tests.rs"]
mod tests;

View File

@@ -0,0 +1,186 @@
use super::*;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use tempfile::TempDir;
#[test]
fn resolves_attributed_server_name_from_session_manifest() {
let metadata_root = TempDir::new().expect("tempdir");
let manifests_root = metadata_root.path().join(SESSION_MANIFESTS_DIR);
std::fs::create_dir_all(&manifests_root).expect("manifest directory");
std::fs::write(
manifests_root.join("session.json"),
serde_json::json!({
"cliSessionId": "session-1",
"remoteMcpServersConfig": [
{
"uuid": "c58ac595-58b5-48f8-ac77-d8d01523dede",
"name": "Figma",
},
],
})
.to_string(),
)
.expect("manifest");
let session_path = metadata_root.path().join("session-1.jsonl");
std::fs::write(
&session_path,
serde_json::json!({"attributionMcpServer": "figma"}).to_string(),
)
.expect("session");
let sessions = vec![ExternalAgentSessionMigration {
path: session_path,
cwd: metadata_root.path().to_path_buf(),
title: None,
}];
let connectors =
detect_cla_session_connectors(&sessions, &[metadata_root.path().to_path_buf()]);
assert_eq!(
connectors,
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::RemoteMcpServersConfig,
}]
);
}
#[test]
fn still_resolves_attributed_server_uuid_from_session_manifest() {
let metadata_root = TempDir::new().expect("tempdir");
let manifests_root = metadata_root.path().join(SESSION_MANIFESTS_DIR);
std::fs::create_dir_all(&manifests_root).expect("manifest directory");
std::fs::write(
manifests_root.join("session.json"),
serde_json::json!({
"cliSessionId": "session-1",
"remoteMcpServersConfig": [
{
"uuid": "c58ac595-58b5-48f8-ac77-d8d01523dede",
"name": "Figma",
},
],
})
.to_string(),
)
.expect("manifest");
let session_path = metadata_root.path().join("session-1.jsonl");
std::fs::write(
&session_path,
serde_json::json!({
"attributionMcpServer": "c58ac595-58b5-48f8-ac77-d8d01523dede"
})
.to_string(),
)
.expect("session");
let sessions = vec![ExternalAgentSessionMigration {
path: session_path,
cwd: metadata_root.path().to_path_buf(),
title: None,
}];
let connectors =
detect_cla_session_connectors(&sessions, &[metadata_root.path().to_path_buf()]);
assert_eq!(
connectors,
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::RemoteMcpServersConfig,
}]
);
}
#[test]
fn keeps_duplicate_session_stems_separate_when_batched() {
let metadata_root = TempDir::new().expect("tempdir");
let manifests_root = metadata_root.path().join(SESSION_MANIFESTS_DIR);
std::fs::create_dir_all(&manifests_root).expect("manifest directory");
std::fs::write(
manifests_root.join("figma-session.json"),
serde_json::json!({
"cliSessionId": "session",
"remoteMcpServersConfig": [
{
"uuid": "figma-server",
"name": "Figma",
},
],
})
.to_string(),
)
.expect("figma manifest");
std::fs::write(
manifests_root.join("slack-session.json"),
serde_json::json!({
"cliSessionId": "session",
"remoteMcpServersConfig": [
{
"uuid": "slack-server",
"name": "Slack",
},
],
})
.to_string(),
)
.expect("slack manifest");
let first_project = metadata_root.path().join("project-a");
let second_project = metadata_root.path().join("project-b");
std::fs::create_dir_all(&first_project).expect("first project");
std::fs::create_dir_all(&second_project).expect("second project");
let first_session = first_project.join("session.jsonl");
let second_session = second_project.join("session.jsonl");
std::fs::write(
&first_session,
serde_json::json!({"attributionMcpServer": "figma-server"}).to_string(),
)
.expect("first session");
std::fs::write(
&second_session,
serde_json::json!({"attributionMcpServer": "slack-server"}).to_string(),
)
.expect("second session");
let first_source_path = std::fs::canonicalize(&first_session).expect("first source path");
let second_source_path = std::fs::canonicalize(&second_session).expect("second source path");
let sessions = [
ExternalAgentSessionMigration {
path: first_session,
cwd: first_project,
title: None,
},
ExternalAgentSessionMigration {
path: second_session,
cwd: second_project,
title: None,
},
];
assert_eq!(
detect_cla_session_connectors_by_source_path(
&sessions,
&[metadata_root.path().to_path_buf()]
),
BTreeMap::from([
(
first_source_path,
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::RemoteMcpServersConfig,
}],
),
(
second_source_path,
vec![DetectedConnectorCandidate {
name: "Slack".to_string(),
session_count: 1,
source: DetectedConnectorSource::RemoteMcpServersConfig,
}],
),
])
);
}

View File

@@ -0,0 +1,304 @@
use serde::Deserialize;
use serde_json::Value as JsonValue;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fs;
use std::io::BufRead;
use std::path::Component;
use std::path::Path;
use std::path::PathBuf;
use crate::model::DetectedConnectorCandidate;
use crate::model::DetectedConnectorSource;
use crate::sessions::ExternalAgentSessionMigration;
const PLUGIN_CACHE_DIR: &str = "plugins/cache";
const PLUGIN_MANIFEST_PATH: &str = ".cursor-plugin/plugin.json";
const MCP_CONFIG_PATH: &str = ".mcp.json";
const PROJECT_MCP_DIR: &str = "mcps";
const PROJECT_MCP_SERVER_METADATA_PATH: &str = "SERVER_METADATA.json";
const AGENT_TRANSCRIPTS_DIR: &str = "agent-transcripts";
const MCP_TOOL_CALL: &str = "CallMcpTool";
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct PluginManifest {
name: String,
display_name: Option<String>,
mcp_servers: Option<JsonValue>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProjectMcpServerMetadata {
server_identifier: String,
server_name: String,
}
#[derive(Default)]
struct ProjectConnectorMetadata {
names_by_server_id: BTreeMap<String, String>,
names_by_normalized_name: BTreeMap<String, String>,
}
pub(crate) fn detect_cur_session_connectors(
sessions: &[ExternalAgentSessionMigration],
external_agent_home: &Path,
) -> Vec<DetectedConnectorCandidate> {
super::aggregate_session_connector_candidates(detect_cur_session_connectors_by_source_path(
sessions,
external_agent_home,
))
}
pub(crate) fn detect_cur_session_connectors_by_source_path(
sessions: &[ExternalAgentSessionMigration],
external_agent_home: &Path,
) -> BTreeMap<PathBuf, Vec<DetectedConnectorCandidate>> {
let cached_connector_names_by_server_id =
cached_connector_names_by_server_id(external_agent_home);
let mut candidates_by_source_path = BTreeMap::new();
for session in sessions {
let Ok(source_path) = fs::canonicalize(&session.path) else {
continue;
};
let project_connector_metadata = project_connector_metadata(session);
let candidates = session_connector_names(
session,
&cached_connector_names_by_server_id,
&project_connector_metadata,
)
.into_values()
.map(|name| DetectedConnectorCandidate {
name,
session_count: 1,
source: DetectedConnectorSource::SessionToolUse,
})
.collect::<Vec<_>>();
if !candidates.is_empty() {
candidates_by_source_path.insert(source_path, candidates);
}
}
candidates_by_source_path
}
fn project_connector_metadata(session: &ExternalAgentSessionMigration) -> ProjectConnectorMetadata {
let Some(project_root) = session
.path
.ancestors()
.find(|path| path.file_name().and_then(|name| name.to_str()) == Some(AGENT_TRANSCRIPTS_DIR))
.and_then(Path::parent)
else {
return ProjectConnectorMetadata::default();
};
let mut connector_metadata = ProjectConnectorMetadata::default();
for server_root in child_directories(&project_root.join(PROJECT_MCP_DIR)) {
let Some(metadata) = read_project_mcp_server_metadata(&server_root) else {
continue;
};
let Some(display_name) =
crate::sessions::normalized_connector_display_name(Some(&metadata.server_name))
else {
continue;
};
let server_identifier = metadata.server_identifier.trim();
if server_identifier.is_empty() {
continue;
}
connector_metadata
.names_by_server_id
.insert(server_identifier.to_lowercase(), display_name.clone());
// Cursor has emitted both the configured identifier and display name in
// mcpDetails.serverName. Match either only after finding it in project
// metadata; never infer a connector from the tool namespace alone.
connector_metadata
.names_by_normalized_name
.insert(server_identifier.to_lowercase(), display_name.clone());
connector_metadata
.names_by_normalized_name
.insert(display_name.to_lowercase(), display_name);
}
connector_metadata
}
fn session_connector_names(
session: &ExternalAgentSessionMigration,
cached_connector_names_by_server_id: &BTreeMap<String, String>,
project_connector_metadata: &ProjectConnectorMetadata,
) -> BTreeMap<String, String> {
let Ok(file) = fs::File::open(&session.path) else {
return BTreeMap::new();
};
std::io::BufReader::new(file)
.lines()
.map_while(Result::ok)
.filter_map(|line| serde_json::from_str::<JsonValue>(line.trim()).ok())
.flat_map(|record| {
let mut connector_names = Vec::new();
let Some(contents) = record
.get("message")
.and_then(|message| message.get("content"))
.and_then(JsonValue::as_array)
else {
return connector_names;
};
for content in contents {
if content.get("type").and_then(JsonValue::as_str) != Some("tool_use") {
continue;
}
let Some(tool_name) = content.get("name").and_then(JsonValue::as_str) else {
continue;
};
let Some(input) = content.get("input") else {
continue;
};
let connector_name = if tool_name == MCP_TOOL_CALL {
input
.get("server")
.and_then(JsonValue::as_str)
.map(str::trim)
.filter(|server_id| !server_id.is_empty())
.map(str::to_lowercase)
.and_then(|server_id| {
project_connector_metadata
.names_by_server_id
.get(&server_id)
.or_else(|| cached_connector_names_by_server_id.get(&server_id))
})
.cloned()
} else if tool_name.starts_with("mcp__") {
input
.get("mcpDetails")
.and_then(|details| details.get("serverName"))
.and_then(JsonValue::as_str)
.and_then(|server_name| {
crate::sessions::normalized_connector_display_name(Some(server_name))
})
.map(|server_name| server_name.to_lowercase())
.and_then(|server_name| {
project_connector_metadata
.names_by_normalized_name
.get(&server_name)
})
.cloned()
} else {
None
};
if let Some(connector_name) = connector_name {
connector_names.push(connector_name);
}
}
connector_names
})
.map(|name| (name.to_lowercase(), name))
.collect()
}
fn cached_connector_names_by_server_id(external_agent_home: &Path) -> BTreeMap<String, String> {
let cache_root = external_agent_home.join(PLUGIN_CACHE_DIR);
let mut connector_names = BTreeMap::new();
for marketplace_root in child_directories(&cache_root) {
for plugin_root in child_directories(&marketplace_root) {
for version_root in child_directories(&plugin_root) {
let Some(manifest) = read_plugin_manifest(&version_root) else {
continue;
};
let Some(display_name) = crate::sessions::normalized_connector_display_name(
manifest.display_name.as_deref().or(Some(&manifest.name)),
) else {
continue;
};
for server_name in cached_mcp_server_names(&version_root, &manifest) {
connector_names.insert(
format!("plugin-{}-{server_name}", manifest.name).to_lowercase(),
display_name.clone(),
);
}
}
}
}
connector_names
}
fn child_directories(root: &Path) -> Vec<std::path::PathBuf> {
let Ok(entries) = fs::read_dir(root) else {
return Vec::new();
};
entries
.flatten()
.filter_map(|entry| {
entry
.file_type()
.ok()
.filter(std::fs::FileType::is_dir)
.map(|_| entry.path())
})
.collect()
}
fn read_plugin_manifest(version_root: &Path) -> Option<PluginManifest> {
let contents = fs::read_to_string(version_root.join(PLUGIN_MANIFEST_PATH)).ok()?;
serde_json::from_str(&contents).ok()
}
fn read_project_mcp_server_metadata(server_root: &Path) -> Option<ProjectMcpServerMetadata> {
let contents = fs::read_to_string(server_root.join(PROJECT_MCP_SERVER_METADATA_PATH)).ok()?;
serde_json::from_str(&contents).ok()
}
fn cached_mcp_server_names(version_root: &Path, manifest: &PluginManifest) -> Vec<String> {
manifest
.mcp_servers
.as_ref()
.map_or_else(
|| mcp_server_names_from_file(version_root, MCP_CONFIG_PATH),
|declaration| manifest_mcp_server_names(version_root, declaration),
)
.into_iter()
.collect()
}
fn manifest_mcp_server_names(version_root: &Path, declaration: &JsonValue) -> BTreeSet<String> {
match declaration {
JsonValue::String(path) => mcp_server_names_from_file(version_root, path),
JsonValue::Object(_) => mcp_server_names_from_config(declaration),
JsonValue::Array(declarations) => declarations
.iter()
.flat_map(|declaration| manifest_mcp_server_names(version_root, declaration))
.collect(),
_ => BTreeSet::new(),
}
}
fn mcp_server_names_from_file(version_root: &Path, relative_path: &str) -> BTreeSet<String> {
let relative_path = Path::new(relative_path);
if relative_path.as_os_str().is_empty()
|| relative_path
.components()
.any(|component| !matches!(component, Component::CurDir | Component::Normal(_)))
{
return BTreeSet::new();
}
let Ok(contents) = fs::read_to_string(version_root.join(relative_path)) else {
return BTreeSet::new();
};
let Ok(config) = serde_json::from_str::<JsonValue>(&contents) else {
return BTreeSet::new();
};
mcp_server_names_from_config(&config)
}
fn mcp_server_names_from_config(config: &JsonValue) -> BTreeSet<String> {
config
.get("mcpServers")
.and_then(JsonValue::as_object)
.or_else(|| config.as_object())
.into_iter()
.flat_map(|servers| servers.keys())
.cloned()
.collect()
}
#[cfg(test)]
#[path = "connectors_cur_tests.rs"]
mod tests;

View File

@@ -0,0 +1,298 @@
use super::*;
use pretty_assertions::assert_eq;
use std::collections::BTreeMap;
use tempfile::TempDir;
#[test]
fn detects_connector_used_by_session_mcp_tool_call() {
let source_home = TempDir::new().expect("source home");
write_cached_plugin(source_home.path(), "figma", "Figma", "figma");
let first_session = write_session(
source_home.path(),
"session-1",
&[
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "GetMcpTools",
"input": {"server": "plugin-figma-figma"}
}]
}
}),
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "CallMcpTool",
"input": {"server": "plugin-figma-figma", "toolName": "whoami"}
}]
}
}),
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "CallMcpTool",
"input": {"server": "plugin-figma-figma", "toolName": "get_metadata"}
}]
}
}),
],
);
let second_session = write_session(
source_home.path(),
"session-2",
&[serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "CallMcpTool",
"input": {"server": "plugin-figma-figma", "toolName": "get_screenshot"}
}]
}
})],
);
let first_source_path = fs::canonicalize(&first_session).expect("first canonical source");
let second_source_path = fs::canonicalize(&second_session).expect("second canonical source");
let sessions = [
ExternalAgentSessionMigration {
path: first_session,
cwd: source_home.path().to_path_buf(),
title: None,
},
ExternalAgentSessionMigration {
path: second_session,
cwd: source_home.path().to_path_buf(),
title: None,
},
];
assert_eq!(
detect_cur_session_connectors_by_source_path(&sessions, source_home.path()),
BTreeMap::from([
(
first_source_path,
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::SessionToolUse,
}],
),
(
second_source_path,
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::SessionToolUse,
}],
),
])
);
let connectors = detect_cur_session_connectors(&sessions, source_home.path());
assert_eq!(
connectors,
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 2,
source: DetectedConnectorSource::SessionToolUse,
}]
);
}
#[test]
fn detects_call_mcp_tool_connector_from_project_mcp_server_metadata() {
let source_home = TempDir::new().expect("source home");
let project_root = source_home.path().join("projects/project");
let session_path = project_root
.join(AGENT_TRANSCRIPTS_DIR)
.join("session-1")
.join("session-1.jsonl");
fs::create_dir_all(session_path.parent().expect("session parent")).expect("session directory");
fs::write(
&session_path,
[
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "GetMcpTools",
"input": {"server": "user-figma"}
}]
}
}),
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "CallMcpTool",
"input": {"server": "user-figma", "toolName": "whoami"}
}]
}
}),
]
.into_iter()
.map(|record| record.to_string())
.collect::<Vec<_>>()
.join("\n"),
)
.expect("session");
let server_root = project_root.join(PROJECT_MCP_DIR).join("user-figma");
fs::create_dir_all(&server_root).expect("server directory");
fs::write(
server_root.join(PROJECT_MCP_SERVER_METADATA_PATH),
serde_json::json!({
"serverIdentifier": "user-figma",
"serverName": "Figma",
})
.to_string(),
)
.expect("server metadata");
assert_eq!(
detect_cur_session_connectors(
&[ExternalAgentSessionMigration {
path: session_path,
cwd: source_home.path().to_path_buf(),
title: None,
}],
source_home.path(),
),
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::SessionToolUse,
}]
);
}
#[test]
fn detects_project_backed_mcp_details_connector_from_metadata_name() {
let source_home = TempDir::new().expect("source home");
let project_root = source_home.path().join("projects/project");
let session_path = project_root
.join(AGENT_TRANSCRIPTS_DIR)
.join("session-1")
.join("session-1.jsonl");
fs::create_dir_all(session_path.parent().expect("session parent")).expect("session directory");
fs::write(
&session_path,
[
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "mcp__figma__get_design_context",
"input": {
"namespace": "figma",
"toolName": "get_design_context",
"mcpDetails": {"serverName": "Figma"},
"arguments": {"nodeId": "fixture-node"}
}
}]
}
}),
serde_json::json!({
"role": "assistant",
"message": {
"content": [{
"type": "tool_use",
"name": "mcp__untrusted__whoami",
"input": {"mcpDetails": {"serverName": "Not In Metadata"}}
}]
}
}),
]
.into_iter()
.map(|record| record.to_string())
.collect::<Vec<_>>()
.join("\n"),
)
.expect("session");
let server_root = project_root
.join(PROJECT_MCP_DIR)
.join("plugin-figma-figma");
fs::create_dir_all(&server_root).expect("server directory");
fs::write(
server_root.join(PROJECT_MCP_SERVER_METADATA_PATH),
serde_json::json!({
"serverIdentifier": "plugin-figma-figma",
"serverName": "Figma",
})
.to_string(),
)
.expect("server metadata");
assert_eq!(
detect_cur_session_connectors(
&[ExternalAgentSessionMigration {
path: session_path,
cwd: source_home.path().to_path_buf(),
title: None,
}],
source_home.path(),
),
vec![DetectedConnectorCandidate {
name: "Figma".to_string(),
session_count: 1,
source: DetectedConnectorSource::SessionToolUse,
}]
);
}
fn write_cached_plugin(
source_home: &Path,
plugin_name: &str,
display_name: &str,
server_name: &str,
) {
let version_root = source_home
.join(PLUGIN_CACHE_DIR)
.join("marketplace")
.join(plugin_name)
.join("version");
fs::create_dir_all(version_root.join(".cursor-plugin")).expect("plugin directory");
fs::write(
version_root.join(PLUGIN_MANIFEST_PATH),
serde_json::json!({
"name": plugin_name,
"displayName": display_name,
})
.to_string(),
)
.expect("plugin manifest");
fs::write(
version_root.join(MCP_CONFIG_PATH),
serde_json::json!({
"mcpServers": {
(server_name): {"type": "http", "url": "https://example.invalid/mcp"}
}
})
.to_string(),
)
.expect("mcp config");
}
fn write_session(source_home: &Path, name: &str, records: &[JsonValue]) -> std::path::PathBuf {
let path = source_home.join(format!("{name}.jsonl"));
fs::write(
&path,
records
.iter()
.map(JsonValue::to_string)
.collect::<Vec<_>>()
.join("\n"),
)
.expect("session");
path
}

View File

@@ -0,0 +1,224 @@
use super::common::SessionFileCandidate;
use super::common::detect_recent_sessions;
use crate::model::ExternalAgentSessionImportLimits;
use crate::sessions::ExternalAgentSessionMigration;
use crate::sessions::SessionRecordFormat;
use std::fs;
use std::io;
use std::path::Path;
use std::path::PathBuf;
const MAX_CUR_PROJECT_PATH_PROBES: usize = 128;
const CUR_PROJECT_SEPARATORS: [&str; 11] =
["-", "_", ".", " ", "--", "..", "__", " ", "+", "@", "&"];
pub fn detect_recent_cur_sessions(
external_agent_home: &Path,
codex_home: &Path,
) -> io::Result<Vec<ExternalAgentSessionMigration>> {
detect_recent_cur_sessions_with_limits(
external_agent_home,
codex_home,
ExternalAgentSessionImportLimits::default(),
)
}
pub(crate) fn detect_recent_cur_sessions_with_limits(
external_agent_home: &Path,
codex_home: &Path,
limits: ExternalAgentSessionImportLimits,
) -> io::Result<Vec<ExternalAgentSessionMigration>> {
let projects_root = external_agent_home.join("projects");
if !projects_root.is_dir() {
return Ok(Vec::new());
}
let mut candidates = Vec::new();
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 fallback_cwd = cur_project_cwd(&project_storage, external_agent_home);
for path in cur_transcript_files(&project_storage.join("agent-transcripts")) {
candidates.push(SessionFileCandidate {
path,
fallback_cwd: fallback_cwd.clone(),
record_format: SessionRecordFormat::Cur,
});
}
}
detect_recent_sessions(
codex_home, candidates, /*require_existing_cwd*/ false, limits,
)
}
fn cur_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 cur_project_cwd(project_storage: &Path, external_agent_home: &Path) -> Option<PathBuf> {
let encoded = project_storage.file_name()?.to_str()?;
// Cursor stores projectless chats under this reserved project name.
if encoded == "empty-window" {
let external_agent_home = if external_agent_home.is_absolute() {
external_agent_home.to_path_buf()
} else {
std::env::current_dir().ok()?.join(external_agent_home)
};
return external_agent_home.parent().map(Path::to_path_buf);
}
decode_cur_project_path(encoded)
}
fn decode_cur_project_path(encoded: &str) -> Option<PathBuf> {
#[cfg(not(windows))]
let mut path = PathBuf::from("/");
#[cfg(windows)]
let (encoded, mut path) = {
let (drive, encoded) = decode_cur_windows_project_drive(encoded)?;
(encoded, PathBuf::from(format!("{drive}:\\")))
};
let encoded = encoded.strip_prefix('-').unwrap_or(encoded);
for component in encoded.split('-') {
if component.is_empty()
|| matches!(component, "." | "..")
|| component.contains(['/', '\\', ':'])
{
return None;
}
path.push(component);
}
let mut matched_path = None;
let mut probes = 0;
let mut inspect = |candidate: PathBuf| {
if probes >= MAX_CUR_PROJECT_PATH_PROBES {
return None;
}
probes += 1;
if candidate.is_dir() {
if matched_path
.as_ref()
.is_some_and(|matched_path| matched_path != &candidate)
{
return None;
}
matched_path = Some(candidate);
}
Some(())
};
inspect(path.clone())?;
for suffix_length in 2..=4 {
let mut parent = path.as_path();
let mut suffix = Vec::with_capacity(suffix_length);
for _ in 0..suffix_length {
let Some(component) = parent.file_name().and_then(|name| name.to_str()) else {
break;
};
suffix.push(component);
let Some(ancestor) = parent.parent() else {
break;
};
parent = ancestor;
}
if suffix.len() != suffix_length {
break;
}
suffix.reverse();
for separator in CUR_PROJECT_SEPARATORS {
inspect(parent.join(suffix.join(separator)))?;
}
}
let mut ancestor = path.parent();
while let Some(right) = ancestor {
let Some(right_name) = right.file_name().and_then(|name| name.to_str()) else {
break;
};
let Some(left) = right.parent() else {
break;
};
let Some(left_name) = left.file_name().and_then(|name| name.to_str()) else {
break;
};
let Some(prefix) = left.parent() else {
break;
};
let Ok(trailing) = path.strip_prefix(right) else {
return None;
};
for separator in CUR_PROJECT_SEPARATORS {
let merged_prefix = prefix.join(format!("{left_name}{separator}{right_name}"));
if probes >= MAX_CUR_PROJECT_PATH_PROBES {
return None;
}
probes += 1;
if !merged_prefix.is_dir() {
continue;
}
if probes >= MAX_CUR_PROJECT_PATH_PROBES {
return None;
}
probes += 1;
let candidate = merged_prefix.join(trailing);
if !candidate.is_dir()
|| matched_path
.as_ref()
.is_some_and(|matched_path| matched_path != &candidate)
{
return None;
}
matched_path = Some(candidate);
}
ancestor = Some(left);
}
matched_path
}
#[cfg(any(windows, test))]
fn decode_cur_windows_project_drive(encoded: &str) -> Option<(char, &str)> {
let drive = encoded.as_bytes().first().copied()?;
if !drive.is_ascii_alphabetic() || encoded.as_bytes().get(1) != Some(&b'-') {
return None;
}
Some((char::from(drive), encoded.get(2..)?))
}
#[cfg(test)]
#[path = "cur_tests.rs"]
mod tests;

View File

@@ -0,0 +1,432 @@
use super::*;
use akode_protocol::ThreadId;
use pretty_assertions::assert_eq;
use std::fs::FileTimes;
use std::fs::OpenOptions;
use std::time::Duration;
use std::time::SystemTime;
use tempfile::TempDir;
#[test]
fn detects_cur_transcript_with_project_cwd() {
let root = TempDir::new().expect("tempdir");
let project_root = root.path().join("workspace with.dots_and-dashes");
fs::create_dir_all(&project_root).expect("project root");
let external_agent_home = root.path().join(".external");
let encoded_project = encode_project_path(&project_root);
let transcript = write_transcript(
&external_agent_home,
&encoded_project,
"a-session",
"first request",
);
let sessions =
detect_recent_cur_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()),
}]
);
}
#[test]
fn detects_projectless_cur_transcript_without_embedded_metadata() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".cursor");
let transcript = write_transcript(
&external_agent_home,
"empty-window",
"projectless-session",
"first request",
);
let sessions =
detect_recent_cur_sessions(&external_agent_home, root.path()).expect("detect sessions");
assert_eq!(
sessions,
vec![ExternalAgentSessionMigration {
path: transcript,
cwd: root.path().to_path_buf(),
title: Some("first request".to_string()),
}]
);
}
#[test]
fn resolves_projectless_cur_cwd_from_relative_home() {
let current_dir = std::env::current_dir().expect("current dir");
assert_eq!(
cur_project_cwd(
Path::new(".cursor/projects/empty-window"),
Path::new(".cursor"),
),
Some(current_dir)
);
}
#[test]
fn detects_cur_transcript_with_embedded_unc_cwd() {
let root = TempDir::new().expect("tempdir");
let external_agent_home = root.path().join(".external");
let encoded_project = "server-share-repo";
let unc_cwd = PathBuf::from(r"\\server\share\repo");
let transcript = external_agent_home
.join("projects")
.join(encoded_project)
.join("agent-transcripts")
.join("unc-session/unc-session.jsonl");
fs::create_dir_all(transcript.parent().expect("transcript parent"))
.expect("transcript directory");
fs::write(
&transcript,
[
serde_json::json!({
"cwd": unc_cwd,
"role": "user",
"timestamp_ms": 1_800_000_000_000_i64,
"message": {
"content": [{
"type": "text",
"text": "<user_query>first request</user_query>",
}],
},
})
.to_string(),
serde_json::json!({
"role": "assistant",
"message": {
"content": [{"type": "text", "text": "first answer"}],
},
})
.to_string(),
]
.join("\n"),
)
.expect("transcript");
assert_eq!(
detect_recent_cur_sessions(&external_agent_home, root.path()).expect("detect sessions"),
vec![ExternalAgentSessionMigration {
path: transcript,
cwd: unc_cwd,
title: Some("first request".to_string()),
}]
);
}
#[test]
fn skips_cur_subagent_transcripts() {
let root = TempDir::new().expect("tempdir");
let project_root = root.path().join("workspace");
fs::create_dir_all(&project_root).expect("project root");
let external_agent_home = root.path().join(".external");
let encoded_project = encode_project_path(&project_root);
let transcript = write_transcript(
&external_agent_home,
&encoded_project,
"main-session",
"first request",
);
let subagent_transcript = external_agent_home
.join("projects")
.join(&encoded_project)
.join("agent-transcripts")
.join("main-session/subagents/worker/worker.jsonl");
fs::create_dir_all(
subagent_transcript
.parent()
.expect("subagent transcript parent"),
)
.expect("subagent transcript directory");
fs::write(&subagent_transcript, transcript_contents("first request"))
.expect("subagent transcript");
let sessions =
detect_recent_cur_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()),
}]
);
}
#[test]
fn rejects_ambiguous_encoded_project_cwd() {
let root = TempDir::new().expect("tempdir");
let nested_project = root.path().join("workspace").join("nested");
let hyphenated_project = root.path().join("workspace-nested");
fs::create_dir_all(&nested_project).expect("nested project");
fs::create_dir_all(&hyphenated_project).expect("hyphenated project");
assert_eq!(
decode_cur_project_path(&encode_project_path(&nested_project)),
None
);
}
#[test]
fn resolves_cur_project_names_with_common_separators() {
for (project_name, encoded_name) in [
("project", "project"),
("my-project", "my-project"),
("my--project", "my-project"),
("my project", "my-project"),
("my.project", "my-project"),
("my..project", "my-project"),
("my_project", "my-project"),
("my+project", "my-project"),
("my@project", "my-project"),
("my&project", "my-project"),
("my-awesome-project", "my-awesome-project"),
("my-awesome-cool-project", "my-awesome-cool-project"),
] {
let root = TempDir::new().expect("tempdir");
let project = root.path().join(project_name);
fs::create_dir_all(&project).expect("project root");
let encoded = format!("{}-{encoded_name}", encode_project_path(root.path()));
assert_eq!(decode_cur_project_path(&encoded), Some(project));
}
}
#[test]
fn rejects_ambiguous_cur_project_without_a_direct_match() {
let root = TempDir::new().expect("tempdir");
for project_name in ["my-project", "my project", "my+project"] {
fs::create_dir_all(root.path().join(project_name)).expect("project root");
}
let encoded = format!("{}-my-project", encode_project_path(root.path()));
assert_eq!(decode_cur_project_path(&encoded), None);
}
#[test]
fn rejects_ambiguous_cur_project_with_punctuated_ancestor() {
let root = TempDir::new().expect("tempdir");
let punctuated_ancestor = root.path().join("a-b").join("c");
let punctuated_leaf = root.path().join("a").join("b-c");
fs::create_dir_all(&punctuated_ancestor).expect("punctuated ancestor project");
fs::create_dir_all(&punctuated_leaf).expect("punctuated leaf project");
let encoded = encode_project_path(&punctuated_ancestor);
assert_eq!(encoded, encode_project_path(&punctuated_leaf));
assert_eq!(decode_cur_project_path(&encoded), None);
}
#[test]
fn rejects_ambiguous_cur_project_with_multiple_punctuated_ancestors() {
for (first, second) in [
(&["a-b", "c-d", "e"][..], &["a", "b", "c", "d-e"][..]),
(&["a-b", "c-d"][..], &["a", "b", "c", "d"][..]),
] {
let root = TempDir::new().expect("tempdir");
let first = first
.iter()
.fold(root.path().to_path_buf(), |path, component| {
path.join(component)
});
let second = second
.iter()
.fold(root.path().to_path_buf(), |path, component| {
path.join(component)
});
fs::create_dir_all(&first).expect("first project");
fs::create_dir_all(&second).expect("second project");
let encoded = encode_project_path(&first);
assert_eq!(encoded, encode_project_path(&second));
assert_eq!(decode_cur_project_path(&encoded), None);
}
}
#[test]
fn parses_windows_cursor_fixture_project_directory() {
assert_eq!(
decode_cur_windows_project_drive("C--Users-fixture-Cursor"),
Some(('C', "-Users-fixture-Cursor"))
);
assert_eq!(
decode_cur_windows_project_drive("C-Users-fixture-Cursor"),
Some(('C', "Users-fixture-Cursor"))
);
assert_eq!(decode_cur_windows_project_drive("1-Users-fixture"), None);
}
#[test]
fn ignores_cur_sessions_older_than_import_window() {
let root = TempDir::new().expect("tempdir");
let project_root = root.path().join("workspace");
fs::create_dir_all(&project_root).expect("project root");
let external_agent_home = root.path().join(".external");
let transcript = write_transcript(
&external_agent_home,
&encode_project_path(&project_root),
"old-session",
"old request",
);
set_modified_at(
&transcript,
SystemTime::UNIX_EPOCH + Duration::from_secs(/*secs*/ 1),
);
assert!(
detect_recent_cur_sessions(&external_agent_home, root.path())
.expect("detect sessions")
.is_empty()
);
}
#[test]
fn detects_cur_sessions_in_batches_and_redetects_modified_imports() {
let root = TempDir::new().expect("tempdir");
let project_root = root.path().join("workspace");
fs::create_dir_all(&project_root).expect("project root");
let external_agent_home = root.path().join(".external");
let encoded_project = encode_project_path(&project_root);
let modified_at = SystemTime::now();
let mut expected = Vec::new();
let default_limits = ExternalAgentSessionImportLimits::default();
for index in 0..=default_limits.max_sessions {
let session_id = format!("session-{index:02}");
let title = format!("request {index}");
let path = write_transcript(&external_agent_home, &encoded_project, &session_id, &title);
set_modified_at(
&path,
modified_at - Duration::from_secs(/*secs*/ index as u64),
);
expected.push(ExternalAgentSessionMigration {
path,
cwd: project_root.clone(),
title: Some(title),
});
}
let oldest_session = expected.pop().expect("oldest session");
let sessions =
detect_recent_cur_sessions(&external_agent_home, root.path()).expect("detect sessions");
assert_eq!(sessions, expected);
for session in &sessions {
crate::sessions::ledger::record_imported_session(
root.path(),
&session.path,
ThreadId::new(),
)
.expect("record import");
}
assert_eq!(
detect_recent_cur_sessions(&external_agent_home, root.path()).expect("detect sessions"),
vec![oldest_session.clone()]
);
crate::sessions::ledger::record_imported_session(
root.path(),
&oldest_session.path,
ThreadId::new(),
)
.expect("record oldest import");
assert!(
detect_recent_cur_sessions(&external_agent_home, root.path())
.expect("detect sessions")
.is_empty()
);
let modified_session = &expected[0];
let updated_record = serde_json::json!({
"role": "assistant",
"message": {
"content": [{"type": "text", "text": "updated answer"}],
},
})
.to_string();
fs::write(
&modified_session.path,
format!(
"{}\n{updated_record}",
transcript_contents(modified_session.title.as_deref().expect("session title"))
),
)
.expect("update transcript");
set_modified_at(
&modified_session.path,
SystemTime::now() + Duration::from_secs(/*secs*/ 1),
);
assert_eq!(
detect_recent_cur_sessions(&external_agent_home, root.path()).expect("detect sessions"),
vec![modified_session.clone()]
);
}
fn write_transcript(
external_agent_home: &Path,
encoded_project: &str,
session_id: &str,
first_request: &str,
) -> PathBuf {
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, transcript_contents(first_request)).expect("transcript");
transcript
}
fn transcript_contents(first_request: &str) -> String {
[
serde_json::json!({
"role": "user",
"message": {
"content": [{
"type": "text",
"text": format!("<user_query>{first_request}</user_query>"),
}],
},
})
.to_string(),
serde_json::json!({
"role": "assistant",
"message": {
"content": [{"type": "text", "text": "first answer"}],
},
})
.to_string(),
]
.join("\n")
}
fn set_modified_at(path: &Path, modified_at: SystemTime) {
OpenOptions::new()
.write(true)
.open(path)
.expect("open transcript")
.set_times(FileTimes::new().set_modified(modified_at))
.expect("set transcript modified time");
}
#[cfg(windows)]
fn encode_project_path(path: &Path) -> String {
path.to_string_lossy().replace([':', '\\', '/'], "-")
}
#[cfg(not(windows))]
fn encode_project_path(path: &Path) -> String {
path.to_string_lossy()
.trim_start_matches('/')
.replace('/', "-")
}

View File

@@ -0,0 +1,40 @@
mod cla;
mod common;
mod connectors_cla;
mod connectors_cur;
mod cur;
use crate::model::DetectedConnectorCandidate;
use std::collections::BTreeMap;
use std::path::PathBuf;
pub use cla::detect_recent_cla_sessions;
pub(crate) use cla::detect_recent_cla_sessions_with_limits;
pub use connectors_cla::ImportedSessionConnectorAttribution;
pub(crate) use connectors_cla::detect_cla_session_connectors;
pub(crate) use connectors_cla::detect_cla_session_connectors_by_source_path;
pub use connectors_cla::detect_imported_cla_session_connectors;
pub use connectors_cla::detect_imported_cla_session_connectors_by_source_path;
pub(crate) use connectors_cur::detect_cur_session_connectors;
pub(crate) use connectors_cur::detect_cur_session_connectors_by_source_path;
pub use cur::detect_recent_cur_sessions;
pub(crate) use cur::detect_recent_cur_sessions_with_limits;
pub(crate) fn aggregate_session_connector_candidates(
candidates_by_source_path: BTreeMap<PathBuf, Vec<DetectedConnectorCandidate>>,
) -> Vec<DetectedConnectorCandidate> {
let mut candidates = BTreeMap::<String, DetectedConnectorCandidate>::new();
for session_candidates in candidates_by_source_path.into_values() {
for candidate in session_candidates {
let key = candidate.name.to_lowercase();
let session_count = candidate.session_count;
let aggregate = candidates.entry(key).or_insert_with(|| {
let mut aggregate = candidate;
aggregate.session_count = 0;
aggregate
});
aggregate.session_count = aggregate.session_count.saturating_add(session_count);
}
}
candidates.into_values().collect()
}