use serde::Serialize;
use std::path::PathBuf;
use std::sync::Arc;
use tauri::State;
use crate::core::{
central_repo, error::AppError, installer, scanner, skill_metadata::sanitize_skill_name,
skill_store::SkillStore, sync_metadata, tool_adapters,
};
fn canonicalize_lossy(path: &str) -> PathBuf {
std::fs::canonicalize(path).unwrap_or_else(|_| PathBuf::from(path))
}
fn match_imported_skill_id(
rec: &crate::core::skill_store::DiscoveredSkillRecord,
managed_skills: &[crate::core::skill_store::SkillRecord],
) -> Option<String> {
let found_path = canonicalize_lossy(&rec.found_path);
if let Some(existing) = managed_skills.iter().find(|skill| {
skill.source_ref.as_deref().map(canonicalize_lossy).as_ref() == Some(&found_path)
|| skill
.source_ref_resolved
.as_deref()
.map(canonicalize_lossy)
.as_ref()
== Some(&found_path)
}) {
return Some(existing.id.clone());
}
if let Some(fingerprint) = rec.fingerprint.as_deref() {
if let Some(existing) = managed_skills
.iter()
.find(|skill| skill.content_hash.as_deref() == Some(fingerprint))
{
return Some(existing.id.clone());
}
}
None
}
#[derive(Debug, Serialize)]
pub struct ScanResultDto {
pub tools_scanned: usize,
pub skills_found: usize,
pub groups: Vec<scanner::DiscoveredGroup>,
}
#[tauri::command]
pub async fn scan_local_skills(
store: State<'_, Arc<SkillStore>>,
) -> Result<ScanResultDto, AppError> {
let store = store.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let all_targets = store.get_all_targets().map_err(AppError::db)?;
let managed_skills = store.get_all_skills().map_err(AppError::db)?;
let managed_paths: Vec<String> = all_targets
.iter()
.map(|t| t.target_path.clone())
.chain(
managed_skills
.iter()
.map(|skill| skill.central_path.clone()),
)
.collect();
let adapters = tool_adapters::all_tool_adapters(&store);
let mut plan = scanner::scan_local_skills_with_adapters(&managed_paths, &adapters)
.map_err(AppError::io)?;
for rec in &mut plan.discovered {
rec.imported_skill_id = match_imported_skill_id(rec, &managed_skills);
}
store.clear_discovered().map_err(AppError::db)?;
for rec in &plan.discovered {
store.insert_discovered(rec).map_err(AppError::db)?;
}
let all_discovered = store.get_all_discovered().map_err(AppError::db)?;
let groups = scanner::group_discovered(&all_discovered);
Ok(ScanResultDto {
tools_scanned: plan.tools_scanned,
skills_found: plan.skills_found,
groups,
})
})
.await?
}
fn remove_existing_skill_by_name(
store: &SkillStore,
sanitized_name: &str,
) -> Result<(), anyhow::Error> {
let central_path = central_repo::skills_dir().join(sanitized_name);
let central_str = central_path.to_string_lossy().to_string();
if let Some(existing) = store.get_skill_by_central_path(¢ral_str)? {
store.delete_skill(&existing.id)?;
}
if central_path.exists() {
std::fs::remove_dir_all(¢ral_path)?;
}
Ok(())
}
#[tauri::command]
pub async fn check_import_conflict(
name: String,
store: State<'_, Arc<SkillStore>>,
) -> Result<Option<String>, AppError> {
let store = store.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let sanitized = sanitize_skill_name(&name).unwrap_or_else(|| name.clone());
let central_path = central_repo::skills_dir().join(&sanitized);
let central_str = central_path.to_string_lossy().to_string();
let existing = store
.get_skill_by_central_path(¢ral_str)
.map_err(AppError::db)?;
Ok(existing.map(|s| s.name))
})
.await?
}
#[tauri::command]
pub async fn check_import_all_conflicts(
store: State<'_, Arc<SkillStore>>,
) -> Result<Vec<String>, AppError> {
let store = store.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
let discovered = store.get_all_discovered().map_err(AppError::db)?;
let groups = scanner::group_discovered(&discovered);
let mut conflicts = Vec::new();
for group in &groups {
if group.imported {
continue;
}
let sanitized = sanitize_skill_name(&group.name).unwrap_or_else(|| group.name.clone());
let central_path = central_repo::skills_dir().join(&sanitized);
let central_str = central_path.to_string_lossy().to_string();
if let Ok(Some(_)) = store.get_skill_by_central_path(¢ral_str) {
conflicts.push(group.name.clone());
}
}
Ok(conflicts)
})
.await?
}
#[tauri::command]
pub async fn import_existing_skill(
source_path: String,
name: Option<String>,
overwrite: Option<bool>,
store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
let store = store.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
sync_metadata::with_repo_lock("import existing skill", || {
let path = PathBuf::from(&source_path);
let resolved_name = installer::resolve_local_skill_name(&path, name.as_deref())?;
if overwrite.unwrap_or(false) {
let sanitized =
sanitize_skill_name(&resolved_name).unwrap_or_else(|| resolved_name.clone());
remove_existing_skill_by_name(&store, &sanitized)?;
}
let result = installer::install_from_local(&path, Some(&resolved_name))?;
if store
.get_skill_by_central_path(&result.central_path.to_string_lossy())?
.is_some()
{
return Ok(());
}
let now = chrono::Utc::now().timestamp_millis();
let id = uuid::Uuid::new_v4().to_string();
let record = crate::core::skill_store::SkillRecord {
id: id.clone(),
name: result.name,
description: result.description,
source_type: "import".to_string(),
source_ref: Some(source_path),
source_ref_resolved: None,
source_subpath: None,
source_branch: None,
source_revision: None,
source_agent: None,
remote_revision: None,
central_path: result.central_path.to_string_lossy().to_string(),
content_hash: Some(result.content_hash),
enabled: true,
created_at: now,
updated_at: now,
status: "ok".to_string(),
update_status: "local_only".to_string(),
last_checked_at: Some(now),
last_check_error: None,
};
store.insert_skill(&record)?;
sync_metadata::write_all_from_db_unlocked(&store)
})
.map_err(AppError::io)?;
Ok(())
})
.await?
}
#[tauri::command]
pub async fn import_all_discovered(
overwrite: Option<bool>,
store: State<'_, Arc<SkillStore>>,
) -> Result<(), AppError> {
let store = store.inner().clone();
tauri::async_runtime::spawn_blocking(move || {
sync_metadata::with_repo_lock("import all discovered skills", || {
let discovered = store.get_all_discovered()?;
let groups = scanner::group_discovered(&discovered);
let mut changed = false;
for group in groups {
if group.imported {
continue;
}
if let Some(first) = group.locations.first() {
let path = PathBuf::from(&first.found_path);
if overwrite.unwrap_or(false) {
let sanitized =
sanitize_skill_name(&group.name).unwrap_or_else(|| group.name.clone());
remove_existing_skill_by_name(&store, &sanitized)?;
}
if let Ok(result) = installer::install_from_local(&path, Some(&group.name)) {
if store
.get_skill_by_central_path(&result.central_path.to_string_lossy())?
.is_some()
{
continue;
}
let now = chrono::Utc::now().timestamp_millis();
let id = uuid::Uuid::new_v4().to_string();
let record = crate::core::skill_store::SkillRecord {
id: id.clone(),
name: result.name,
description: result.description,
source_type: "import".to_string(),
source_ref: Some(first.found_path.clone()),
source_ref_resolved: None,
source_subpath: None,
source_branch: None,
source_revision: None,
source_agent: Some(first.tool.clone()),
remote_revision: None,
central_path: result.central_path.to_string_lossy().to_string(),
content_hash: Some(result.content_hash),
enabled: true,
created_at: now,
updated_at: now,
status: "ok".to_string(),
update_status: "local_only".to_string(),
last_checked_at: Some(now),
last_check_error: None,
};
store.insert_skill(&record)?;
changed = true;
}
}
}
if changed {
sync_metadata::write_all_from_db_unlocked(&store)?;
}
Ok(())
})
.map_err(AppError::io)?;
Ok(())
})
.await?
}
#[cfg(test)]
mod tests;