Skip to main content

agent_hub_runtime/commands/
projects.rs

1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
3use std::sync::atomic::AtomicBool;
4use std::sync::Arc;
5use std::time::Instant;
6use walkdir::WalkDir;
7
8use serde::Serialize;
9use tauri::State;
10
11use crate::core::skill_store::{ProjectRecord, SkillRecord, SkillStore};
12use crate::core::timing::should_log_first_or_slow;
13use crate::core::{error::AppError, installer, project_scanner, sync_engine, tool_adapters};
14
15#[derive(Serialize, Default)]
16pub struct SyncHealthDto {
17    pub in_sync: usize,
18    pub project_newer: usize,
19    pub center_newer: usize,
20    pub diverged: usize,
21    pub project_only: usize,
22}
23
24#[derive(Serialize)]
25pub struct ProjectDto {
26    pub id: String,
27    pub name: String,
28    pub path: String,
29    pub workspace_type: String,
30    pub linked_agent_name: Option<String>,
31    pub supports_skill_toggle: bool,
32    pub sort_order: i32,
33    pub skill_count: usize,
34    pub sync_health: SyncHealthDto,
35    pub created_at: i64,
36    pub updated_at: i64,
37    pub visited_at: Option<i64>,
38}
39
40#[derive(Serialize)]
41pub struct ProjectSkillDocumentDto {
42    pub skill_name: String,
43    pub filename: String,
44    pub content: String,
45}
46
47#[derive(Serialize)]
48pub struct ProjectSkillFileDto {
49    pub filename: String,
50    pub content: String,
51}
52
53#[derive(Serialize, Clone)]
54pub struct ProjectAgentTargetDto {
55    pub key: String,
56    pub display_name: String,
57    pub enabled: bool,
58    pub installed: bool,
59    pub is_custom: bool,
60}
61
62pub(super) fn agent_skill_configs(store: &SkillStore) -> Vec<project_scanner::AgentSkillConfig> {
63    let mut grouped: Vec<(String, Vec<(String, String)>)> = Vec::new();
64    for adapter in tool_adapters::all_tool_adapters(store) {
65        let project_dir = adapter.project_relative_skills_dir().to_string();
66        if project_dir.is_empty() {
67            continue;
68        }
69        if let Some((_, agents)) = grouped.iter_mut().find(|(dir, _)| *dir == project_dir) {
70            agents.push((adapter.key, adapter.display_name));
71        } else {
72            grouped.push((project_dir, vec![(adapter.key, adapter.display_name)]));
73        }
74    }
75
76    grouped
77        .into_iter()
78        .filter_map(|(relative_skills_dir, agents)| {
79            let (key, first_display_name) = agents.first()?.clone();
80            let display_name = if agents.len() == 1 {
81                first_display_name
82            } else {
83                agents
84                    .into_iter()
85                    .map(|(_, display_name)| display_name)
86                    .collect::<Vec<_>>()
87                    .join(" / ")
88            };
89            Some(project_scanner::AgentSkillConfig {
90                key,
91                display_name,
92                relative_skills_dir,
93            })
94        })
95        .collect()
96}
97
98fn linked_workspace_agent_key(rec: &ProjectRecord) -> String {
99    rec.linked_agent_key
100        .clone()
101        .unwrap_or_else(|| slugify_skill_dir_name(&rec.name))
102}
103
104fn linked_workspace_agent_name(rec: &ProjectRecord) -> String {
105    rec.linked_agent_name
106        .clone()
107        .unwrap_or_else(|| rec.name.clone())
108}
109
110pub(super) fn read_workspace_skills(
111    rec: &ProjectRecord,
112    configs: &[project_scanner::AgentSkillConfig],
113) -> Vec<project_scanner::ProjectSkillInfo> {
114    if rec.workspace_type == "linked" {
115        return project_scanner::read_linked_workspace_skills(
116            Path::new(&rec.path),
117            rec.disabled_path.as_deref().map(Path::new),
118            &linked_workspace_agent_key(rec),
119            &linked_workspace_agent_name(rec),
120            true,
121        );
122    }
123    project_scanner::read_project_skills(Path::new(&rec.path), configs)
124}
125
126/// Resolve the enabled and disabled skills root directories for a given agent in a workspace.
127pub(super) fn resolve_agent_skills_roots(
128    store: &SkillStore,
129    rec: &ProjectRecord,
130    agent: &str,
131) -> Option<(PathBuf, Option<PathBuf>)> {
132    if rec.workspace_type == "linked" {
133        if linked_workspace_agent_key(rec) != agent {
134            return None;
135        }
136        return Some((
137            PathBuf::from(&rec.path),
138            rec.disabled_path.as_ref().map(PathBuf::from),
139        ));
140    }
141
142    let adapter = tool_adapters::all_tool_adapters(store)
143        .into_iter()
144        .find(|adapter| adapter.key == agent)?;
145    let project_dir = adapter.project_relative_skills_dir();
146    let skills_root = Path::new(&rec.path).join(project_dir);
147    let disabled_root = Path::new(&rec.path).join(format!("{}-disabled", project_dir));
148    Some((skills_root, Some(disabled_root)))
149}
150
151fn project_agent_targets_for_record(
152    store: &SkillStore,
153    rec: &ProjectRecord,
154) -> Vec<ProjectAgentTargetDto> {
155    if rec.workspace_type == "linked" {
156        return vec![ProjectAgentTargetDto {
157            key: linked_workspace_agent_key(rec),
158            display_name: linked_workspace_agent_name(rec),
159            enabled: true,
160            installed: true,
161            is_custom: false,
162        }];
163    }
164
165    agent_skill_configs(store)
166        .into_iter()
167        .map(|config| {
168            let adapter = tool_adapters::find_adapter_with_store(store, &config.key);
169            ProjectAgentTargetDto {
170                // Project targets describe team support, independent of personal preferences.
171                enabled: true,
172                installed: adapter.as_ref().map(|a| a.is_installed()).unwrap_or(false),
173                is_custom: adapter.as_ref().map(|a| a.is_custom).unwrap_or(false),
174                key: config.key,
175                display_name: config.display_name,
176            }
177        })
178        .collect()
179}
180
181/// Convert a project record into its DTO, folding the copies of one logical
182/// skill across agents together by relative path.
183fn project_to_dto(
184    rec: &ProjectRecord,
185    all_managed: &[SkillRecord],
186    configs: &[project_scanner::AgentSkillConfig],
187) -> ProjectDto {
188    let skills = read_workspace_skills(rec, configs);
189    let mut grouped_statuses: HashMap<String, String> = HashMap::new();
190
191    for skill in &skills {
192        let matched = find_best_center_match(skill, all_managed);
193        let status = classify_sync_status(skill, matched);
194        let key = skill.relative_path.to_lowercase();
195        let existing = grouped_statuses
196            .entry(key)
197            .or_insert_with(|| status.clone());
198        if sync_status_priority(&status) > sync_status_priority(existing) {
199            *existing = status;
200        }
201    }
202
203    let skill_count = grouped_statuses.len();
204    let mut health = SyncHealthDto::default();
205    for status in grouped_statuses.values() {
206        match status.as_str() {
207            "in_sync" => health.in_sync += 1,
208            "project_newer" => health.project_newer += 1,
209            "center_newer" => health.center_newer += 1,
210            "diverged" => health.diverged += 1,
211            _ => health.project_only += 1,
212        }
213    }
214
215    ProjectDto {
216        skill_count,
217        sync_health: health,
218        ..project_metadata(rec)
219    }
220}
221
222pub(crate) fn project_metadata(rec: &ProjectRecord) -> ProjectDto {
223    ProjectDto {
224        id: rec.id.clone(),
225        name: rec.name.clone(),
226        path: rec.path.clone(),
227        workspace_type: rec.workspace_type.clone(),
228        linked_agent_name: rec.linked_agent_name.clone(),
229        supports_skill_toggle: rec.workspace_type != "linked" || rec.disabled_path.is_some(),
230        sort_order: rec.sort_order,
231        skill_count: 0,
232        sync_health: SyncHealthDto::default(),
233        created_at: rec.created_at,
234        updated_at: rec.updated_at,
235        visited_at: rec.visited_at,
236    }
237}
238
239/// Severity of a sync status, used to reduce one logical skill's per-agent
240/// copies to a single verdict: the worst one the group carries.
241fn sync_status_priority(status: &str) -> u8 {
242    match status {
243        "diverged" => 5,
244        "project_newer" => 4,
245        "center_newer" => 3,
246        "project_only" => 2,
247        "in_sync" => 1,
248        _ => 0,
249    }
250}
251
252pub(crate) use crate::core::path_guard::{ensure_dir_within_root, ensure_safe_skill_relative_path};
253use crate::core::project_skill_toggle::set_project_skill_enabled_state;
254
255fn remove_workspace_skill_target(path: &Path) -> Result<(), AppError> {
256    sync_engine::remove_target(path).map_err(AppError::io)
257}
258
259fn ensure_distinct_linked_workspace_roots(
260    skills_root: &Path,
261    disabled_root: &Path,
262) -> Result<(), AppError> {
263    let skills_canonical = std::fs::canonicalize(skills_root)?;
264    let disabled_canonical = std::fs::canonicalize(disabled_root)?;
265
266    if skills_canonical == disabled_canonical
267        || skills_canonical.starts_with(&disabled_canonical)
268        || disabled_canonical.starts_with(&skills_canonical)
269    {
270        return Err(AppError::invalid_input(
271            "Skills directory and disabled skills directory must not overlap",
272        ));
273    }
274
275    Ok(())
276}
277
278pub(crate) fn slugify_skill_dir_name(name: &str) -> String {
279    let mut out = String::new();
280    let mut prev_dash = false;
281    for ch in name.chars().flat_map(|c| c.to_lowercase()) {
282        let valid = ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || ch == '.';
283        if valid {
284            out.push(ch);
285            prev_dash = false;
286        } else if !prev_dash {
287            out.push('-');
288            prev_dash = true;
289        }
290    }
291    let trimmed = out.trim_matches(|c| c == '-' || c == '_' || c == '.');
292    if trimmed.is_empty() {
293        "skill".to_string()
294    } else {
295        trimmed.to_string()
296    }
297}
298
299pub(crate) fn source_ref_matches_skill_path(
300    skill_path: &str,
301    skill_canonical: Option<&PathBuf>,
302    managed: &SkillRecord,
303) -> bool {
304    let Some(source_ref) = managed.source_ref.as_deref() else {
305        return false;
306    };
307    if source_ref == skill_path {
308        return true;
309    }
310    let Some(skill_canonical) = skill_canonical else {
311        return false;
312    };
313    let Ok(source_canonical) = std::fs::canonicalize(source_ref) else {
314        return false;
315    };
316    source_canonical == *skill_canonical
317}
318
319pub(crate) fn find_best_center_match<'a>(
320    skill: &project_scanner::ProjectSkillInfo,
321    all_managed: &'a [SkillRecord],
322) -> Option<&'a SkillRecord> {
323    let skill_hash = skill.content_hash.as_deref();
324    let canonical_skill_path = std::fs::canonicalize(&skill.path).ok();
325
326    // source_ref is the strongest direct link there is.
327    if let Some(managed) = all_managed.iter().find(|managed| {
328        source_ref_matches_skill_path(&skill.path, canonical_skill_path.as_ref(), managed)
329    }) {
330        return Some(managed);
331    }
332
333    // A content hash that names exactly one library skill outranks any
334    // directory or name evidence: it says the two directories hold the same
335    // bytes, while a directory name only says they were once called the same
336    // thing. An export written under a slugified name can land on a directory
337    // that now reads as a *different* skill (a library holding both
338    // "Code Review" and "code-review" exports the first as `code-review`),
339    // and this match also decides where an import writes back — binding the
340    // wrong row there overwrites the other skill.
341    //
342    // Only a unique hash qualifies. Several skills sharing one hash is the
343    // arbitrary-pick this fix exists to remove, and those fall through to the
344    // directory and name layers below.
345    if let Some(hash) = skill_hash {
346        let mut by_hash = all_managed
347            .iter()
348            .filter(|managed| managed.content_hash.as_deref() == Some(hash));
349        if let Some(first) = by_hash.next() {
350            if by_hash.next().is_none() {
351                return Some(first);
352            }
353        }
354    }
355
356    // The central directory name is steadier than the frontmatter name:
357    // several skills shipped from one repo can share the latter.
358    let by_central_dir: Vec<&SkillRecord> = all_managed
359        .iter()
360        .filter(|managed| {
361            Path::new(&managed.central_path)
362                .file_name()
363                .map(|name| name.to_string_lossy().eq_ignore_ascii_case(&skill.dir_name))
364                .unwrap_or(false)
365        })
366        .collect();
367    if let Some(managed) = unique_center_match(&by_central_dir, skill_hash) {
368        return Some(managed);
369    }
370
371    // Covers the ordinary skill whose name and directory agree.
372    let by_name: Vec<&SkillRecord> = all_managed
373        .iter()
374        .filter(|managed| {
375            slugify_skill_dir_name(&managed.name).eq_ignore_ascii_case(&skill.dir_name)
376        })
377        .collect();
378    if let Some(managed) = unique_center_match(&by_name, skill_hash) {
379        return Some(managed);
380    }
381
382    None
383}
384
385/// Pick the one skill among candidates sharing an identity signal,
386/// disambiguating by content hash when the signal alone leaves several.
387fn unique_center_match<'a>(
388    candidates: &[&'a SkillRecord],
389    skill_hash: Option<&str>,
390) -> Option<&'a SkillRecord> {
391    match candidates.len() {
392        0 => None,
393        1 => Some(candidates[0]),
394        _ => {
395            let hash = skill_hash?;
396            let mut filtered = candidates
397                .iter()
398                .copied()
399                .filter(|managed| managed.content_hash.as_deref() == Some(hash));
400            let first = filtered.next()?;
401            filtered.next().is_none().then_some(first)
402        }
403    }
404}
405
406pub(crate) fn classify_sync_status(
407    skill: &project_scanner::ProjectSkillInfo,
408    managed: Option<&SkillRecord>,
409) -> String {
410    let Some(managed) = managed else {
411        return "project_only".to_string();
412    };
413
414    // Fast path: compare project hash against DB-stored center hash
415    if skill.content_hash.is_some()
416        && managed.content_hash.as_deref() == skill.content_hash.as_deref()
417    {
418        return "in_sync".to_string();
419    }
420
421    // The DB hash may be stale, and `updated_at` is the wrong clock for the
422    // comparison further down, so read the center from disk once and answer
423    // both questions from the same walk.
424    let center_entries =
425        crate::core::content_hash::list_content_files(Path::new(&managed.central_path));
426
427    if let Some(project_hash) = skill.content_hash.as_deref() {
428        if project_hash == crate::core::content_hash::hash_entries(&center_entries) {
429            return "in_sync".to_string();
430        }
431    }
432
433    let Some(project_modified_at) = skill.last_modified_at else {
434        return "diverged".to_string();
435    };
436
437    // The project side is a filesystem mtime, so the center has to be one too.
438    // `updated_at` is a database column stamped when the row was written:
439    // editing files in the library does not move it, and a metadata-only write
440    // moves it while no content changed. Comparing the two rulers reported
441    // "center is newer" for a project copy the user had just edited, and that
442    // status invites a pull, which overwrites the edit — the diagnosis behind
443    // #328.
444    let Some(center_modified_at) = crate::core::content_hash::latest_modified_ms(&center_entries)
445    else {
446        return "diverged".to_string();
447    };
448    let threshold_ms = 1_000;
449    if project_modified_at > center_modified_at + threshold_ms {
450        "project_newer".to_string()
451    } else if center_modified_at > project_modified_at + threshold_ms {
452        "center_newer".to_string()
453    } else {
454        "diverged".to_string()
455    }
456}
457
458static GET_PROJECTS_FIRST_CALL: AtomicBool = AtomicBool::new(true);
459
460#[tauri::command]
461pub async fn get_projects(
462    store: State<'_, Arc<SkillStore>>,
463    metadata_only: Option<bool>,
464) -> Result<Vec<ProjectDto>, AppError> {
465    let store = store.inner().clone();
466    tauri::async_runtime::spawn_blocking(move || {
467        let start = Instant::now();
468        store.prune_recent_projects().map_err(AppError::db)?;
469        let records = store.get_all_projects().map_err(AppError::db)?;
470        if metadata_only.unwrap_or(false) {
471            return Ok(records.iter().map(project_metadata).collect());
472        }
473        let all_managed = store.get_all_skills().map_err(AppError::db)?;
474        let configs = agent_skill_configs(&store);
475        let count = records.len();
476        let dtos: Vec<ProjectDto> = records
477            .iter()
478            .map(|r| project_to_dto(r, &all_managed, &configs))
479            .collect();
480        let elapsed_ms = start.elapsed().as_millis();
481        if should_log_first_or_slow(&GET_PROJECTS_FIRST_CALL, elapsed_ms, 100) {
482            log::info!("get_projects: {count} projects in {elapsed_ms} ms");
483        }
484        Ok(dtos)
485    })
486    .await?
487}
488
489#[tauri::command]
490pub async fn add_project(
491    store: State<'_, Arc<SkillStore>>,
492    path: String,
493) -> Result<ProjectDto, AppError> {
494    let store = store.inner().clone();
495    tauri::async_runtime::spawn_blocking(move || {
496        let project_path = Path::new(&path);
497        if !project_path.is_dir() {
498            return Err(AppError::invalid_input("Directory does not exist"));
499        }
500        let claude_dir = project_path.join(".claude");
501        let skills_dir = claude_dir.join("skills");
502        let disabled_dir = claude_dir.join("skills-disabled");
503
504        // Support initializing an empty project directory as a managed project.
505        std::fs::create_dir_all(&skills_dir)?;
506        std::fs::create_dir_all(&disabled_dir)?;
507
508        let name = project_path
509            .file_name()
510            .map(|n| n.to_string_lossy().to_string())
511            .unwrap_or_else(|| "unknown".to_string());
512
513        let now = chrono::Utc::now().timestamp_millis();
514        let record = ProjectRecord {
515            id: uuid::Uuid::new_v4().to_string(),
516            name,
517            path: path.clone(),
518            workspace_type: "project".to_string(),
519            linked_agent_key: None,
520            linked_agent_name: None,
521            disabled_path: None,
522            sort_order: 0,
523            created_at: now,
524            updated_at: now,
525            visited_at: None,
526        };
527
528        store.insert_project(&record).map_err(AppError::db)?;
529        let all_managed = store.get_all_skills().map_err(AppError::db)?;
530        let configs = agent_skill_configs(&store);
531        Ok(project_to_dto(&record, &all_managed, &configs))
532    })
533    .await?
534}
535
536#[tauri::command]
537pub async fn add_linked_workspace(
538    store: State<'_, Arc<SkillStore>>,
539    name: String,
540    path: String,
541    disabled_path: Option<String>,
542) -> Result<ProjectDto, AppError> {
543    let store = store.inner().clone();
544    tauri::async_runtime::spawn_blocking(move || {
545        let name = name.trim().to_string();
546        if name.is_empty() {
547            return Err(AppError::invalid_input("Workspace name is required"));
548        }
549
550        let skills_root = PathBuf::from(path.trim());
551        if !skills_root.is_dir() {
552            return Err(AppError::invalid_input("Skills directory does not exist"));
553        }
554
555        let disabled_path = disabled_path
556            .as_deref()
557            .map(str::trim)
558            .filter(|value| !value.is_empty())
559            .map(str::to_string);
560        let disabled_path = if let Some(disabled) = disabled_path {
561            let disabled_root = PathBuf::from(&disabled);
562            if !disabled_root.is_dir() {
563                return Err(AppError::invalid_input(
564                    "Disabled skills directory does not exist",
565                ));
566            }
567            ensure_distinct_linked_workspace_roots(&skills_root, &disabled_root)?;
568            Some(disabled)
569        } else {
570            let mut disabled_root = skills_root.clone();
571            let derived = disabled_root
572                .file_name()
573                .and_then(|n| n.to_str())
574                .map(|name| format!("{}-disabled", name));
575            match derived {
576                Some(name) => {
577                    disabled_root.set_file_name(name);
578                    match std::fs::create_dir_all(&disabled_root) {
579                        Ok(()) => {
580                            ensure_distinct_linked_workspace_roots(&skills_root, &disabled_root)?;
581                            Some(disabled_root.to_string_lossy().to_string())
582                        }
583                        Err(_) => None,
584                    }
585                }
586                None => None,
587            }
588        };
589
590        let now = chrono::Utc::now().timestamp_millis();
591        let record = ProjectRecord {
592            id: uuid::Uuid::new_v4().to_string(),
593            name: name.clone(),
594            path: skills_root.to_string_lossy().to_string(),
595            workspace_type: "linked".to_string(),
596            linked_agent_key: Some(slugify_skill_dir_name(&name)),
597            linked_agent_name: Some(name),
598            disabled_path,
599            sort_order: 0,
600            created_at: now,
601            updated_at: now,
602            visited_at: None,
603        };
604
605        store.insert_project(&record).map_err(AppError::db)?;
606        let all_managed = store.get_all_skills().map_err(AppError::db)?;
607        let configs = agent_skill_configs(&store);
608        Ok(project_to_dto(&record, &all_managed, &configs))
609    })
610    .await?
611}
612
613#[tauri::command]
614pub async fn remove_project(store: State<'_, Arc<SkillStore>>, id: String) -> Result<(), AppError> {
615    let store = store.inner().clone();
616    tauri::async_runtime::spawn_blocking(move || store.delete_project(&id).map_err(AppError::db))
617        .await?
618}
619
620#[tauri::command]
621pub async fn reorder_projects(
622    ids: Vec<String>,
623    store: State<'_, Arc<SkillStore>>,
624) -> Result<(), AppError> {
625    let store = store.inner().clone();
626    tauri::async_runtime::spawn_blocking(move || store.reorder_projects(&ids).map_err(AppError::db))
627        .await?
628}
629
630#[tauri::command]
631pub async fn touch_project_visited(
632    app: tauri::AppHandle,
633    id: String,
634    store: State<'_, Arc<SkillStore>>,
635) -> Result<(), AppError> {
636    let store = store.inner().clone();
637    let visits = tauri::async_runtime::spawn_blocking(move || {
638        store.touch_project_visited(&id).map_err(AppError::db)?;
639        store.project_visit_history().map_err(AppError::db)
640    })
641    .await??;
642    tauri::Emitter::emit(&app, "project-visits-changed", visits).map_err(AppError::io)
643}
644
645#[tauri::command]
646pub async fn scan_projects(
647    root: String,
648    store: State<'_, Arc<SkillStore>>,
649) -> Result<Vec<String>, AppError> {
650    let store = store.inner().clone();
651    tauri::async_runtime::spawn_blocking(move || {
652        let root_path = Path::new(&root);
653        if !root_path.is_dir() {
654            return Err(AppError::invalid_input("Directory does not exist"));
655        }
656        let configs = agent_skill_configs(&store);
657        Ok(project_scanner::scan_projects_in_dir(
658            root_path, 4, &configs,
659        ))
660    })
661    .await?
662}
663
664#[tauri::command]
665pub async fn get_project_agent_targets(
666    store: State<'_, Arc<SkillStore>>,
667    project_id: String,
668) -> Result<Vec<ProjectAgentTargetDto>, AppError> {
669    let store = store.inner().clone();
670    tauri::async_runtime::spawn_blocking(move || {
671        let record = store
672            .get_project_by_id(&project_id)
673            .map_err(AppError::db)?
674            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
675        Ok(project_agent_targets_for_record(&store, &record))
676    })
677    .await?
678}
679
680#[tauri::command]
681pub async fn get_project_skills(
682    store: State<'_, Arc<SkillStore>>,
683    project_id: String,
684) -> Result<Vec<project_scanner::ProjectSkillInfo>, AppError> {
685    let store = store.inner().clone();
686    tauri::async_runtime::spawn_blocking(move || {
687        let record = store
688            .get_project_by_id(&project_id)
689            .map_err(AppError::db)?
690            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
691
692        let configs = agent_skill_configs(&store);
693        let mut skills = read_workspace_skills(&record, &configs);
694
695        let all_managed = store.get_all_skills().unwrap_or_default();
696        let tags_map = store.get_tags_map().unwrap_or_default();
697        for skill in &mut skills {
698            let matched = find_best_center_match(skill, &all_managed);
699            skill.in_center = matched.is_some();
700            skill.center_skill_id = matched.map(|m| m.id.clone());
701            skill.tags = skill
702                .center_skill_id
703                .as_ref()
704                .and_then(|skill_id| tags_map.get(skill_id).cloned())
705                .unwrap_or_default();
706            skill.sync_status = classify_sync_status(skill, matched);
707        }
708
709        Ok(skills)
710    })
711    .await?
712}
713
714#[tauri::command]
715pub async fn get_project_skill_document(
716    project_id: String,
717    skill_relative_path: String,
718    agent: String,
719    store: State<'_, Arc<SkillStore>>,
720) -> Result<ProjectSkillDocumentDto, AppError> {
721    let store = store.inner().clone();
722    tauri::async_runtime::spawn_blocking(move || {
723        ensure_safe_skill_relative_path(&skill_relative_path)?;
724
725        let record = store
726            .get_project_by_id(&project_id)
727            .map_err(AppError::db)?
728            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
729
730        let (skills_root, disabled_root) = resolve_agent_skills_roots(&store, &record, &agent)
731            .ok_or_else(|| AppError::not_found(format!("Unknown workspace agent: {}", agent)))?;
732        let disabled_root_copy = disabled_root.clone();
733        let skill_dir = skills_root.join(&skill_relative_path);
734        let skill_dir = if skill_dir.is_dir() {
735            ensure_dir_within_root(&skill_dir, &skills_root)?;
736            skill_dir
737        } else if let Some(disabled_root) = disabled_root {
738            let disabled = disabled_root.join(&skill_relative_path);
739            if disabled.is_dir() {
740                ensure_dir_within_root(&disabled, &disabled_root)?;
741                disabled
742            } else {
743                return Err(AppError::not_found("Skill directory not found"));
744            }
745        } else {
746            return Err(AppError::not_found("Skill directory not found"));
747        };
748
749        // Collect all allowed roots for symlink target validation
750        let mut allowed_roots: Vec<PathBuf> = vec![skills_root.clone()];
751        if let Some(dr) = disabled_root_copy {
752            allowed_roots.push(dr);
753        }
754        // For project workspaces, also allow the project root itself
755        if record.workspace_type != "linked" {
756            allowed_roots.push(PathBuf::from(&record.path));
757        }
758
759        let candidates = ["SKILL.md", "skill.md", "CLAUDE.md", "README.md"];
760        for candidate in &candidates {
761            let file_path = skill_dir.join(candidate);
762            if !file_path.exists() {
763                continue;
764            }
765            // For symlinks, verify the resolved target stays within an allowed root
766            if let Ok(meta) = std::fs::symlink_metadata(&file_path) {
767                if meta.file_type().is_symlink() {
768                    let resolved = match std::fs::canonicalize(&file_path) {
769                        Ok(r) => r,
770                        Err(_) => continue, // broken symlink
771                    };
772                    let in_allowed_root = allowed_roots.iter().any(|root| {
773                        std::fs::canonicalize(root)
774                            .map(|canon| resolved.starts_with(&canon))
775                            .unwrap_or(false)
776                    });
777                    if !in_allowed_root {
778                        continue;
779                    }
780                }
781            }
782            if file_path.is_file() {
783                let content = std::fs::read_to_string(&file_path)?;
784                return Ok(ProjectSkillDocumentDto {
785                    skill_name: skill_relative_path,
786                    filename: candidate.to_string(),
787                    content,
788                });
789            }
790        }
791
792        Err(AppError::not_found(
793            "No document file found in skill directory",
794        ))
795    })
796    .await?
797}
798
799#[tauri::command]
800pub async fn get_project_skill_files(
801    project_id: String,
802    skill_relative_path: String,
803    agent: String,
804    store: State<'_, Arc<SkillStore>>,
805) -> Result<Vec<ProjectSkillFileDto>, AppError> {
806    let store = store.inner().clone();
807    tauri::async_runtime::spawn_blocking(move || {
808        ensure_safe_skill_relative_path(&skill_relative_path)?;
809        let record = store
810            .get_project_by_id(&project_id)
811            .map_err(AppError::db)?
812            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
813        let (skills_root, disabled_root) = resolve_agent_skills_roots(&store, &record, &agent)
814            .ok_or_else(|| AppError::not_found(format!("Unknown workspace agent: {}", agent)))?;
815        let skill_dir = skills_root.join(&skill_relative_path);
816        let skill_dir = if skill_dir.is_dir() {
817            ensure_dir_within_root(&skill_dir, &skills_root)?;
818            skill_dir
819        } else if let Some(disabled_root) = disabled_root {
820            let disabled = disabled_root.join(&skill_relative_path);
821            if !disabled.is_dir() {
822                return Err(AppError::not_found("Skill directory not found"));
823            }
824            ensure_dir_within_root(&disabled, &disabled_root)?;
825            disabled
826        } else {
827            return Err(AppError::not_found("Skill directory not found"));
828        };
829
830        let mut files = Vec::new();
831        for entry in WalkDir::new(&skill_dir)
832            .max_depth(8)
833            .into_iter()
834            .filter_map(Result::ok)
835        {
836            if !entry.file_type().is_file() {
837                continue;
838            }
839            let path = entry.path();
840            if let Ok(content) = std::fs::read_to_string(path) {
841                let filename = path
842                    .strip_prefix(&skill_dir)
843                    .map_err(AppError::io)?
844                    .to_string_lossy()
845                    .replace('\\', "/");
846                files.push(ProjectSkillFileDto { filename, content });
847            }
848        }
849        files.sort_by(|a, b| a.filename.cmp(&b.filename));
850        Ok(files)
851    })
852    .await?
853}
854
855#[tauri::command]
856pub async fn import_project_skill_to_center(
857    store: State<'_, Arc<SkillStore>>,
858    project_id: String,
859    skill_relative_path: String,
860    agent: String,
861) -> Result<String, AppError> {
862    let store = store.inner().clone();
863    tauri::async_runtime::spawn_blocking(move || {
864        ensure_safe_skill_relative_path(&skill_relative_path)?;
865
866        let record = store
867            .get_project_by_id(&project_id)
868            .map_err(AppError::db)?
869            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
870
871        let configs = agent_skill_configs(&store);
872        let skills = read_workspace_skills(&record, &configs);
873        let skill = skills
874            .iter()
875            .find(|s| s.relative_path == skill_relative_path && s.agent == agent)
876            .ok_or_else(|| AppError::not_found("Skill not found in workspace"))?;
877
878        let source_path = PathBuf::from(&skill.path);
879        let all_managed = store.get_all_skills().unwrap_or_default();
880        // Use the same matching logic as the UI (find_best_center_match) to
881        // stay consistent with sync-status display. After updating, bind
882        // source_ref so future imports match by exact path.
883        if let Some(existing) = find_best_center_match(skill, &all_managed) {
884            let result = installer::install_from_local_to_destination(
885                &source_path,
886                Some(&existing.name),
887                Path::new(&existing.central_path),
888            )
889            .map_err(AppError::io)?;
890            store
891                .update_skill_after_install(
892                    &existing.id,
893                    &existing.name,
894                    result.description.as_deref(),
895                    existing.source_revision.as_deref(),
896                    existing.remote_revision.as_deref(),
897                    Some(&result.content_hash),
898                    "local_only",
899                )
900                .map_err(AppError::db)?;
901            // Only update source_ref when the match was already by source_ref
902            // path (not by hash or name). This avoids permanently rebinding
903            // unrelated center skills that merely share a name or content.
904            let already_matched_by_ref = source_ref_matches_skill_path(
905                &skill.path,
906                std::fs::canonicalize(&skill.path).ok().as_ref(),
907                existing,
908            );
909            if existing.source_type == "local" && already_matched_by_ref {
910                store
911                    .update_skill_source_ref(&existing.id, &skill.path)
912                    .map_err(AppError::db)?;
913            }
914            return Ok(existing.id.clone());
915        }
916
917        let result =
918            installer::install_from_local(&source_path, Some(&skill.name)).map_err(AppError::io)?;
919
920        let now = chrono::Utc::now().timestamp_millis();
921        let id = uuid::Uuid::new_v4().to_string();
922
923        let skill_record = SkillRecord {
924            id: id.clone(),
925            name: result.name.clone(),
926            description: result.description.clone(),
927            source_type: "local".to_string(),
928            source_ref: Some(skill.path.clone()),
929            source_ref_resolved: None,
930            source_subpath: None,
931            source_branch: None,
932            source_revision: None,
933            source_agent: None,
934            remote_revision: None,
935            central_path: result.central_path.to_string_lossy().to_string(),
936            content_hash: Some(result.content_hash.clone()),
937            enabled: true,
938            created_at: now,
939            updated_at: now,
940            status: "ok".to_string(),
941            update_status: "local_only".to_string(),
942            last_checked_at: Some(now),
943            last_check_error: None,
944        };
945
946        store.insert_skill(&skill_record).map_err(AppError::db)?;
947
948        Ok(id)
949    })
950    .await?
951}
952
953#[tauri::command]
954pub async fn update_project_skill_to_center(
955    store: State<'_, Arc<SkillStore>>,
956    project_id: String,
957    skill_relative_path: String,
958    agent: String,
959) -> Result<String, AppError> {
960    import_project_skill_to_center(store, project_id, skill_relative_path, agent).await
961}
962
963#[tauri::command]
964pub fn slugify_skill_names(names: Vec<String>) -> Vec<String> {
965    names.iter().map(|n| slugify_skill_dir_name(n)).collect()
966}
967
968#[tauri::command]
969pub async fn export_skill_to_project(
970    store: State<'_, Arc<SkillStore>>,
971    skill_id: String,
972    project_id: String,
973    agents: Option<Vec<String>>,
974    copy: Option<bool>,
975) -> Result<(), AppError> {
976    let store = store.inner().clone();
977    tauri::async_runtime::spawn_blocking(move || {
978        let project = store
979            .get_project_by_id(&project_id)
980            .map_err(AppError::db)?
981            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
982
983        let skill = store
984            .get_skill_by_id(&skill_id)
985            .map_err(AppError::db)?
986            .ok_or_else(|| AppError::not_found("Skill not found"))?;
987
988        if project.workspace_type != "linked" {
989            let keys = agents
990                .filter(|keys| !keys.is_empty())
991                .unwrap_or_else(|| vec!["claude_code".into()]);
992            let targets = keys
993                .iter()
994                .map(|key| {
995                    tool_adapters::find_adapter_with_store(&store, key)
996                        .ok_or_else(|| AppError::not_found(format!("Unknown agent: {key}")))
997                })
998                .collect::<Result<Vec<_>, _>>()?;
999            crate::core::project_library::install_with_mode(
1000                Path::new(&project.path),
1001                &skill,
1002                &targets,
1003                matches!(
1004                    crate::core::deployment_preferences::Preference::load(
1005                        &store,
1006                        crate::core::deployment_preferences::Scope::Project,
1007                    )?
1008                    .for_install(copy),
1009                    sync_engine::SyncMode::Copy
1010                ),
1011            )?;
1012            return Ok(());
1013        }
1014
1015        let source = PathBuf::from(&skill.central_path);
1016        let dir_name = sync_engine::target_dir_name(&source, &skill.name);
1017        ensure_safe_skill_relative_path(&dir_name)?;
1018        let requested_agent_keys = agents.filter(|items| !items.is_empty()).unwrap_or_else(|| {
1019            if project.workspace_type == "linked" {
1020                vec![linked_workspace_agent_key(&project)]
1021            } else {
1022                vec!["claude_code".to_string()]
1023            }
1024        });
1025        let agent_keys = requested_agent_keys;
1026
1027        for agent_key in &agent_keys {
1028            let (skills_root, disabled_root) =
1029                resolve_agent_skills_roots(&store, &project, agent_key)
1030                    .ok_or_else(|| AppError::not_found(format!("Unknown agent: {}", agent_key)))?;
1031            let target_dir = skills_root.join(&dir_name);
1032
1033            if target_dir.strip_prefix(&skills_root).is_err() {
1034                return Err(AppError::invalid_input("Invalid skill directory path"));
1035            }
1036
1037            if target_dir.exists()
1038                || disabled_root
1039                    .as_ref()
1040                    .map(|path| path.join(&dir_name).exists())
1041                    .unwrap_or(false)
1042            {
1043                return Err(AppError::invalid_input(format!(
1044                    "Skill \"{}\" already exists in this workspace for agent {}",
1045                    skill.name, agent_key
1046                )));
1047            }
1048        }
1049
1050        let preference = crate::core::deployment_preferences::Preference::load(
1051            &store,
1052            crate::core::deployment_preferences::Scope::Linked,
1053        )?;
1054        // Two agents can resolve to the same project skills root, in which case
1055        // the second pass would find the directory the first just wrote and
1056        // refuse it. The artifact is already correct, so skip instead.
1057        let mut written: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();
1058        for agent_key in &agent_keys {
1059            let (skills_root, _) = resolve_agent_skills_roots(&store, &project, agent_key)
1060                .ok_or_else(|| AppError::not_found(format!("Unknown agent: {}", agent_key)))?;
1061            let target_dir = skills_root.join(&dir_name);
1062            if !written.insert(target_dir.clone()) {
1063                continue;
1064            }
1065            std::fs::create_dir_all(&skills_root)?;
1066            let mode = preference.for_install(copy);
1067            // NoClobber: the loop above already refused every pre-existing
1068            // target, so nothing here should need replacing. Belt and braces —
1069            // `exists()` misses dangling links and is racy against this write.
1070            sync_engine::sync_skill(
1071                &source,
1072                &target_dir,
1073                mode,
1074                sync_engine::ReplacePolicy::NoClobber,
1075            )
1076            .map_err(AppError::io)?;
1077        }
1078
1079        Ok(())
1080    })
1081    .await?
1082}
1083
1084#[tauri::command]
1085pub async fn toggle_project_skill(
1086    store: State<'_, Arc<SkillStore>>,
1087    project_id: String,
1088    skill_relative_path: String,
1089    agent: String,
1090    enabled: bool,
1091) -> Result<(), AppError> {
1092    let store = store.inner().clone();
1093    tauri::async_runtime::spawn_blocking(move || {
1094        ensure_safe_skill_relative_path(&skill_relative_path)?;
1095
1096        let record = store
1097            .get_project_by_id(&project_id)
1098            .map_err(AppError::db)?
1099            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
1100
1101        if record.workspace_type != "linked"
1102            && crate::core::project_library::is_managed(
1103                Path::new(&record.path),
1104                &skill_relative_path,
1105            )?
1106        {
1107            let shared =
1108                resolve_agent_skills_roots(&store, &record, &agent).is_some_and(|(root, _)| {
1109                    root == Path::new(&record.path)
1110                        .join(crate::core::project_library::SKILLS_DIRECTORY)
1111                });
1112            if shared {
1113                crate::core::project_library::set_enabled(
1114                    Path::new(&record.path),
1115                    &skill_relative_path,
1116                    enabled,
1117                )?;
1118                return Ok(());
1119            }
1120            crate::core::project_library::set_target_enabled(
1121                Path::new(&record.path),
1122                &skill_relative_path,
1123                &agent,
1124                enabled,
1125            )?;
1126            return Ok(());
1127        }
1128
1129        let (skills_dir, disabled_dir) = resolve_agent_skills_roots(&store, &record, &agent)
1130            .ok_or_else(|| AppError::not_found(format!("Unknown agent: {}", agent)))?;
1131        let disabled_dir = disabled_dir.ok_or_else(|| {
1132            AppError::invalid_input("This workspace does not support disabling skills")
1133        })?;
1134
1135        set_project_skill_enabled_state(&skills_dir, &disabled_dir, &skill_relative_path, enabled)
1136    })
1137    .await?
1138}
1139
1140#[tauri::command]
1141pub async fn delete_project_skill(
1142    store: State<'_, Arc<SkillStore>>,
1143    project_id: String,
1144    skill_relative_path: String,
1145    agent: String,
1146) -> Result<(), AppError> {
1147    let store = store.inner().clone();
1148    tauri::async_runtime::spawn_blocking(move || {
1149        ensure_safe_skill_relative_path(&skill_relative_path)?;
1150
1151        let record = store
1152            .get_project_by_id(&project_id)
1153            .map_err(AppError::db)?
1154            .ok_or_else(|| AppError::not_found("Workspace not found"))?;
1155
1156        if record.workspace_type != "linked"
1157            && crate::core::project_library::is_managed(
1158                Path::new(&record.path),
1159                &skill_relative_path,
1160            )?
1161        {
1162            let shared = resolve_agent_skills_roots(&store, &record, &agent)
1163                .is_some_and(|(root, _)| root == Path::new(&record.path).join(crate::core::project_library::SKILLS_DIRECTORY));
1164            if shared {
1165                return Err(AppError::invalid_input("Shared project content is visible to multiple Agents. Use project Skill deletion or shared project disable instead."));
1166            }
1167            let adapter = tool_adapters::find_adapter_with_store(&store, &agent)
1168                .ok_or_else(|| AppError::not_found(format!("Unknown agent: {agent}")))?;
1169            crate::core::project_library::remove_target_with_adapter(
1170                Path::new(&record.path),
1171                &skill_relative_path,
1172                &adapter,
1173            )?;
1174            return Ok(());
1175        }
1176
1177        let (skills_root, disabled_root) = resolve_agent_skills_roots(&store, &record, &agent)
1178            .ok_or_else(|| AppError::not_found(format!("Unknown agent: {}", agent)))?;
1179        let skills_dir = skills_root.join(&skill_relative_path);
1180        let disabled_dir = disabled_root
1181            .as_ref()
1182            .map(|root| root.join(&skill_relative_path));
1183
1184        let (target, target_root) = if skills_dir.is_dir() {
1185            (skills_dir, skills_root)
1186        } else if let Some(disabled_dir) = disabled_dir.filter(|path| path.is_dir()) {
1187            (
1188                disabled_dir,
1189                disabled_root.expect("present when disabled_dir exists"),
1190            )
1191        } else {
1192            return Ok(());
1193        };
1194
1195        ensure_dir_within_root(&target, &target_root)?;
1196        remove_workspace_skill_target(&target)?;
1197        Ok(())
1198    })
1199    .await?
1200}
1201
1202#[cfg(test)]
1203mod tests;