Skip to main content

agent_hub_runtime/commands/
skills.rs

1use super::skills_update_policy::{
2    display_update_status, local_source_is_discarded, local_source_status, preserve_newer_library,
3};
4use serde::Serialize;
5use std::collections::{HashMap, HashSet};
6use std::path::{Path, PathBuf};
7use std::sync::atomic::AtomicBool;
8use std::sync::{Arc, Mutex};
9use std::time::Instant;
10use tauri::State;
11use walkdir::WalkDir;
12pub(crate) mod catalog_install;
13pub(crate) mod repository_install;
14pub use catalog_install::install_catalog_skill;
15
16use crate::core::{
17    audit_log::AuditDraft,
18    central_repo,
19    error::AppError,
20    git_fetcher,
21    install_cancel::InstallCancelRegistry,
22    installer, path_guard,
23    repo_lock::RepoLock,
24    scanner,
25    skill_metadata::{self, is_valid_skill_dir},
26    skill_store::{SkillRecord, SkillStore, SkillTargetRecord},
27    sync_engine, sync_metadata,
28    timing::should_log_first_or_slow,
29};
30
31#[derive(Debug, Serialize)]
32pub struct UpdateSkillResult {
33    pub skill: ManagedSkillDto,
34    /// Whether the skill's file content actually changed.
35    /// False when a monorepo commit didn't touch this skill's subdirectory.
36    pub content_changed: bool,
37    /// What the update would remove, when it declined because of it (#256).
38    /// Non-empty means **nothing was changed**: show these and call again with
39    /// `approved_removals` set to `removal_approval` if the user accepts.
40    ///
41    /// Empty on every ordinary update, including approved ones.
42    pub pending_removals: Vec<PendingRemoval>,
43    /// Identifies exactly what `pending_removals` describes. Passing it back
44    /// approves *that* list against *that* revision and nothing else — if the
45    /// remote moves on, or the skill writes another file while the dialog is
46    /// open, the approval no longer matches and the user is asked again.
47    pub removal_approval: Option<String>,
48}
49
50/// Stands in for a revision when binding a re-import's approval: there is no
51/// remote to move on, but the removal set still has to be bound.
52const REIMPORT_APPROVAL_DOMAIN: &str = "reimport";
53
54/// Result of re-importing a local skill from its source path.
55#[derive(Debug, Serialize)]
56pub struct ReimportSkillResult {
57    pub skill: ManagedSkillDto,
58    /// Non-empty means **nothing was changed** — see [`UpdateSkillResult`].
59    pub pending_removals: Vec<PendingRemoval>,
60    /// Approves exactly `pending_removals` — see [`UpdateSkillResult`].
61    pub removal_approval: Option<String>,
62}
63
64/// Where a path about to be removed lives.
65#[derive(Debug, Clone, Serialize)]
66pub struct PendingRemoval {
67    /// [`LIBRARY_LOCATION`], or the key of the agent whose deployed copy holds
68    /// it. The user needs to know which directory to go and rescue.
69    pub location: String,
70    pub path: String,
71}
72
73/// `PendingRemoval::location` for the central library, as opposed to an agent's
74/// deployed copy.
75pub const LIBRARY_LOCATION: &str = "library";
76
77enum UpdateOutcome {
78    Applied {
79        content_changed: bool,
80    },
81    /// Declined, having changed nothing.
82    Held {
83        pending: Vec<PendingRemoval>,
84        approval: String,
85    },
86}
87
88/// Everything a replacement would take away — from the library and from every
89/// copy-mode deployment of this skill.
90///
91/// `staged` is the tree about to be installed, or `None` when the library keeps
92/// what it already has. Even then the deployments are torn down and rebuilt from
93/// it, which loses files just as effectively, so they are always checked.
94///
95/// Compared against the *staged* tree rather than the source it came from: the
96/// installer drops `.git` and every symlink, so anything else would report a
97/// path as surviving that the swap goes on to remove.
98pub(crate) fn pending_removals_for(
99    store: &SkillStore,
100    skill: &SkillRecord,
101    staged: Option<&Path>,
102) -> Result<Vec<PendingRemoval>, AppError> {
103    let library = Path::new(&skill.central_path);
104    let mut pending = Vec::new();
105
106    if let Some(staged) = staged {
107        for path in crate::core::removals::removed_paths(library, staged).map_err(AppError::io)? {
108            pending.push(PendingRemoval {
109                location: LIBRARY_LOCATION.to_string(),
110                path,
111            });
112        }
113    }
114
115    let effective_new = staged.unwrap_or(library);
116    for target in store
117        .get_targets_for_skill(&skill.id)
118        .map_err(AppError::db)?
119    {
120        if target.mode != "copy" {
121            continue;
122        }
123        for path in
124            crate::core::removals::removed_paths(Path::new(&target.target_path), effective_new)
125                .map_err(AppError::io)?
126        {
127            pending.push(PendingRemoval {
128                location: target.tool.clone(),
129                path,
130            });
131        }
132    }
133    Ok(pending)
134}
135
136/// A stable name for one exact set of removals at one exact revision.
137fn removal_approval_token(revision: &str, pending: &[PendingRemoval]) -> String {
138    use sha2::{Digest, Sha256};
139    let mut hasher = Sha256::new();
140    hasher.update(revision.as_bytes());
141    let mut rows: Vec<String> = pending
142        .iter()
143        .map(|p| format!("{}\u{0}{}", p.location, p.path))
144        .collect();
145    rows.sort();
146    for row in rows {
147        hasher.update(row.as_bytes());
148        hasher.update([0]);
149    }
150    hex::encode(hasher.finalize())
151}
152
153/// Removes a staged directory unless the swap claimed it.
154struct StagedPathGuard<'a> {
155    path: &'a Path,
156    armed: std::cell::Cell<bool>,
157}
158
159impl<'a> StagedPathGuard<'a> {
160    fn new(path: &'a Path, armed: bool) -> Self {
161        Self {
162            path,
163            armed: std::cell::Cell::new(armed),
164        }
165    }
166
167    /// The swap has taken ownership of it; there is nothing left to clean.
168    fn release(&self) {
169        self.armed.set(false);
170    }
171}
172
173impl Drop for StagedPathGuard<'_> {
174    fn drop(&mut self) {
175        if self.armed.get() {
176            // Declining an update must leave nothing behind — a stray
177            // `.name.staged-<uuid>` inside the library is picked up by the
178            // metadata rebuild scan as a skill of its own.
179            let _ = remove_path_if_exists(self.path);
180        }
181    }
182}
183
184#[derive(Debug, Serialize)]
185pub struct BatchUpdateSkillsResult {
186    pub refreshed: usize,
187    pub unchanged: usize,
188    pub failed: Vec<String>,
189    /// Skills left alone because updating would have removed files the new
190    /// version does not have. Named so the user can go and look, rather than
191    /// wondering why the badge did not clear.
192    pub held_back: Vec<String>,
193}
194
195#[derive(Debug, Serialize)]
196pub struct BatchDeleteSkillsResult {
197    pub deleted: usize,
198    pub failed: Vec<String>,
199}
200
201#[derive(Debug, Serialize)]
202pub struct ManagedSkillDto {
203    pub id: String,
204    pub name: String,
205    pub description: Option<String>,
206    pub version: Option<String>,
207    pub source_type: String,
208    pub source_ref: Option<String>,
209    pub source_ref_resolved: Option<String>,
210    pub source_subpath: Option<String>,
211    pub source_branch: Option<String>,
212    pub source_revision: Option<String>,
213    pub source_agent: Option<String>,
214    pub remote_revision: Option<String>,
215    pub update_status: String,
216    pub last_checked_at: Option<i64>,
217    pub last_check_error: Option<String>,
218    pub central_path: String,
219    pub enabled: bool,
220    pub created_at: i64,
221    pub updated_at: i64,
222    pub status: String,
223    pub targets: Vec<TargetDto>,
224    pub skill_group_ids: Vec<String>,
225    pub tags: Vec<String>,
226}
227
228#[derive(Debug, Serialize)]
229pub struct TargetDto {
230    pub id: String,
231    pub skill_id: String,
232    pub tool: String,
233    pub target_path: String,
234    pub mode: String,
235    pub status: String,
236    pub synced_at: Option<i64>,
237}
238
239#[derive(Debug, Serialize)]
240pub struct SkillDocumentDto {
241    pub skill_id: String,
242    pub filename: String,
243    pub content: String,
244    pub central_path: String,
245}
246
247#[derive(Debug, Serialize)]
248pub struct SourceSkillDocumentDto {
249    pub skill_id: String,
250    pub filename: String,
251    pub content: String,
252    pub source_label: String,
253    pub revision: String,
254}
255
256pub use super::skills_diff_metadata::{SkillSourceDiffDto, SkillSourceDiffEntryDto};
257
258#[derive(Debug, Serialize)]
259pub struct SkillFileEntryDto {
260    pub relative_path: String,
261    pub size: u64,
262    pub is_text: bool,
263}
264
265#[derive(Debug, Serialize)]
266pub struct SkillFileContentDto {
267    pub skill_id: String,
268    pub relative_path: String,
269    /// "text" | "binary" | "too_large"
270    pub content_kind: String,
271    pub content: Option<String>,
272}
273
274#[derive(Debug, Clone)]
275pub struct InstallSourceMetadata {
276    pub source_type: String,
277    pub source_ref: Option<String>,
278    pub source_ref_resolved: Option<String>,
279    pub source_subpath: Option<String>,
280    pub source_branch: Option<String>,
281    pub source_revision: Option<String>,
282    pub source_agent: Option<String>,
283    pub remote_revision: Option<String>,
284    pub update_status: String,
285}
286
287#[derive(Debug, Clone)]
288pub struct GitSkillSource {
289    pub clone_url: String,
290    pub branch: Option<String>,
291    pub subpath: Option<String>,
292    pub locator_skill_id: Option<String>,
293}
294
295pub use crate::core::git_catalog::{skill_rel_key, GitSkillPreview};
296
297#[derive(Debug, serde::Serialize)]
298pub struct GitPreviewResult {
299    pub temp_dir: String,
300    pub skills: Vec<GitSkillPreview>,
301}
302
303#[derive(Debug, serde::Deserialize)]
304pub struct SkillInstallItem {
305    pub rel_path: String,
306    pub name: String,
307    #[serde(default)]
308    pub overwrite_skill_id: Option<String>,
309}
310
311struct CancelRegistrationGuard {
312    registry: Arc<InstallCancelRegistry>,
313    key: String,
314}
315
316impl CancelRegistrationGuard {
317    fn new(registry: Arc<InstallCancelRegistry>, key: String) -> Self {
318        Self { registry, key }
319    }
320}
321
322impl Drop for CancelRegistrationGuard {
323    fn drop(&mut self) {
324        self.registry.remove(&self.key);
325    }
326}
327
328static GET_MANAGED_SKILLS_FIRST_CALL: AtomicBool = AtomicBool::new(true);
329
330#[tauri::command]
331pub async fn get_managed_skills(
332    store: State<'_, Arc<SkillStore>>,
333) -> Result<Vec<ManagedSkillDto>, AppError> {
334    let store = store.inner().clone();
335    tauri::async_runtime::spawn_blocking(move || {
336        let start = Instant::now();
337        let skills = store.get_all_skills().map_err(AppError::db)?;
338        let all_targets = store.get_all_targets().map_err(AppError::db)?;
339        let tags_map = store.get_tags_map().map_err(AppError::db)?;
340        let count = skills.len();
341        let dtos: Vec<ManagedSkillDto> = skills
342            .into_iter()
343            .map(|skill| managed_skill_to_dto(&store, skill, &all_targets, &tags_map))
344            .collect();
345        let elapsed_ms = start.elapsed().as_millis();
346        if should_log_first_or_slow(&GET_MANAGED_SKILLS_FIRST_CALL, elapsed_ms, 100) {
347            log::info!("get_managed_skills: {count} skills in {elapsed_ms} ms");
348        }
349        Ok(dtos)
350    })
351    .await?
352}
353
354#[tauri::command]
355pub async fn get_skills_for_skill_group(
356    skill_group_id: String,
357    store: State<'_, Arc<SkillStore>>,
358) -> Result<Vec<ManagedSkillDto>, AppError> {
359    let store = store.inner().clone();
360    tauri::async_runtime::spawn_blocking(move || {
361        let skills = store
362            .get_skills_for_scenario(&skill_group_id)
363            .map_err(AppError::db)?;
364        let all_targets = store.get_all_targets().map_err(AppError::db)?;
365        let tags_map = store.get_tags_map().map_err(AppError::db)?;
366
367        Ok(skills
368            .into_iter()
369            .map(|skill| managed_skill_to_dto(&store, skill, &all_targets, &tags_map))
370            .collect())
371    })
372    .await?
373}
374
375#[tauri::command]
376pub async fn get_skill_document(
377    skill_id: String,
378    store: State<'_, Arc<SkillStore>>,
379) -> Result<SkillDocumentDto, AppError> {
380    let store = store.inner().clone();
381    tauri::async_runtime::spawn_blocking(move || {
382        let skill = store
383            .get_skill_by_id(&skill_id)
384            .map_err(AppError::db)?
385            .ok_or_else(|| AppError::not_found("Skill not found"))?;
386
387        let (filename, content) = read_skill_document_from_dir(Path::new(&skill.central_path))?;
388
389        Ok(SkillDocumentDto {
390            skill_id,
391            filename,
392            content,
393            central_path: skill.central_path,
394        })
395    })
396    .await?
397}
398
399#[tauri::command]
400pub async fn get_source_skill_document(
401    skill_id: String,
402    store: State<'_, Arc<SkillStore>>,
403) -> Result<SourceSkillDocumentDto, AppError> {
404    let store = store.inner().clone();
405    let proxy_url = store.proxy_url();
406    tauri::async_runtime::spawn_blocking(move || {
407        let skill = store
408            .get_skill_by_id(&skill_id)
409            .map_err(AppError::db)?
410            .ok_or_else(|| AppError::not_found("Skill not found"))?;
411
412        if matches!(skill.source_type.as_str(), "local" | "import") {
413            let source_path = skill.source_ref.as_ref().ok_or_else(|| {
414                AppError::not_found("Local skill is missing its original source path")
415            })?;
416            let source_dir = PathBuf::from(source_path);
417            if !source_dir.exists() {
418                return Err(AppError::not_found("Original source path no longer exists"));
419            }
420            let (filename, content) = read_skill_document_from_dir(&source_dir)?;
421            return Ok(SourceSkillDocumentDto {
422                skill_id,
423                filename,
424                content,
425                source_label: source_label_for_skill(&skill),
426                revision: "workspace".to_string(),
427            });
428        }
429
430        if !matches!(skill.source_type.as_str(), "git" | "skillssh") {
431            return Err(AppError::invalid_input(
432                "Skill does not support source diff preview",
433            ));
434        }
435
436        let git_source = git_source_from_skill(&skill)?;
437        git_fetcher::validate_git_url(&git_source.clone_url).map_err(AppError::git)?;
438        let remote_revision = git_fetcher::resolve_remote_revision(
439            &git_source.clone_url,
440            git_source.branch.as_deref(),
441            proxy_url.as_deref(),
442        )
443        .map_err(AppError::git)?;
444
445        let temp_dir = git_fetcher::clone_repo_ref_scoped(
446            &git_source.clone_url,
447            git_source.branch.as_deref(),
448            git_source.subpath.as_deref(),
449            None,
450            proxy_url.as_deref(),
451            None,
452        )
453        .map_err(AppError::classify_git_error)?;
454
455        let result = (|| -> Result<SourceSkillDocumentDto, AppError> {
456            git_fetcher::checkout_revision(&temp_dir, &remote_revision).map_err(AppError::git)?;
457            let skill_dir = resolve_skill_dir(
458                &temp_dir,
459                git_source.subpath.as_deref(),
460                git_source.locator_skill_id.as_deref(),
461            )?;
462            let (filename, content) = read_skill_document_from_dir(&skill_dir)?;
463
464            Ok(SourceSkillDocumentDto {
465                skill_id,
466                filename,
467                content,
468                source_label: source_label_for_skill(&skill),
469                revision: remote_revision,
470            })
471        })();
472
473        git_fetcher::cleanup_temp(&temp_dir);
474        result
475    })
476    .await?
477}
478
479/// Files larger than this are flagged but not sent to the frontend — the
480/// line diff is O(n²), so previewing a huge file would hang the UI.
481const MAX_DIFF_FILE_BYTES: usize = 256 * 1024;
482
483/// Classify a file's bytes for diffing: oversized and binary files get a
484/// summary row instead of a text body.
485fn classify_diff_bytes(bytes: Option<Vec<u8>>) -> (&'static str, Option<String>) {
486    match bytes {
487        Some(b) if b.len() > MAX_DIFF_FILE_BYTES => ("too_large", None),
488        Some(b) if b.contains(&0) => ("binary", None),
489        Some(b) => match String::from_utf8(b) {
490            Ok(text) => ("text", Some(text)),
491            Err(_) => ("binary", None),
492        },
493        None => ("binary", None),
494    }
495}
496
497/// Diff the whole content scope of two skill directories. `original_dir` is
498/// the central copy, `updated_dir` is the compared source. Uses the same
499/// file enumeration as the hash so it reports exactly what flips the badge.
500pub(super) fn build_source_diff_entries(
501    original_dir: &Path,
502    updated_dir: &Path,
503) -> Vec<SkillSourceDiffEntryDto> {
504    use crate::core::content_hash::{self, ContentEntry};
505    use std::collections::BTreeMap;
506
507    let index = |dir: &Path| -> BTreeMap<String, ContentEntry> {
508        content_hash::list_content_files(dir)
509            .into_iter()
510            .map(|e| (e.relative_path.clone(), e))
511            .collect()
512    };
513    let original = index(original_dir);
514    let updated = index(updated_dir);
515
516    let mut keys: Vec<&String> = original.keys().chain(updated.keys()).collect();
517    keys.sort();
518    keys.dedup();
519
520    let mut entries = Vec::new();
521    for key in keys {
522        match (original.get(key), updated.get(key)) {
523            (None, Some(u)) => {
524                let (kind, text) = classify_diff_bytes(std::fs::read(&u.path).ok());
525                entries.push(SkillSourceDiffEntryDto {
526                    relative_path: key.clone(),
527                    status: "added".into(),
528                    content_kind: kind.into(),
529                    original_text: None,
530                    updated_text: text,
531                    executable_before: false,
532                    executable_after: u.is_executable(),
533                });
534            }
535            (Some(o), None) => {
536                let (kind, text) = classify_diff_bytes(std::fs::read(&o.path).ok());
537                entries.push(SkillSourceDiffEntryDto {
538                    relative_path: key.clone(),
539                    status: "removed".into(),
540                    content_kind: kind.into(),
541                    original_text: text,
542                    updated_text: None,
543                    executable_before: o.is_executable(),
544                    executable_after: false,
545                });
546            }
547            (Some(o), Some(u)) => {
548                let o_bytes = std::fs::read(&o.path).ok();
549                let u_bytes = std::fs::read(&u.path).ok();
550                let exec_before = o.is_executable();
551                let exec_after = u.is_executable();
552                let bytes_equal = o_bytes.is_some() && o_bytes == u_bytes;
553
554                if bytes_equal {
555                    if exec_before == exec_after {
556                        continue; // unchanged — must match the hash's verdict
557                    }
558                    entries.push(SkillSourceDiffEntryDto {
559                        relative_path: key.clone(),
560                        status: "modified".into(),
561                        content_kind: "permission_only".into(),
562                        original_text: None,
563                        updated_text: None,
564                        executable_before: exec_before,
565                        executable_after: exec_after,
566                    });
567                    continue;
568                }
569
570                let (o_kind, o_text) = classify_diff_bytes(o_bytes);
571                let (u_kind, u_text) = classify_diff_bytes(u_bytes);
572                let (kind, original_text, updated_text) = if o_kind == "text" && u_kind == "text" {
573                    ("text", o_text, u_text)
574                } else if o_kind == "too_large" || u_kind == "too_large" {
575                    ("too_large", None, None)
576                } else {
577                    ("binary", None, None)
578                };
579                entries.push(SkillSourceDiffEntryDto {
580                    relative_path: key.clone(),
581                    status: "modified".into(),
582                    content_kind: kind.into(),
583                    original_text,
584                    updated_text,
585                    executable_before: exec_before,
586                    executable_after: exec_after,
587                });
588            }
589            (None, None) => {}
590        }
591    }
592
593    entries
594}
595
596#[tauri::command]
597pub async fn get_skill_source_diff(
598    skill_id: String,
599    store: State<'_, Arc<SkillStore>>,
600) -> Result<SkillSourceDiffDto, AppError> {
601    let store = store.inner().clone();
602    let proxy_url = store.proxy_url();
603    tauri::async_runtime::spawn_blocking(move || {
604        let skill = store
605            .get_skill_by_id(&skill_id)
606            .map_err(AppError::db)?
607            .ok_or_else(|| AppError::not_found("Skill not found"))?;
608
609        let central_dir = PathBuf::from(&skill.central_path);
610        let source_label = source_label_for_skill(&skill);
611
612        if matches!(skill.source_type.as_str(), "local" | "import") {
613            let source_path = skill.source_ref.as_ref().ok_or_else(|| {
614                AppError::not_found("Local skill is missing its original source path")
615            })?;
616            let source_dir = PathBuf::from(source_path);
617            if !source_dir.exists() {
618                return Err(AppError::not_found("Original source path no longer exists"));
619            }
620            let entries = build_source_diff_entries(&central_dir, &source_dir);
621            return Ok(SkillSourceDiffDto::from_directories(
622                skill_id,
623                source_label,
624                "workspace".to_string(),
625                &central_dir,
626                &source_dir,
627                source_path.clone(),
628                entries,
629            ));
630        }
631
632        if !matches!(skill.source_type.as_str(), "git" | "skillssh") {
633            return Err(AppError::invalid_input(
634                "Skill does not support source diff preview",
635            ));
636        }
637
638        let git_source = git_source_from_skill(&skill)?;
639        git_fetcher::validate_git_url(&git_source.clone_url).map_err(AppError::git)?;
640        let remote_revision = git_fetcher::resolve_remote_revision(
641            &git_source.clone_url,
642            git_source.branch.as_deref(),
643            proxy_url.as_deref(),
644        )
645        .map_err(AppError::git)?;
646
647        let temp_dir = git_fetcher::clone_repo_ref_scoped(
648            &git_source.clone_url,
649            git_source.branch.as_deref(),
650            git_source.subpath.as_deref(),
651            None,
652            proxy_url.as_deref(),
653            None,
654        )
655        .map_err(AppError::classify_git_error)?;
656
657        let result = (|| -> Result<SkillSourceDiffDto, AppError> {
658            git_fetcher::checkout_revision(&temp_dir, &remote_revision).map_err(AppError::git)?;
659            let skill_dir = resolve_skill_dir(
660                &temp_dir,
661                git_source.subpath.as_deref(),
662                git_source.locator_skill_id.as_deref(),
663            )?;
664            let entries = build_source_diff_entries(&central_dir, &skill_dir);
665            let relative_dir = skill_dir.strip_prefix(&temp_dir).map_err(|_| {
666                AppError::invalid_input("Resolved skill directory is outside source checkout")
667            })?;
668            let directory = if relative_dir.as_os_str().is_empty() {
669                ".".to_string()
670            } else {
671                relative_dir.to_string_lossy().into_owned()
672            };
673            let source_path = format!(
674                "{} :: {}",
675                crate::core::log_sanitize::sanitize(&git_source.clone_url),
676                directory
677            );
678            Ok(SkillSourceDiffDto::from_directories(
679                skill_id,
680                source_label,
681                remote_revision,
682                &central_dir,
683                &skill_dir,
684                source_path,
685                entries,
686            ))
687        })();
688
689        git_fetcher::cleanup_temp(&temp_dir);
690        result
691    })
692    .await?
693}
694
695fn read_skill_document_from_dir(dir: &Path) -> Result<(String, String), AppError> {
696    let candidates = [
697        "SKILL.md",
698        "skill.md",
699        "CLAUDE.md",
700        "claude.md",
701        "README.md",
702        "readme.md",
703    ];
704
705    for name in &candidates {
706        let path = dir.join(name);
707        if path.exists() {
708            let content = std::fs::read_to_string(&path)?;
709            return Ok((name.to_string(), content));
710        }
711    }
712
713    for e in WalkDir::new(dir).max_depth(4).into_iter().flatten() {
714        let fname = e.file_name().to_string_lossy();
715        if candidates.contains(&fname.as_ref()) {
716            let content = std::fs::read_to_string(e.path())?;
717            return Ok((fname.to_string(), content));
718        }
719    }
720
721    Err(AppError::not_found("No documentation file found"))
722}
723
724const MAX_DISPLAY_FILE_BYTES: usize = 512 * 1024;
725
726const TEXT_PROBE_BYTES: usize = 8192;
727
728fn probe_is_text(path: &Path) -> bool {
729    let Ok(file) = std::fs::File::open(path) else {
730        return false;
731    };
732    use std::io::Read;
733    let mut buf = vec![0u8; TEXT_PROBE_BYTES];
734    let n = match file.take(TEXT_PROBE_BYTES as u64).read(&mut buf) {
735        Ok(n) => n,
736        Err(_) => return false,
737    };
738    !buf[..n].contains(&0) && std::str::from_utf8(&buf[..n]).is_ok()
739}
740
741#[tauri::command]
742pub async fn get_skill_files(
743    skill_id: String,
744    store: State<'_, Arc<SkillStore>>,
745) -> Result<Vec<SkillFileEntryDto>, AppError> {
746    let store = store.inner().clone();
747    tauri::async_runtime::spawn_blocking(move || {
748        let skill = store
749            .get_skill_by_id(&skill_id)
750            .map_err(AppError::db)?
751            .ok_or_else(|| AppError::not_found("Skill not found"))?;
752
753        let entries = crate::core::content_hash::list_content_files(Path::new(&skill.central_path));
754        let result = entries
755            .into_iter()
756            .map(|entry| {
757                let size = std::fs::metadata(&entry.path).map(|m| m.len()).unwrap_or(0);
758                let is_text = probe_is_text(&entry.path);
759                SkillFileEntryDto {
760                    relative_path: entry.relative_path,
761                    size,
762                    is_text,
763                }
764            })
765            .collect();
766        Ok(result)
767    })
768    .await?
769}
770
771#[tauri::command]
772pub async fn read_skill_file(
773    skill_id: String,
774    relative_path: String,
775    store: State<'_, Arc<SkillStore>>,
776) -> Result<SkillFileContentDto, AppError> {
777    let store = store.inner().clone();
778    tauri::async_runtime::spawn_blocking(move || {
779        let skill = store
780            .get_skill_by_id(&skill_id)
781            .map_err(AppError::db)?
782            .ok_or_else(|| AppError::not_found("Skill not found"))?;
783
784        // Path-traversal guard: ensure relative_path contains only normal components
785        for component in Path::new(&relative_path).components() {
786            if !matches!(component, std::path::Component::Normal(_)) {
787                return Err(AppError::invalid_input("Invalid file path"));
788            }
789        }
790
791        let central = Path::new(&skill.central_path);
792        let resolved = central.join(&relative_path);
793
794        if !path_guard::is_path_safe(central, &resolved) {
795            return Err(AppError::invalid_input("Invalid file path"));
796        }
797
798        let bytes = std::fs::read(&resolved)?;
799        if bytes.len() > MAX_DISPLAY_FILE_BYTES {
800            return Ok(SkillFileContentDto {
801                skill_id,
802                relative_path,
803                content_kind: "too_large".into(),
804                content: None,
805            });
806        }
807        if bytes.contains(&0) {
808            return Ok(SkillFileContentDto {
809                skill_id,
810                relative_path,
811                content_kind: "binary".into(),
812                content: None,
813            });
814        }
815        match String::from_utf8(bytes) {
816            Ok(text) => Ok(SkillFileContentDto {
817                skill_id,
818                relative_path,
819                content_kind: "text".into(),
820                content: Some(text),
821            }),
822            Err(_) => Ok(SkillFileContentDto {
823                skill_id,
824                relative_path,
825                content_kind: "binary".into(),
826                content: None,
827            }),
828        }
829    })
830    .await?
831}
832
833fn source_label_for_skill(skill: &SkillRecord) -> String {
834    match skill.source_type.as_str() {
835        "skillssh" => "skills.sh".to_string(),
836        "git" => "Git".to_string(),
837        "local" => "Local".to_string(),
838        "import" => "Imported".to_string(),
839        other => other.to_string(),
840    }
841}
842
843#[tauri::command]
844pub async fn delete_managed_skill(
845    skill_id: String,
846    store: State<'_, Arc<SkillStore>>,
847) -> Result<(), AppError> {
848    let store = store.inner().clone();
849    tauri::async_runtime::spawn_blocking(move || {
850        let result = delete_managed_skills_by_ids(&store, std::slice::from_ref(&skill_id))?;
851        if result.deleted == 0 {
852            return Err(AppError::not_found("Skill not found"));
853        }
854        Ok(())
855    })
856    .await?
857}
858
859#[tauri::command]
860pub async fn delete_managed_skills(
861    skill_ids: Vec<String>,
862    store: State<'_, Arc<SkillStore>>,
863) -> Result<BatchDeleteSkillsResult, AppError> {
864    let store = store.inner().clone();
865    tauri::async_runtime::spawn_blocking(move || delete_managed_skills_by_ids(&store, &skill_ids))
866        .await?
867}
868
869pub fn delete_managed_skills_by_ids(
870    store: &SkillStore,
871    skill_ids: &[String],
872) -> Result<BatchDeleteSkillsResult, AppError> {
873    sync_metadata::with_repo_lock("delete skills", || {
874        let mut deleted = 0;
875        let mut failed = Vec::new();
876
877        for skill_id in skill_ids {
878            let Some(skill) = store.get_skill_by_id(skill_id)? else {
879                store.log_audit(
880                    AuditDraft::new("remove")
881                        .skill(skill_id.clone(), "")
882                        .fail("not found"),
883                );
884                failed.push(skill_id.clone());
885                continue;
886            };
887
888            let targets = store.get_targets_for_skill(skill_id)?;
889            for target in &targets {
890                sync_engine::remove_recorded_target_or_warn(
891                    &PathBuf::from(&target.target_path),
892                    &target.mode,
893                );
894            }
895
896            let central = PathBuf::from(&skill.central_path);
897            if central.exists() {
898                std::fs::remove_dir_all(&central).ok();
899            }
900
901            store.delete_skill(skill_id)?;
902            store.log_audit(
903                AuditDraft::new("remove")
904                    .skill(skill_id.clone(), skill.name.clone())
905                    .ok(),
906            );
907            deleted += 1;
908        }
909
910        if deleted > 0 {
911            sync_metadata::write_all_from_db_unlocked(store)?;
912        }
913
914        Ok(BatchDeleteSkillsResult { deleted, failed })
915    })
916    .map_err(AppError::db)
917}
918
919/// Append an audit log entry summarising an install attempt.
920/// `source_label` is short text identifying the source (e.g. "local", "git", "skillssh").
921fn log_install_outcome(
922    store: &SkillStore,
923    source_label: &str,
924    outcome: Result<&(String, String), &AppError>,
925) {
926    let draft = AuditDraft::new("install").detail(source_label);
927    let draft = match outcome {
928        Ok((id, name)) => draft.skill(id.clone(), name.clone()).ok(),
929        Err(e) => draft.fail(e.to_string()),
930    };
931    store.log_audit(draft);
932}
933
934fn log_update_outcome(
935    store: &SkillStore,
936    skill_id: &str,
937    source_label: &str,
938    outcome: Result<&UpdateSkillResult, &AppError>,
939) {
940    let mut draft = AuditDraft::new("update").detail(source_label);
941    match outcome {
942        Ok(result) if !result.pending_removals.is_empty() => {
943            // Held back, not applied. Recording it as a successful "unchanged"
944            // would make the audit trail disagree with what actually happened.
945            draft = draft
946                .skill(result.skill.id.clone(), result.skill.name.clone())
947                .detail(format!(
948                    "{source_label}; held back — would remove {} path(s)",
949                    result.pending_removals.len()
950                ))
951                .ok();
952        }
953        Ok(result) => {
954            draft = draft
955                .skill(result.skill.id.clone(), result.skill.name.clone())
956                .detail(if result.content_changed {
957                    format!("{source_label}; content changed")
958                } else {
959                    format!("{source_label}; unchanged")
960                })
961                .ok();
962        }
963        Err(e) => {
964            let name = store
965                .get_skill_by_id(skill_id)
966                .ok()
967                .flatten()
968                .map(|s| s.name)
969                .unwrap_or_default();
970            draft = draft.skill(skill_id.to_string(), name).fail(e.to_string());
971        }
972    }
973    store.log_audit(draft);
974}
975
976fn log_reimport_outcome(
977    store: &SkillStore,
978    skill_id: &str,
979    outcome: Result<&ReimportSkillResult, &AppError>,
980) {
981    let mut draft = AuditDraft::new("update").detail("local");
982    match outcome {
983        Ok(result) if !result.pending_removals.is_empty() => {
984            draft = draft
985                .skill(result.skill.id.clone(), result.skill.name.clone())
986                .detail(format!(
987                    "local; held back — would remove {} path(s)",
988                    result.pending_removals.len()
989                ))
990                .ok();
991        }
992        Ok(result) => {
993            draft = draft
994                .skill(result.skill.id.clone(), result.skill.name.clone())
995                .ok();
996        }
997        Err(e) => {
998            let name = store
999                .get_skill_by_id(skill_id)
1000                .ok()
1001                .flatten()
1002                .map(|s| s.name)
1003                .unwrap_or_default();
1004            draft = draft.skill(skill_id.to_string(), name).fail(e.to_string());
1005        }
1006    }
1007    store.log_audit(draft);
1008}
1009
1010#[tauri::command]
1011pub async fn check_install_local_conflict(
1012    source_path: String,
1013    name: Option<String>,
1014    store: State<'_, Arc<SkillStore>>,
1015) -> Result<Option<String>, AppError> {
1016    let store = store.inner().clone();
1017    tauri::async_runtime::spawn_blocking(move || {
1018        let path = PathBuf::from(&source_path);
1019        let resolved =
1020            installer::resolve_local_skill_name(&path, name.as_deref()).map_err(AppError::io)?;
1021        let sanitized = skill_metadata::sanitize_skill_name(&resolved).unwrap_or(resolved);
1022        let central_path = central_repo::skills_dir().join(&sanitized);
1023        let central_str = central_path.to_string_lossy().to_string();
1024        let existing = store
1025            .get_skill_by_central_path(&central_str)
1026            .map_err(AppError::db)?;
1027        Ok(existing.map(|s| s.name))
1028    })
1029    .await?
1030}
1031
1032#[tauri::command]
1033pub async fn install_local(
1034    source_path: String,
1035    name: Option<String>,
1036    overwrite: Option<bool>,
1037    store: State<'_, Arc<SkillStore>>,
1038) -> Result<(), AppError> {
1039    let store = store.inner().clone();
1040    tauri::async_runtime::spawn_blocking(move || {
1041        let outcome = (|| -> Result<(String, String), AppError> {
1042            let path = PathBuf::from(&source_path);
1043            let metadata = InstallSourceMetadata {
1044                source_type: "local".to_string(),
1045                source_ref: Some(source_path.clone()),
1046                source_ref_resolved: None,
1047                source_subpath: None,
1048                source_branch: None,
1049                source_revision: None,
1050                source_agent: None,
1051                remote_revision: None,
1052                update_status: "local_only".to_string(),
1053            };
1054            let _lock =
1055                RepoLock::acquire_foreground("install local skill").map_err(AppError::db)?;
1056
1057            if overwrite.unwrap_or(false) {
1058                let resolved = installer::resolve_local_skill_name(&path, name.as_deref())
1059                    .map_err(AppError::io)?;
1060                let sanitized = skill_metadata::sanitize_skill_name(&resolved)
1061                    .unwrap_or_else(|| resolved.clone());
1062                let central_path = central_repo::skills_dir().join(&sanitized);
1063                let central_str = central_path.to_string_lossy().to_string();
1064                if let Some(existing) = store
1065                    .get_skill_by_central_path(&central_str)
1066                    .map_err(AppError::db)?
1067                {
1068                    store.delete_skill(&existing.id).map_err(AppError::db)?;
1069                }
1070                if central_path.exists() {
1071                    std::fs::remove_dir_all(&central_path).map_err(AppError::io)?;
1072                }
1073            }
1074
1075            let result =
1076                installer::install_from_local(&path, name.as_deref()).map_err(AppError::io)?;
1077            let skill_name = result.name.clone();
1078            // Install only adds the skill to the central library; skill_group
1079            // membership is an explicit action (see issue #213).
1080            let skill_id = store_installed_skill_unlocked(&store, &result, &metadata, None)?;
1081            Ok((skill_id, skill_name))
1082        })();
1083        log_install_outcome(&store, "local", outcome.as_ref());
1084        outcome.map(|_| ())
1085    })
1086    .await?
1087}
1088
1089#[tauri::command]
1090pub async fn install_git(
1091    repo_url: String,
1092    name: Option<String>,
1093    store: State<'_, Arc<SkillStore>>,
1094    cancel_registry: State<'_, Arc<InstallCancelRegistry>>,
1095    app_handle: tauri::AppHandle,
1096) -> Result<(), AppError> {
1097    let store = store.inner().clone();
1098    let proxy_url = store.proxy_url();
1099    let registry = cancel_registry.inner().clone();
1100    let cancel_key = repo_url.clone();
1101    let cancel = registry.register(&cancel_key);
1102    let _cancel_guard = CancelRegistrationGuard::new(registry.clone(), cancel_key);
1103
1104    tauri::async_runtime::spawn_blocking(move || {
1105        use tauri::Emitter;
1106        let emit_progress = |phase: &str| {
1107            app_handle
1108                .emit(
1109                    "install-progress",
1110                    serde_json::json!({
1111                        "skill_id": repo_url,
1112                        "phase": phase,
1113                    }),
1114                )
1115                .ok();
1116        };
1117
1118        let outcome = (|| -> Result<(String, String), AppError> {
1119            git_fetcher::validate_git_url(&repo_url).map_err(AppError::git)?;
1120            emit_progress("cloning");
1121            let parsed = git_fetcher::parse_git_source_resolved(&repo_url, proxy_url.as_deref());
1122            let app_for_progress = app_handle.clone();
1123            let url_for_progress = repo_url.clone();
1124            let progress_cb: git_fetcher::ProgressCallback = Box::new(move |msg: &str| {
1125                app_for_progress
1126                    .emit(
1127                        "install-progress",
1128                        serde_json::json!({
1129                            "skill_id": url_for_progress,
1130                            "phase": "cloning",
1131                            "detail": msg,
1132                        }),
1133                    )
1134                    .ok();
1135            });
1136            let temp_dir = git_fetcher::clone_repo_ref_scoped(
1137                &parsed.clone_url,
1138                parsed.branch.as_deref(),
1139                parsed.subpath.as_deref(),
1140                Some(&cancel),
1141                proxy_url.as_deref(),
1142                Some(progress_cb),
1143            )
1144            .map_err(AppError::classify_git_error)?;
1145
1146            emit_progress("installing");
1147            let install_result = (|| -> Result<(String, String), AppError> {
1148                let _lock =
1149                    RepoLock::acquire_foreground("install git skill").map_err(AppError::db)?;
1150                let skill_dir = resolve_skill_dir(&temp_dir, parsed.subpath.as_deref(), None)?;
1151                let revision = git_fetcher::get_head_revision(&temp_dir).map_err(AppError::git)?;
1152                let result = installer::install_from_git_dir(&skill_dir, name.as_deref())
1153                    .map_err(AppError::io)?;
1154                let metadata = InstallSourceMetadata {
1155                    source_type: "git".to_string(),
1156                    source_ref: Some(parsed.original_url.clone()),
1157                    source_ref_resolved: Some(parsed.clone_url.clone()),
1158                    source_subpath: git_fetcher::relative_subpath(&temp_dir, &skill_dir),
1159                    source_branch: parsed.branch.clone(),
1160                    source_revision: Some(revision.clone()),
1161                    source_agent: None,
1162                    remote_revision: Some(revision),
1163                    update_status: "up_to_date".to_string(),
1164                };
1165                let skill_name = result.name.clone();
1166                let skill_id = store_installed_skill_unlocked(&store, &result, &metadata, None)?;
1167                Ok((skill_id, skill_name))
1168            })();
1169
1170            git_fetcher::cleanup_temp(&temp_dir);
1171            install_result
1172        })();
1173
1174        log_install_outcome(&store, "git", outcome.as_ref());
1175        outcome?;
1176
1177        emit_progress("done");
1178        Ok(())
1179    })
1180    .await?
1181}
1182
1183#[tauri::command]
1184pub async fn check_skillssh_conflict(
1185    skill_id: String,
1186    store: State<'_, Arc<SkillStore>>,
1187) -> Result<Option<String>, AppError> {
1188    let store = store.inner().clone();
1189    tauri::async_runtime::spawn_blocking(move || {
1190        let sanitized =
1191            skill_metadata::sanitize_skill_name(&skill_id).unwrap_or_else(|| skill_id.clone());
1192        let central_path = central_repo::skills_dir().join(&sanitized);
1193        let central_str = central_path.to_string_lossy().to_string();
1194        let existing = store
1195            .get_skill_by_central_path(&central_str)
1196            .map_err(AppError::db)?;
1197        Ok(existing.map(|s| s.name))
1198    })
1199    .await?
1200}
1201
1202#[tauri::command]
1203pub async fn install_from_skillssh(
1204    source: String,
1205    skill_id: String,
1206    overwrite: Option<bool>,
1207    store: State<'_, Arc<SkillStore>>,
1208    cancel_registry: State<'_, Arc<InstallCancelRegistry>>,
1209    app_handle: tauri::AppHandle,
1210) -> Result<(), AppError> {
1211    let store = store.inner().clone();
1212    let proxy_url = store.proxy_url();
1213    let registry = cancel_registry.inner().clone();
1214    let cancel_key_owned = format!("{}/{}", source, skill_id);
1215    let cancel = registry.register(&cancel_key_owned);
1216    let _cancel_guard = CancelRegistrationGuard::new(registry.clone(), cancel_key_owned);
1217
1218    tauri::async_runtime::spawn_blocking(move || {
1219        use tauri::Emitter;
1220        let skill_key = format!("{}/{}", source, skill_id);
1221        let emit_progress = |phase: &str| {
1222            app_handle
1223                .emit(
1224                    "install-progress",
1225                    serde_json::json!({
1226                        "skill_id": skill_key,
1227                        "phase": phase,
1228                    }),
1229                )
1230                .ok();
1231        };
1232
1233        let outcome = (|| -> Result<(String, String), AppError> {
1234            emit_progress("cloning");
1235            let parts: Vec<&str> = source.split('/').collect();
1236            if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) || source.contains('.') {
1237                return Err(AppError::invalid_input(format!(
1238                    "Invalid skills.sh source '{}': expected 'owner/repo'",
1239                    source
1240                )));
1241            }
1242            let repo_url = format!("https://github.com/{}.git", source);
1243            log::info!(
1244                "[skillssh] start install: source={}, skill_id={}, overwrite={:?}, repo_url={}",
1245                source,
1246                skill_id,
1247                overwrite,
1248                repo_url
1249            );
1250            let app_for_progress = app_handle.clone();
1251            let skill_key_for_progress = skill_key.clone();
1252            let progress_cb: git_fetcher::ProgressCallback = Box::new(move |msg: &str| {
1253                app_for_progress
1254                    .emit(
1255                        "install-progress",
1256                        serde_json::json!({
1257                            "skill_id": skill_key_for_progress,
1258                            "phase": "cloning",
1259                            "detail": msg,
1260                        }),
1261                    )
1262                    .ok();
1263            });
1264            let temp_dir = git_fetcher::clone_repo_ref_with_progress(
1265                &repo_url,
1266                None,
1267                Some(&cancel),
1268                proxy_url.as_deref(),
1269                Some(progress_cb),
1270            )
1271            .map_err(|e| {
1272                log::error!(
1273                    "[skillssh] clone failed: repo_url={}, error={}",
1274                    repo_url,
1275                    e
1276                );
1277                AppError::classify_git_error(e)
1278            })?;
1279            log::info!("[skillssh] clone ok: temp_dir={}", temp_dir.display());
1280
1281            emit_progress("installing");
1282            let install_result = (|| -> Result<(String, String), AppError> {
1283                let _lock =
1284                    RepoLock::acquire_foreground("install skillssh skill").map_err(AppError::db)?;
1285                log::info!(
1286                    "[skillssh] resolving skill_dir: temp_dir={}, skill_id={}",
1287                    temp_dir.display(),
1288                    skill_id
1289                );
1290                let skill_dir =
1291                    resolve_skill_dir(&temp_dir, None, Some(&skill_id)).map_err(|e| {
1292                        log::error!("[skillssh] resolve_skill_dir failed: {}", e);
1293                        e
1294                    })?;
1295                log::info!("[skillssh] skill_dir resolved: {}", skill_dir.display());
1296
1297                if overwrite.unwrap_or(false) {
1298                    let sanitized = skill_metadata::sanitize_skill_name(&skill_id)
1299                        .unwrap_or_else(|| skill_id.clone());
1300                    let central_path = central_repo::skills_dir().join(&sanitized);
1301                    let central_str = central_path.to_string_lossy().to_string();
1302                    if let Some(existing) = store
1303                        .get_skill_by_central_path(&central_str)
1304                        .map_err(AppError::db)?
1305                    {
1306                        store.delete_skill(&existing.id).map_err(AppError::db)?;
1307                    }
1308                    if central_path.exists() {
1309                        std::fs::remove_dir_all(&central_path).map_err(AppError::io)?;
1310                    }
1311                }
1312
1313                let source_hash = installer::hash_local_source(&skill_dir).map_err(AppError::io)?;
1314                let revision = git_fetcher::get_head_revision(&temp_dir).map_err(AppError::git)?;
1315                let source_ref = format!("{}/{}", source, skill_id);
1316                log::info!(
1317                    "[skillssh] source_hash={}, revision={}, source_ref={}",
1318                    source_hash,
1319                    revision,
1320                    source_ref
1321                );
1322                let (install_name, destination) = resolve_skillssh_install_target(
1323                    &store,
1324                    &source_ref,
1325                    &skill_id,
1326                    Some(&source_hash),
1327                )?;
1328                log::info!(
1329                    "[skillssh] install target: name={}, dest={}",
1330                    install_name,
1331                    destination.display()
1332                );
1333                let result = installer::install_skill_dir_to_destination(
1334                    &skill_dir,
1335                    &install_name,
1336                    &destination,
1337                )
1338                .map_err(|e| {
1339                    log::error!("[skillssh] install_skill_dir_to_destination failed: {}", e);
1340                    AppError::io(e)
1341                })?;
1342                let metadata = InstallSourceMetadata {
1343                    source_type: "skillssh".to_string(),
1344                    source_ref: Some(source_ref),
1345                    source_ref_resolved: Some(repo_url.clone()),
1346                    source_subpath: git_fetcher::relative_subpath(&temp_dir, &skill_dir),
1347                    source_branch: None,
1348                    source_revision: Some(revision.clone()),
1349                    source_agent: None,
1350                    remote_revision: Some(revision),
1351                    update_status: "up_to_date".to_string(),
1352                };
1353                let skill_name = result.name.clone();
1354                let new_id = store_installed_skill_unlocked(&store, &result, &metadata, None)?;
1355                log::info!(
1356                    "[skillssh] install success: id={}, name={}",
1357                    new_id,
1358                    skill_name
1359                );
1360                Ok((new_id, skill_name))
1361            })();
1362
1363            git_fetcher::cleanup_temp(&temp_dir);
1364            if let Err(ref e) = install_result {
1365                log::error!("[skillssh] install_result error: {:?}", e);
1366            }
1367            install_result
1368        })();
1369
1370        log_install_outcome(&store, "skillssh", outcome.as_ref());
1371        if let Err(ref e) = outcome {
1372            log::error!("[skillssh] final outcome error: {:?}", e);
1373        }
1374        outcome?;
1375
1376        emit_progress("done");
1377        Ok(())
1378    })
1379    .await?
1380}
1381
1382/// Clone a git repo and return a preview list of skills found, without installing.
1383/// The caller must follow up with `confirm_git_install` using the returned `temp_dir`.
1384#[tauri::command]
1385pub async fn preview_git_install(
1386    repo_url: String,
1387    store: State<'_, Arc<SkillStore>>,
1388    cancel_registry: State<'_, Arc<InstallCancelRegistry>>,
1389    app_handle: tauri::AppHandle,
1390) -> Result<GitPreviewResult, AppError> {
1391    let store = store.inner().clone();
1392    let proxy_url = store.get_setting("proxy_url").ok().flatten();
1393    let registry = cancel_registry.inner().clone();
1394    let cancel_key = repo_url.clone();
1395    let cancel = registry.register(&cancel_key);
1396    let _cancel_guard = CancelRegistrationGuard::new(registry.clone(), cancel_key);
1397
1398    tauri::async_runtime::spawn_blocking(move || {
1399        use tauri::Emitter;
1400        app_handle
1401            .emit(
1402                "install-progress",
1403                serde_json::json!({
1404                    "skill_id": repo_url,
1405                    "phase": "cloning",
1406                }),
1407            )
1408            .ok();
1409
1410        let parsed = git_fetcher::parse_git_source_resolved(&repo_url, proxy_url.as_deref());
1411        let app_for_progress = app_handle.clone();
1412        let url_for_progress = repo_url.clone();
1413        let progress_cb: git_fetcher::ProgressCallback = Box::new(move |msg: &str| {
1414            app_for_progress
1415                .emit(
1416                    "install-progress",
1417                    serde_json::json!({
1418                        "skill_id": url_for_progress,
1419                        "phase": "cloning",
1420                        "detail": msg,
1421                    }),
1422                )
1423                .ok();
1424        });
1425        let temp_dir = git_fetcher::clone_repo_ref_scoped(
1426            &parsed.clone_url,
1427            parsed.branch.as_deref(),
1428            parsed.subpath.as_deref(),
1429            Some(&cancel),
1430            proxy_url.as_deref(),
1431            Some(progress_cb),
1432        )
1433        .map_err(AppError::classify_git_error)?;
1434
1435        let build_preview = || -> Result<GitPreviewResult, AppError> {
1436            let skill_dir = resolve_skill_dir(&temp_dir, parsed.subpath.as_deref(), None)?;
1437            let dirs = collect_git_skill_dirs(&skill_dir);
1438
1439            let skills: Vec<GitSkillPreview> = dirs
1440                .iter()
1441                .map(|dir| crate::core::git_catalog::preview_skill(&temp_dir, &skill_dir, dir))
1442                .collect();
1443
1444            Ok(GitPreviewResult {
1445                temp_dir: temp_dir.to_string_lossy().to_string(),
1446                skills,
1447            })
1448        };
1449
1450        build_preview().inspect_err(|_e| {
1451            git_fetcher::cleanup_temp(&temp_dir);
1452        })
1453    })
1454    .await?
1455}
1456
1457/// Install selected skills from a previously cloned temp directory.
1458#[tauri::command]
1459pub async fn confirm_git_install(
1460    repo_url: String,
1461    temp_dir: String,
1462    items: Vec<SkillInstallItem>,
1463    store: State<'_, Arc<SkillStore>>,
1464) -> Result<(), AppError> {
1465    let store = store.inner().clone();
1466    let proxy_url = store.proxy_url();
1467    tauri::async_runtime::spawn_blocking(move || {
1468        let temp_path = validate_clone_temp_path(&temp_dir)?;
1469
1470        let result: Result<(), AppError> = (|| {
1471            if items.is_empty() {
1472                return Ok(());
1473            }
1474            repository_install::validate_overwrite_targets(&items)?;
1475
1476            let parsed = git_fetcher::parse_git_source_resolved(&repo_url, proxy_url.as_deref());
1477            let skill_dir = resolve_skill_dir(&temp_path, parsed.subpath.as_deref(), None)?;
1478            let all_dirs = collect_git_skill_dirs(&skill_dir);
1479            let revision = git_fetcher::get_head_revision(&temp_path).map_err(AppError::git)?;
1480            let _lock =
1481                RepoLock::acquire_foreground("confirm git install").map_err(AppError::db)?;
1482
1483            for dir in &all_dirs {
1484                let rel_key = skill_rel_key(&skill_dir, dir);
1485                let item = match items.iter().find(|i| i.rel_path == rel_key) {
1486                    Some(i) => i,
1487                    None => continue,
1488                };
1489                let custom_name = item.name.trim();
1490                let install_name = if custom_name.is_empty() {
1491                    None
1492                } else {
1493                    Some(custom_name)
1494                };
1495                let subpath = git_fetcher::relative_subpath(&temp_path, dir);
1496                let metadata = InstallSourceMetadata {
1497                    source_type: "git".to_string(),
1498                    source_ref: Some(repo_url.clone()),
1499                    source_ref_resolved: Some(parsed.clone_url.clone()),
1500                    source_subpath: subpath,
1501                    source_branch: parsed.branch.clone(),
1502                    source_revision: Some(revision.clone()),
1503                    source_agent: None,
1504                    remote_revision: Some(revision.clone()),
1505                    update_status: "up_to_date".to_string(),
1506                };
1507                if let Some(skill_id) = item.overwrite_skill_id.as_deref() {
1508                    repository_install::overwrite_skill_unlocked(&store, skill_id, dir, &metadata)?;
1509                } else {
1510                    let result =
1511                        installer::install_from_git_dir(dir, install_name).map_err(AppError::io)?;
1512                    store_installed_skill_unlocked(&store, &result, &metadata, None)?;
1513                }
1514            }
1515            Ok(())
1516        })();
1517
1518        // Always clean up temp directory, regardless of success or failure.
1519        git_fetcher::cleanup_temp(&temp_path);
1520        result
1521    })
1522    .await?
1523}
1524
1525/// Clean up temp directory from a cancelled preview session.
1526#[tauri::command]
1527pub async fn cancel_git_preview(temp_dir: String) -> Result<(), AppError> {
1528    tauri::async_runtime::spawn_blocking(move || {
1529        if let Ok(temp_path) = validate_clone_temp_path(&temp_dir) {
1530            git_fetcher::cleanup_temp(&temp_path);
1531        }
1532        Ok(())
1533    })
1534    .await?
1535}
1536
1537#[tauri::command]
1538pub async fn check_skill_update(
1539    skill_id: String,
1540    force: Option<bool>,
1541    store: State<'_, Arc<SkillStore>>,
1542) -> Result<ManagedSkillDto, AppError> {
1543    let store = store.inner().clone();
1544    let proxy_url = store.proxy_url();
1545    tauri::async_runtime::spawn_blocking(move || {
1546        let force = force.unwrap_or(false);
1547        // Resolve first, take the lock second. Holding it across `ls-remote`
1548        // meant one check of a slow remote could occupy the repository for the
1549        // whole round-trip and fail every concurrent operation (#315).
1550        let prefetched = prefetch_skill_remote(&store, &skill_id, force, proxy_url.as_deref());
1551        let _lock = RepoLock::acquire_foreground("check skill update").map_err(AppError::db)?;
1552        check_skill_update_internal_with_remote(&store, &skill_id, force, prefetched)
1553    })
1554    .await?
1555}
1556
1557#[tauri::command]
1558pub async fn check_all_skill_updates(
1559    force: Option<bool>,
1560    store: State<'_, Arc<SkillStore>>,
1561) -> Result<(), AppError> {
1562    let store = store.inner().clone();
1563    let proxy_url = store.proxy_url();
1564    tauri::async_runtime::spawn_blocking(move || {
1565        let force_check = force.unwrap_or(false);
1566        let skills = store.get_all_skills().map_err(AppError::db)?;
1567
1568        // ── Phase A: resolve every distinct remote once, concurrently ──
1569        // Collect the git-backed skills that still need a network check keyed by
1570        // (clone_url, branch). Skills installed from subdirectories of the same
1571        // monorepo collapse to a single `ls-remote`, and each remote is queried
1572        // off the central-repo lock so a slow remote (e.g. vercel/ai's ref
1573        // advertisement runs ~30s) never starves a concurrent check into a 20s
1574        // lock-timeout "busy" failure — the reason "检查全部" both crawled and
1575        // popped failures.
1576        let mut remotes: HashSet<RemoteKey> = HashSet::new();
1577        for skill in &skills {
1578            if !matches!(skill.source_type.as_str(), "git" | "skillssh") {
1579                continue;
1580            }
1581            match should_skip_update_check(&store, skill, force_check) {
1582                Ok(true) => continue,
1583                Ok(false) => {}
1584                // A transient skip-decision error (e.g. a settings read) must not
1585                // abort the whole batch: fall through so Phase B still checks this
1586                // skill and collects any real failure per-skill, as before.
1587                Err(err) => log::warn!(
1588                    "check all: skip-decision for {} failed, checking anyway: {}",
1589                    skill.id,
1590                    err.message
1591                ),
1592            }
1593            if let Ok(source) = git_source_from_skill(skill) {
1594                remotes.insert(RemoteKey::from(source));
1595            }
1596        }
1597        let remote_revisions = if remotes.is_empty() {
1598            HashMap::new()
1599        } else {
1600            resolve_remotes_concurrent(remotes.into_iter().collect(), proxy_url.clone())
1601        };
1602
1603        // ── Phase B: apply the resolved revisions + local-source checks ──
1604        // Phase A already did every network read, so this loop only computes and
1605        // writes each skill's status columns. Re-take the central-repo lock per
1606        // skill around that write — the same guard the pre-concurrent code used so
1607        // a concurrent manual install/update can't race the `update_status` write
1608        // — but now the lock is never held across a slow `ls-remote`, because the
1609        // network happened off the lock in Phase A, and the apply step itself
1610        // can't reach the network. A skill whose source moved (or whose TTL
1611        // expired) between the two phases has no usable prefetch and is simply
1612        // left for the next round. Lock contention is still reported per skill
1613        // so the caller knows the check didn't complete for it.
1614        let mut failed = Vec::new();
1615        for skill in &skills {
1616            let prefetched = if matches!(skill.source_type.as_str(), "git" | "skillssh") {
1617                git_source_from_skill(skill).ok().and_then(|source| {
1618                    let key = RemoteKey::from(source);
1619                    remote_revisions
1620                        .get(&key)
1621                        .cloned()
1622                        .map(|result| PrefetchedRemote { key, result })
1623                })
1624            } else {
1625                None
1626            };
1627            let _lock = match RepoLock::acquire("check skill update") {
1628                Ok(lock) => lock,
1629                Err(err) => {
1630                    failed.push(format!("{}: {}", skill.id, err));
1631                    continue;
1632                }
1633            };
1634            if let Err(err) =
1635                check_skill_update_internal_with_remote(&store, &skill.id, force_check, prefetched)
1636            {
1637                // Surface the real per-skill reason so a batch that "just fails"
1638                // is diagnosable from the logs, not only the aggregated toast.
1639                log::warn!("check all: {} failed: {}", skill.id, err.message);
1640                failed.push(format!("{}: {}", skill.id, err));
1641            }
1642        }
1643
1644        if failed.is_empty() {
1645            Ok(())
1646        } else {
1647            Err(AppError::internal(format!(
1648                "Failed to check {} skill(s): {}",
1649                failed.len(),
1650                failed.join("; ")
1651            )))
1652        }
1653    })
1654    .await?
1655}
1656
1657/// A distinct remote to resolve once during a batch check. Several skills can
1658/// share one — e.g. many skills installed from subdirectories of a single
1659/// monorepo — so keying by (clone_url, branch) collapses the redundant network
1660/// queries the per-skill loop used to make.
1661#[derive(Clone, PartialEq, Eq, Hash)]
1662struct RemoteKey {
1663    clone_url: String,
1664    branch: Option<String>,
1665}
1666
1667impl From<GitSkillSource> for RemoteKey {
1668    fn from(source: GitSkillSource) -> Self {
1669        RemoteKey {
1670            clone_url: source.clone_url,
1671            branch: source.branch,
1672        }
1673    }
1674}
1675
1676impl RemoteKey {
1677    /// Whether `source` still points at this remote. Subpath is deliberately
1678    /// ignored: two subdirectories of one repo share a head revision.
1679    fn matches(&self, source: &GitSkillSource) -> bool {
1680        self.clone_url == source.clone_url && self.branch == source.branch
1681    }
1682}
1683
1684/// A remote revision resolved off the central-repo lock, tagged with the remote
1685/// it was resolved for. The tag is what makes it safe to apply later: a
1686/// reinstall keeps a skill's row and repoints its source
1687/// (`update_skill_after_reinstall`), so the applying side re-derives the key
1688/// from the freshly read record and drops a prefetch that no longer matches.
1689#[derive(Clone)]
1690pub struct PrefetchedRemote {
1691    key: RemoteKey,
1692    result: Result<String, String>,
1693}
1694
1695/// Resolve one skill's remote revision *before* the caller takes the
1696/// central-repo lock. Every lock-holding update-check path goes through this:
1697/// holding the lock across a slow `ls-remote` is what made an unrelated
1698/// foreground operation fail with a 20s "repository is busy" (#315).
1699///
1700/// Returns `None` when there is nothing to resolve — a local skill, one still
1701/// inside its check TTL, or an unparseable source — in which case the check
1702/// itself does no network either.
1703pub fn prefetch_skill_remote(
1704    store: &SkillStore,
1705    skill_id: &str,
1706    force: bool,
1707    proxy_url: Option<&str>,
1708) -> Option<PrefetchedRemote> {
1709    let skill = store.get_skill_by_id(skill_id).ok().flatten()?;
1710    if !matches!(skill.source_type.as_str(), "git" | "skillssh") {
1711        return None;
1712    }
1713    if should_skip_update_check(store, &skill, force).unwrap_or(false) {
1714        return None;
1715    }
1716    let key = RemoteKey::from(git_source_from_skill(&skill).ok()?);
1717    let result =
1718        git_fetcher::resolve_remote_revision(&key.clone_url, key.branch.as_deref(), proxy_url)
1719            .map_err(|err| err.to_string());
1720    Some(PrefetchedRemote { key, result })
1721}
1722
1723/// Upper bound on concurrent `ls-remote` queries during a batch check. Collapses
1724/// the wall-clock cost of a large library from "sum of every remote" to "slowest
1725/// single remote" without opening an unbounded number of git subprocesses.
1726const MAX_CHECK_CONCURRENCY: usize = 8;
1727
1728/// Resolve each remote's head revision concurrently, without the central-repo
1729/// lock — these are read-only remote reads. A failed resolution is stored as
1730/// `Err(message)` so Phase B can mark just that remote's skills as errored
1731/// without aborting the batch.
1732fn resolve_remotes_concurrent(
1733    remotes: Vec<RemoteKey>,
1734    proxy_url: Option<String>,
1735) -> HashMap<RemoteKey, Result<String, String>> {
1736    resolve_concurrent(remotes, |key| {
1737        git_fetcher::resolve_remote_revision(
1738            &key.clone_url,
1739            key.branch.as_deref(),
1740            proxy_url.as_deref(),
1741        )
1742        .map_err(|err| err.to_string())
1743    })
1744}
1745
1746/// Run `resolve` over every remote concurrently (bounded by
1747/// `MAX_CHECK_CONCURRENCY`) with work-stealing, and collect each result. Factored
1748/// out of [`resolve_remotes_concurrent`] so the concurrency contract is testable
1749/// with an injected resolver instead of live network: every remote is resolved
1750/// exactly once, a per-remote failure is stored as `Err` rather than aborting the
1751/// batch, and — since this function never touches `RepoLock` — resolution always
1752/// runs off the central-repo lock.
1753fn resolve_concurrent<F>(
1754    remotes: Vec<RemoteKey>,
1755    resolve: F,
1756) -> HashMap<RemoteKey, Result<String, String>>
1757where
1758    F: Fn(&RemoteKey) -> Result<String, String> + Sync,
1759{
1760    use std::sync::atomic::{AtomicUsize, Ordering};
1761
1762    let next = AtomicUsize::new(0);
1763    let results: Mutex<HashMap<RemoteKey, Result<String, String>>> =
1764        Mutex::new(HashMap::with_capacity(remotes.len()));
1765    let worker_count = MAX_CHECK_CONCURRENCY.min(remotes.len().max(1));
1766
1767    std::thread::scope(|scope| {
1768        for _ in 0..worker_count {
1769            scope.spawn(|| loop {
1770                let idx = next.fetch_add(1, Ordering::Relaxed);
1771                let Some(key) = remotes.get(idx) else { break };
1772
1773                let resolved = resolve(key);
1774                if let Ok(mut map) = results.lock() {
1775                    map.insert(key.clone(), resolved);
1776                }
1777            });
1778        }
1779    });
1780
1781    results.into_inner().unwrap_or_default()
1782}
1783
1784/// Update one skill.
1785///
1786/// `approved_removals` carries back `removal_approval` from a call that
1787/// declined. The first call from the UI passes `None`; if it comes back with
1788/// `pending_removals`, the user is shown exactly what would disappear and only
1789/// then is it called again with that token.
1790#[tauri::command]
1791pub async fn update_skill(
1792    skill_id: String,
1793    approved_removals: Option<String>,
1794    store: State<'_, Arc<SkillStore>>,
1795    cancel_registry: State<'_, Arc<InstallCancelRegistry>>,
1796) -> Result<UpdateSkillResult, AppError> {
1797    let store = store.inner().clone();
1798    let proxy_url = store.proxy_url();
1799    let registry = cancel_registry.inner().clone();
1800    let cancel_key = format!("update:{}", skill_id);
1801    let cancel = registry.register(&cancel_key);
1802    let _cancel_guard = CancelRegistrationGuard::new(registry.clone(), cancel_key);
1803
1804    tauri::async_runtime::spawn_blocking(move || {
1805        let outcome = update_git_skill_internal(
1806            &store,
1807            &skill_id,
1808            proxy_url.as_deref(),
1809            Some(&cancel),
1810            approved_removals.as_deref(),
1811        );
1812        log_update_outcome(&store, &skill_id, "git", outcome.as_ref());
1813        outcome
1814    })
1815    .await?
1816}
1817
1818#[tauri::command]
1819pub async fn reimport_local_skill(
1820    skill_id: String,
1821    approved_removals: Option<String>,
1822    store: State<'_, Arc<SkillStore>>,
1823) -> Result<ReimportSkillResult, AppError> {
1824    let store = store.inner().clone();
1825    tauri::async_runtime::spawn_blocking(move || {
1826        let outcome =
1827            reimport_local_skill_internal(&store, &skill_id, approved_removals.as_deref());
1828        log_reimport_outcome(&store, &skill_id, outcome.as_ref());
1829        outcome
1830    })
1831    .await?
1832}
1833
1834#[tauri::command]
1835pub async fn batch_update_skills(
1836    skill_ids: Vec<String>,
1837    store: State<'_, Arc<SkillStore>>,
1838) -> Result<BatchUpdateSkillsResult, AppError> {
1839    let store = store.inner().clone();
1840    let proxy_url = store.proxy_url();
1841    tauri::async_runtime::spawn_blocking(move || {
1842        let mut refreshed = 0usize;
1843        let mut unchanged = 0usize;
1844        let mut failed = Vec::new();
1845        let mut held_back = Vec::new();
1846
1847        for skill_id in skill_ids {
1848            let skill = match store.get_skill_by_id(&skill_id).map_err(AppError::db)? {
1849                Some(skill) => skill,
1850                None => {
1851                    failed.push(format!("{skill_id}: Skill not found"));
1852                    continue;
1853                }
1854            };
1855
1856            match skill.source_type.as_str() {
1857                "git" | "skillssh" => {
1858                    let outcome = update_git_skill_internal(
1859                        &store,
1860                        &skill_id,
1861                        proxy_url.as_deref(),
1862                        None,
1863                        None,
1864                    );
1865                    log_update_outcome(&store, &skill_id, "git", outcome.as_ref());
1866                    match outcome {
1867                        Ok(result) if !result.pending_removals.is_empty() => {
1868                            // Held back rather than applied: it would have taken
1869                            // away files the new version does not have, and a
1870                            // batch has nobody to ask.
1871                            held_back.push(skill.name.clone());
1872                        }
1873                        Ok(result) => {
1874                            if result.content_changed {
1875                                refreshed += 1;
1876                            } else {
1877                                unchanged += 1;
1878                            }
1879                        }
1880                        Err(err) => failed.push(format!("{}: {}", skill.name, err.message)),
1881                    }
1882                }
1883                "local" | "import" => {
1884                    let outcome = reimport_local_skill_internal(&store, &skill_id, None);
1885                    log_reimport_outcome(&store, &skill_id, outcome.as_ref());
1886                    match outcome {
1887                        Ok(result) if !result.pending_removals.is_empty() => {
1888                            held_back.push(skill.name.clone());
1889                        }
1890                        Ok(result) if result.skill.update_status == "central_newer" => {
1891                            unchanged += 1
1892                        }
1893                        Ok(_) => refreshed += 1,
1894                        Err(err) => failed.push(format!("{}: {}", skill.name, err.message)),
1895                    }
1896                }
1897                _ => failed.push(format!("{}: Source type cannot be refreshed", skill.name)),
1898            }
1899        }
1900
1901        Ok(BatchUpdateSkillsResult {
1902            refreshed,
1903            unchanged,
1904            failed,
1905            held_back,
1906        })
1907    })
1908    .await?
1909}
1910
1911#[tauri::command]
1912/// Re-point a local skill at a different source directory.
1913///
1914/// `approved_removals` behaves as on the update paths: choosing a new source is
1915/// not a statement about discarding what the library has accumulated, so a
1916/// replacement that would take files away stops and reports them first.
1917pub async fn relink_local_skill_source(
1918    skill_id: String,
1919    source_path: String,
1920    approved_removals: Option<String>,
1921    store: State<'_, Arc<SkillStore>>,
1922) -> Result<ReimportSkillResult, AppError> {
1923    let store = store.inner().clone();
1924    tauri::async_runtime::spawn_blocking(move || {
1925        let skill = store
1926            .get_skill_by_id(&skill_id)
1927            .map_err(AppError::db)?
1928            .ok_or_else(|| AppError::not_found("Skill not found"))?;
1929
1930        if !matches!(skill.source_type.as_str(), "local" | "import") {
1931            return Err(AppError::invalid_input(
1932                "Only local skills can relink source paths",
1933            ));
1934        }
1935
1936        let path = PathBuf::from(&source_path);
1937        if !path.exists() {
1938            return Err(AppError::not_found("Selected source path does not exist"));
1939        }
1940        if !is_valid_skill_dir(&path) {
1941            return Err(AppError::invalid_input(
1942                "Selected source path is not a valid skill directory",
1943            ));
1944        }
1945
1946        store
1947            .update_skill_update_status(&skill_id, "updating")
1948            .map_err(AppError::db)?;
1949
1950        let result = (|| -> Result<(Vec<PendingRemoval>, Option<String>), AppError> {
1951            let _lock = RepoLock::acquire_foreground("relink local skill").map_err(AppError::db)?;
1952            let staged_path = staged_path_for(&skill.central_path);
1953            let install_result = installer::install_from_local_to_destination(
1954                &path,
1955                Some(&skill.name),
1956                &staged_path,
1957            )
1958            .inspect_err(|_| {
1959                let _ = remove_path_if_exists(&staged_path);
1960            })
1961            .map_err(AppError::io)?;
1962            let staged_guard = StagedPathGuard::new(&staged_path, true);
1963
1964            // Picking a new source says which source to follow. It does not say
1965            // to discard whatever has accumulated in the library since — same
1966            // replacement, same guard.
1967            let pending = pending_removals_for(&store, &skill, Some(&staged_path))?;
1968            let approval = removal_approval_token(&source_path, &pending);
1969            if !pending.is_empty() && approved_removals.as_deref() != Some(approval.as_str()) {
1970                // Put back exactly what was there. Hardcoding a status loses
1971                // `source_missing` — the only state relink is reachable from —
1972                // so declining would hide the Relink and Detach buttons on the
1973                // next refresh, and `check_state` would also clear the recorded
1974                // error and check time that nothing here has re-established.
1975                store
1976                    .update_skill_update_status(&skill.id, &skill.update_status)
1977                    .map_err(AppError::db)?;
1978                return Ok((pending, Some(approval)));
1979            }
1980
1981            swap_skill_directory(&staged_path, Path::new(&skill.central_path))?;
1982            staged_guard.release();
1983            store
1984                .update_skill_after_reinstall(
1985                    &skill.id,
1986                    &skill.name,
1987                    install_result.description.as_deref(),
1988                    &skill.source_type,
1989                    Some(&source_path),
1990                    None,
1991                    None,
1992                    None,
1993                    None,
1994                    None,
1995                    Some(&install_result.content_hash),
1996                    "local_only",
1997                )
1998                .map_err(AppError::db)?;
1999            resync_copy_targets(&store, &skill.id)?;
2000            sync_metadata::write_all_from_db_unlocked(&store).map_err(AppError::db)?;
2001            Ok((Vec::new(), None))
2002        })();
2003
2004        match result {
2005            Ok((pending_removals, removal_approval)) => Ok(ReimportSkillResult {
2006                skill: managed_skill_by_id(&store, &skill_id)?,
2007                pending_removals,
2008                removal_approval,
2009            }),
2010            Err(e) => {
2011                let _ = store.update_skill_check_state(&skill_id, None, "error", Some(&e.message));
2012                Err(e)
2013            }
2014        }
2015    })
2016    .await?
2017}
2018
2019#[tauri::command]
2020pub async fn detach_local_skill_source(
2021    skill_id: String,
2022    store: State<'_, Arc<SkillStore>>,
2023) -> Result<ManagedSkillDto, AppError> {
2024    let store = store.inner().clone();
2025    tauri::async_runtime::spawn_blocking(move || {
2026        detach_local_skill_source_internal(&store, &skill_id)?;
2027        managed_skill_by_id(&store, &skill_id)
2028    })
2029    .await?
2030}
2031
2032/// Keep the managed library copy and its identity, without an external source.
2033pub fn detach_local_skill_source_internal(
2034    store: &SkillStore,
2035    skill_id: &str,
2036) -> Result<(), AppError> {
2037    let _lock = RepoLock::acquire_foreground("detach local skill").map_err(AppError::db)?;
2038    let skill = store
2039        .get_skill_by_id(skill_id)
2040        .map_err(AppError::db)?
2041        .ok_or_else(|| AppError::not_found("Skill not found"))?;
2042    if !matches!(skill.source_type.as_str(), "local" | "import") {
2043        return Err(AppError::invalid_input(
2044            "Only local skills can detach source paths",
2045        ));
2046    }
2047    store
2048        .update_skill_after_reinstall(
2049            &skill.id,
2050            &skill.name,
2051            skill.description.as_deref(),
2052            &skill.source_type,
2053            None,
2054            None,
2055            None,
2056            None,
2057            None,
2058            None,
2059            skill.content_hash.as_deref(),
2060            "local_only",
2061        )
2062        .map_err(AppError::db)?;
2063    sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)
2064}
2065
2066fn managed_skill_to_dto(
2067    store: &SkillStore,
2068    skill: SkillRecord,
2069    all_targets: &[SkillTargetRecord],
2070    tags_map: &std::collections::HashMap<String, Vec<String>>,
2071) -> ManagedSkillDto {
2072    let targets = all_targets
2073        .iter()
2074        .filter(|target| target.skill_id == skill.id)
2075        .map(|target| TargetDto {
2076            id: target.id.clone(),
2077            skill_id: target.skill_id.clone(),
2078            tool: target.tool.clone(),
2079            target_path: target.target_path.clone(),
2080            mode: target.mode.clone(),
2081            status: target.status.clone(),
2082            synced_at: target.synced_at,
2083        })
2084        .collect();
2085
2086    let skill_group_ids = store.get_scenarios_for_skill(&skill.id).unwrap_or_default();
2087    let tags = tags_map.get(&skill.id).cloned().unwrap_or_default();
2088
2089    // Prefer description from SKILL.md so the list view reflects edits made
2090    // directly on disk (file watcher emits a change event; this read serves
2091    // the fresh value). Keep `name` on the DB value to avoid drift with
2092    // sync target directory names.
2093    let metadata = skill_metadata::parse_skill_md(Path::new(&skill.central_path));
2094    let update_status = display_update_status(&skill, metadata.version.as_deref());
2095    let description = metadata
2096        .description
2097        .filter(|s| !s.trim().is_empty())
2098        .or(skill.description);
2099    let version = metadata.version.filter(|s| !s.trim().is_empty());
2100
2101    ManagedSkillDto {
2102        id: skill.id,
2103        name: skill.name,
2104        description,
2105        version,
2106        source_type: skill.source_type,
2107        source_ref: skill.source_ref,
2108        source_ref_resolved: skill.source_ref_resolved,
2109        source_subpath: skill.source_subpath,
2110        source_branch: skill.source_branch,
2111        source_revision: skill.source_revision,
2112        source_agent: skill.source_agent,
2113        remote_revision: skill.remote_revision,
2114        update_status: update_status.clone(),
2115        last_checked_at: skill.last_checked_at,
2116        last_check_error: if update_status == "local_only" {
2117            None
2118        } else {
2119            skill.last_check_error
2120        },
2121        central_path: skill.central_path,
2122        enabled: skill.enabled,
2123        created_at: skill.created_at,
2124        updated_at: skill.updated_at,
2125        status: skill.status,
2126        targets,
2127        skill_group_ids,
2128        tags,
2129    }
2130}
2131
2132pub fn managed_skill_by_id(
2133    store: &SkillStore,
2134    skill_id: &str,
2135) -> Result<ManagedSkillDto, AppError> {
2136    let skill = store
2137        .get_skill_by_id(skill_id)
2138        .map_err(AppError::db)?
2139        .ok_or_else(|| AppError::not_found("Skill not found"))?;
2140    let all_targets = store.get_all_targets().map_err(AppError::db)?;
2141    let tags_map = store.get_tags_map().map_err(AppError::db)?;
2142    Ok(managed_skill_to_dto(store, skill, &all_targets, &tags_map))
2143}
2144
2145/// Update an installed git-sourced skill.
2146///
2147/// `approved_removals` carries back the token from a previous call that
2148/// declined, approving exactly the list it reported at exactly that revision.
2149/// Without it — or with a stale one — an update that would take away files the
2150/// new version does not have stops and reports them instead, having changed
2151/// nothing. See [`crate::core::removals`].
2152///
2153/// Unattended callers pass `None` and simply do not update: nobody is there to
2154/// be asked, and applying anyway is what #256 was.
2155pub fn update_git_skill_internal(
2156    store: &SkillStore,
2157    skill_id: &str,
2158    proxy_url: Option<&str>,
2159    cancel: Option<&Arc<AtomicBool>>,
2160    approved_removals: Option<&str>,
2161) -> Result<UpdateSkillResult, AppError> {
2162    let skill = store
2163        .get_skill_by_id(skill_id)
2164        .map_err(AppError::db)?
2165        .ok_or_else(|| AppError::not_found("Skill not found"))?;
2166
2167    if !matches!(skill.source_type.as_str(), "git" | "skillssh") {
2168        return Err(AppError::invalid_input(
2169            "Only git-based skills can be updated",
2170        ));
2171    }
2172
2173    let git_source = git_source_from_skill(&skill)?;
2174    git_fetcher::validate_git_url(&git_source.clone_url).map_err(AppError::git)?;
2175    let remote_revision = git_fetcher::resolve_remote_revision(
2176        &git_source.clone_url,
2177        git_source.branch.as_deref(),
2178        proxy_url,
2179    )
2180    .map_err(|e| {
2181        let message = e.to_string();
2182        let _ = store.update_skill_check_state(
2183            skill_id,
2184            skill.remote_revision.as_deref(),
2185            "error",
2186            Some(&message),
2187        );
2188        AppError::git(message)
2189    })?;
2190
2191    store
2192        .update_skill_update_status(skill_id, "updating")
2193        .map_err(AppError::db)?;
2194
2195    let temp_dir = git_fetcher::clone_repo_ref_scoped(
2196        &git_source.clone_url,
2197        git_source.branch.as_deref(),
2198        git_source.subpath.as_deref(),
2199        cancel,
2200        proxy_url,
2201        None,
2202    )
2203    .map_err(AppError::classify_git_error)?;
2204    let update_result = (|| -> Result<UpdateOutcome, AppError> {
2205        git_fetcher::checkout_revision(&temp_dir, &remote_revision).map_err(AppError::git)?;
2206        let skill_dir = resolve_skill_dir(
2207            &temp_dir,
2208            git_source.subpath.as_deref(),
2209            git_source.locator_skill_id.as_deref(),
2210        )?;
2211
2212        let new_hash =
2213            crate::core::content_hash::hash_directory(&skill_dir).map_err(AppError::io)?;
2214        let content_changed = skill.content_hash.as_deref() != Some(new_hash.as_str());
2215        let source_subpath = git_fetcher::relative_subpath(&temp_dir, &skill_dir);
2216        let _lock = RepoLock::acquire_foreground("update installed skill").map_err(AppError::db)?;
2217
2218        if preserve_newer_library(store, &skill, &skill_dir, Some(&remote_revision))? {
2219            return Ok(UpdateOutcome::Applied {
2220                content_changed: false,
2221            });
2222        }
2223
2224        // Stage first, then compare. The tree that lands in the library is the
2225        // installer's output, not the raw checkout — it drops `.git` and every
2226        // symlink — so comparing against the checkout would report a path as
2227        // surviving that the swap then removes.
2228        let staged_path = staged_path_for(&skill.central_path);
2229        let install_result = if content_changed {
2230            Some(
2231                installer::install_skill_dir_to_destination(&skill_dir, &skill.name, &staged_path)
2232                    .inspect_err(|_| {
2233                        let _ = remove_path_if_exists(&staged_path);
2234                    })
2235                    .map_err(AppError::io)?,
2236            )
2237        } else {
2238            None
2239        };
2240        let staged_guard = StagedPathGuard::new(&staged_path, install_result.is_some());
2241
2242        let pending = pending_removals_for(
2243            store,
2244            &skill,
2245            install_result.is_some().then_some(staged_path.as_path()),
2246        )?;
2247
2248        // A confirmation answers one exact question: this revision, this list
2249        // as shown. It closes the window while the dialog is open — a push, or
2250        // a file that changes the list, re-asks. Note a directory the new
2251        // version drops is one entry, so a file created *inside* it afterwards
2252        // does not change the list; approving `outputs/` approves the subtree. It cannot close the window
2253        // between this scan and the removal itself: the repo lock holds off
2254        // agent-hub, not the agent processes writing into these very
2255        // directories. Narrowing that further needs the directories frozen
2256        // before the scan, not another scan.
2257        let approval = removal_approval_token(&remote_revision, &pending);
2258        if !pending.is_empty() && approved_removals != Some(approval.as_str()) {
2259            // Declining is not a failure: nothing was touched and the update is
2260            // still waiting. Clear the `updating` marker here, inside the lock,
2261            // rather than after releasing it — doing it later lets a concurrent
2262            // update overwrite the state, and swallowing the error would leave
2263            // the skill showing "updating" forever.
2264            store
2265                .update_skill_check_state(
2266                    &skill.id,
2267                    Some(&remote_revision),
2268                    "update_available",
2269                    None,
2270                )
2271                .map_err(AppError::db)?;
2272            return Ok(UpdateOutcome::Held { pending, approval });
2273        }
2274
2275        if let Some(install_result) = install_result {
2276            swap_skill_directory(&staged_path, Path::new(&skill.central_path))?;
2277            // Only now is it the library's. Releasing before the swap left the
2278            // staged directory behind whenever its first rename failed.
2279            staged_guard.release();
2280
2281            store
2282                .update_skill_source_metadata(
2283                    &skill.id,
2284                    Some(&git_source.clone_url),
2285                    source_subpath.as_deref(),
2286                    git_source.branch.as_deref(),
2287                    Some(&remote_revision),
2288                )
2289                .map_err(AppError::db)?;
2290            store
2291                .update_skill_after_install(
2292                    &skill.id,
2293                    &skill.name,
2294                    install_result.description.as_deref(),
2295                    Some(&remote_revision),
2296                    Some(&remote_revision),
2297                    Some(&install_result.content_hash),
2298                    "up_to_date",
2299                )
2300                .map_err(AppError::db)?;
2301            resync_copy_targets(store, &skill.id)?;
2302            sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)?;
2303        } else {
2304            store
2305                .update_skill_source_metadata(
2306                    &skill.id,
2307                    Some(&git_source.clone_url),
2308                    source_subpath.as_deref(),
2309                    git_source.branch.as_deref(),
2310                    Some(&remote_revision),
2311                )
2312                .map_err(AppError::db)?;
2313            store
2314                .update_skill_check_state(&skill.id, Some(&remote_revision), "up_to_date", None)
2315                .map_err(AppError::db)?;
2316            resync_copy_targets(store, &skill.id)?;
2317            sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)?;
2318        }
2319        Ok(UpdateOutcome::Applied { content_changed })
2320    })();
2321    git_fetcher::cleanup_temp(&temp_dir);
2322
2323    match update_result {
2324        Ok(outcome) => {
2325            let (content_changed, pending_removals, removal_approval) = match outcome {
2326                UpdateOutcome::Applied { content_changed } => (content_changed, Vec::new(), None),
2327                UpdateOutcome::Held { pending, approval } => (false, pending, Some(approval)),
2328            };
2329            let skill = managed_skill_by_id(store, skill_id)?;
2330            Ok(UpdateSkillResult {
2331                skill,
2332                content_changed,
2333                pending_removals,
2334                removal_approval,
2335            })
2336        }
2337        Err(e) => {
2338            let _ = store.update_skill_check_state(
2339                skill_id,
2340                Some(&remote_revision),
2341                "error",
2342                Some(&e.message),
2343            );
2344            Err(e)
2345        }
2346    }
2347}
2348
2349#[derive(Debug, Serialize)]
2350pub struct SetSourceResult {
2351    pub skill_id: String,
2352    pub name: String,
2353    /// Source type before the change (`local`, `import`, `git`, `skillssh`).
2354    pub previous_source_type: String,
2355    pub previous_source_ref: Option<String>,
2356    pub clone_url: String,
2357    pub subpath: Option<String>,
2358    pub branch: Option<String>,
2359    pub revision: String,
2360    /// Whether the new source's content differs from the hash recorded for the
2361    /// library copy. False means the re-point is metadata-only — no file is
2362    /// rewritten. Compared against the recorded hash, not a fresh hash of the
2363    /// central directory, so hand-edits made after install do not count as a
2364    /// difference (and are left in place, since no file work runs).
2365    pub content_changed: bool,
2366    pub dry_run: bool,
2367}
2368
2369/// Resolve the skill directory inside a fresh checkout, strictly.
2370///
2371/// Unlike [`resolve_skill_dir`], an explicit subpath that does not land on a
2372/// valid skill directory inside `repo_dir` is an error rather than a silent
2373/// fallback to repo-wide discovery. Re-pointing establishes a *new* source of
2374/// truth for an already-installed skill, so guessing is worse than failing: a
2375/// typo would otherwise install some unrelated directory — or the whole repo —
2376/// over the existing central copy.
2377fn resolve_repoint_skill_dir(repo_dir: &Path, subpath: Option<&str>) -> Result<PathBuf, AppError> {
2378    let Some(subpath) = subpath else {
2379        return if is_valid_skill_dir(repo_dir) {
2380            Ok(repo_dir.to_path_buf())
2381        } else {
2382            Err(AppError::invalid_input(
2383                "Repository root is not a skill directory (no SKILL.md); pass --subpath",
2384            ))
2385        };
2386    };
2387
2388    // `Path::join` returns the argument verbatim when it is absolute, and `..`
2389    // segments climb out, so the candidate must be checked before it is used.
2390    // `is_path_safe` canonicalizes both sides, which also catches symlinks that
2391    // point outside the checkout.
2392    let candidate = repo_dir.join(subpath);
2393    if !path_guard::is_path_safe(repo_dir, &candidate) {
2394        return Err(AppError::invalid_input(format!(
2395            "Subpath '{subpath}' resolves outside the repository"
2396        )));
2397    }
2398    if !candidate.is_dir() {
2399        return Err(AppError::not_found(format!(
2400            "Subpath '{subpath}' does not exist in the repository"
2401        )));
2402    }
2403    if !is_valid_skill_dir(&candidate) {
2404        return Err(AppError::invalid_input(format!(
2405            "Subpath '{subpath}' is not a skill directory (no SKILL.md)"
2406        )));
2407    }
2408    Ok(candidate)
2409}
2410
2411/// Re-point an installed skill at a git source **in place**.
2412///
2413/// The skill row is updated by id, so the skill id, tags, skill group membership and
2414/// deployment targets all survive. This is the only safe way to convert a
2415/// `local` skill to a `git` one: `install` reuses a central directory only when
2416/// the content hash matches exactly (see `installer::unique_skill_dest`) and
2417/// otherwise silently allocates `<name>-2`, while `remove` + `install` drops the
2418/// id and everything keyed to it.
2419///
2420/// When the new source's content differs from the current central copy the
2421/// command refuses unless `force` is set. Re-pointing is not an update: the
2422/// remote is not yet known to be the authoritative copy, so overwriting local
2423/// content that may exist nowhere else has to be a deliberate choice.
2424#[allow(clippy::too_many_arguments)]
2425pub fn set_git_source_internal(
2426    store: &SkillStore,
2427    skill_id: &str,
2428    git_url: &str,
2429    subpath: Option<&str>,
2430    branch: Option<&str>,
2431    proxy_url: Option<&str>,
2432    force: bool,
2433    dry_run: bool,
2434) -> Result<SetSourceResult, AppError> {
2435    let skill = store
2436        .get_skill_by_id(skill_id)
2437        .map_err(AppError::db)?
2438        .ok_or_else(|| AppError::not_found("Skill not found"))?;
2439
2440    // Validate before parsing: resolving a GitHub tree URL runs `ls-remote`, so
2441    // an unvalidated URL would reach the network first. `install` validates its
2442    // raw input the same way.
2443    git_fetcher::validate_git_url(git_url).map_err(AppError::git)?;
2444    let parsed = git_fetcher::parse_git_source_resolved(git_url, proxy_url);
2445
2446    // An explicit flag wins over whatever the URL encodes. `--subpath ""` is the
2447    // caller saying "the skill is at the repo root", which is distinct from
2448    // omitting the flag and letting the URL decide.
2449    let branch = branch.map(str::to_string).or_else(|| parsed.branch.clone());
2450    let subpath = match subpath {
2451        Some("") => None,
2452        Some(value) => Some(value.to_string()),
2453        None => parsed.subpath.clone(),
2454    };
2455
2456    let remote_revision =
2457        git_fetcher::resolve_remote_revision(&parsed.clone_url, branch.as_deref(), proxy_url)
2458            .map_err(|e| AppError::git(e.to_string()))?;
2459
2460    let temp_dir = git_fetcher::clone_repo_ref_scoped(
2461        &parsed.clone_url,
2462        branch.as_deref(),
2463        subpath.as_deref(),
2464        None,
2465        proxy_url,
2466        None,
2467    )
2468    .map_err(AppError::classify_git_error)?;
2469
2470    // Nothing before this point has written to the store, so a failure during
2471    // the network phase leaves no state to unwind — in particular the skill is
2472    // never left stuck in `updating`.
2473    let marked_updating = std::cell::Cell::new(false);
2474    let source_committed = std::cell::Cell::new(false);
2475    let outcome = (|| -> Result<(String, bool), AppError> {
2476        git_fetcher::checkout_revision(&temp_dir, &remote_revision).map_err(AppError::git)?;
2477        let skill_dir = resolve_repoint_skill_dir(&temp_dir, subpath.as_deref())?;
2478        let resolved_subpath = git_fetcher::relative_subpath(&temp_dir, &skill_dir);
2479
2480        let new_hash =
2481            crate::core::content_hash::hash_directory(&skill_dir).map_err(AppError::io)?;
2482        let content_changed = skill.content_hash.as_deref() != Some(new_hash.as_str());
2483
2484        // Report before refusing: inspecting a skill whose content differs is
2485        // exactly what --dry-run is for, so it must not need --force to run.
2486        if dry_run {
2487            return Ok((resolved_subpath.unwrap_or_default(), content_changed));
2488        }
2489        if content_changed && !force {
2490            return Err(AppError::invalid_input(
2491                "New source content differs from the current library copy; \
2492                 re-run with --dry-run to inspect, or --force to overwrite",
2493            ));
2494        }
2495
2496        let _lock = RepoLock::acquire_foreground("set skill source").map_err(AppError::db)?;
2497
2498        // The clone happened outside the lock, so the skill may have been
2499        // removed or re-pointed meanwhile. Re-read and refuse to apply a
2500        // decision made against a stale snapshot.
2501        let current = store
2502            .get_skill_by_id(skill_id)
2503            .map_err(AppError::db)?
2504            .ok_or_else(|| AppError::not_found("Skill was removed while fetching the source"))?;
2505        if current.central_path != skill.central_path
2506            || current.content_hash != skill.content_hash
2507            || current.source_type != skill.source_type
2508            || current.source_ref != skill.source_ref
2509        {
2510            return Err(AppError::invalid_input(
2511                "Skill changed while fetching the source; re-run the command",
2512            ));
2513        }
2514
2515        store
2516            .update_skill_update_status(skill_id, "updating")
2517            .map_err(AppError::db)?;
2518        marked_updating.set(true);
2519
2520        // Identical content needs no file work — swapping would rewrite the
2521        // central copy for a metadata-only change, and `installer` does not
2522        // copy exactly the set of files `content_hash` covers, so the rewrite
2523        // could alter files while still reporting `content_changed: false`.
2524        let description = if content_changed {
2525            let staged_path = staged_path_for(&skill.central_path);
2526            let install_result =
2527                installer::install_skill_dir_to_destination(&skill_dir, &skill.name, &staged_path)
2528                    .inspect_err(|_| {
2529                        let _ = std::fs::remove_dir_all(&staged_path);
2530                    })
2531                    .map_err(AppError::io)?;
2532            swap_skill_directory(&staged_path, Path::new(&skill.central_path))?;
2533            install_result.description
2534        } else {
2535            skill.description.clone()
2536        };
2537
2538        store
2539            .update_skill_after_reinstall(
2540                &skill.id,
2541                &skill.name,
2542                description.as_deref(),
2543                "git",
2544                Some(&parsed.original_url),
2545                Some(&parsed.clone_url),
2546                resolved_subpath.as_deref(),
2547                branch.as_deref(),
2548                Some(&remote_revision),
2549                Some(&remote_revision),
2550                Some(&new_hash),
2551                "up_to_date",
2552            )
2553            .map_err(AppError::db)?;
2554        source_committed.set(true);
2555        resync_copy_targets(store, &skill.id)?;
2556        sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)?;
2557        Ok((resolved_subpath.unwrap_or_default(), content_changed))
2558    })();
2559
2560    git_fetcher::cleanup_temp(&temp_dir);
2561
2562    match outcome {
2563        Ok((resolved_subpath, content_changed)) => Ok(SetSourceResult {
2564            skill_id: skill.id,
2565            name: skill.name,
2566            previous_source_type: skill.source_type,
2567            previous_source_ref: skill.source_ref,
2568            clone_url: parsed.clone_url,
2569            subpath: (!resolved_subpath.is_empty()).then_some(resolved_subpath),
2570            branch,
2571            revision: remote_revision,
2572            content_changed,
2573            dry_run,
2574        }),
2575        Err(e) => {
2576            // Only clear `updating` if this call actually set it. A refusal
2577            // (bad subpath, content differs without --force) touched nothing,
2578            // so marking the skill as errored would be a lie.
2579            //
2580            // `update_skill_check_state` always writes the revision column, so
2581            // it has to be given the one that matches whichever source the row
2582            // now describes: the new source's revision once the re-point
2583            // committed, otherwise the revision the old source already had.
2584            // Passing the newly resolved revision unconditionally would file a
2585            // commit from the new repo under a skill still pointing at the old
2586            // one; passing None would blank a revision that is still valid.
2587            if marked_updating.get() {
2588                let revision = if source_committed.get() {
2589                    Some(remote_revision.as_str())
2590                } else {
2591                    skill.remote_revision.as_deref()
2592                };
2593                let _ =
2594                    store.update_skill_check_state(skill_id, revision, "error", Some(&e.message));
2595            }
2596            Err(e)
2597        }
2598    }
2599}
2600
2601/// Re-import a local skill from its recorded source path.
2602///
2603/// `approved_removals` mirrors the git path: without it — or with one that no
2604/// longer matches the recomputed list — a re-import that would take away files
2605/// the source does not have stops and reports them.
2606pub fn reimport_local_skill_internal(
2607    store: &SkillStore,
2608    skill_id: &str,
2609    approved_removals: Option<&str>,
2610) -> Result<ReimportSkillResult, AppError> {
2611    let skill = store
2612        .get_skill_by_id(skill_id)
2613        .map_err(AppError::db)?
2614        .ok_or_else(|| AppError::not_found("Skill not found"))?;
2615
2616    if !matches!(skill.source_type.as_str(), "local" | "import") {
2617        return Err(AppError::invalid_input(
2618            "Only local skills can be reimported",
2619        ));
2620    }
2621
2622    let source_path = skill
2623        .source_ref
2624        .clone()
2625        .ok_or_else(|| AppError::not_found("Local skill is missing its original source path"))?;
2626    let path = PathBuf::from(&source_path);
2627    if !path.exists() {
2628        store
2629            .update_skill_check_state(
2630                &skill.id,
2631                None,
2632                "source_missing",
2633                Some("Original source path no longer exists"),
2634            )
2635            .map_err(AppError::db)?;
2636        return Err(AppError::not_found("Original source path no longer exists"));
2637    }
2638
2639    store
2640        .update_skill_update_status(skill_id, "updating")
2641        .map_err(AppError::db)?;
2642
2643    let result = (|| -> Result<(Vec<PendingRemoval>, Option<String>), AppError> {
2644        let _lock = RepoLock::acquire_foreground("reimport local skill").map_err(AppError::db)?;
2645        let staged_path = staged_path_for(&skill.central_path);
2646        let install_result =
2647            installer::install_from_local_to_destination(&path, Some(&skill.name), &staged_path)
2648                .inspect_err(|_| {
2649                    let _ = remove_path_if_exists(&staged_path);
2650                })
2651                .map_err(AppError::io)?;
2652        let staged_guard = StagedPathGuard::new(&staged_path, true);
2653        if preserve_newer_library(store, &skill, &staged_path, None)? {
2654            return Ok((Vec::new(), None));
2655        }
2656
2657        // Same replacement, same guard. Re-importing is explicit about the
2658        // *source*, not about discarding whatever has accumulated in the
2659        // library since — and for a local skill the "update" button runs this,
2660        // so leaving it uncovered would guard one path and not its twin.
2661        let pending = pending_removals_for(store, &skill, Some(&staged_path))?;
2662        // Bound to the set itself, not to a constant. A constant would match on
2663        // the approving call no matter what the recomputed list said, so a file
2664        // written while the dialog was open would be deleted having never been
2665        // shown — which is the whole failure this is here to prevent.
2666        let approval = removal_approval_token(REIMPORT_APPROVAL_DOMAIN, &pending);
2667        if !pending.is_empty() && approved_removals != Some(approval.as_str()) {
2668            // Restore the status this started from rather than asserting one:
2669            // declining changed nothing, so nothing about the skill's state
2670            // should read differently afterwards.
2671            store
2672                .update_skill_update_status(&skill.id, &skill.update_status)
2673                .map_err(AppError::db)?;
2674            return Ok((pending, Some(approval)));
2675        }
2676
2677        swap_skill_directory(&staged_path, Path::new(&skill.central_path))?;
2678        // Only now is it the library's; before this the guard still owns it.
2679        staged_guard.release();
2680        store
2681            .update_skill_after_install(
2682                &skill.id,
2683                &skill.name,
2684                install_result.description.as_deref(),
2685                None,
2686                None,
2687                Some(&install_result.content_hash),
2688                "local_only",
2689            )
2690            .map_err(AppError::db)?;
2691        resync_copy_targets(store, &skill.id)?;
2692        sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)?;
2693        Ok((Vec::new(), None))
2694    })();
2695
2696    match result {
2697        Ok((pending_removals, removal_approval)) => Ok(ReimportSkillResult {
2698            skill: managed_skill_by_id(store, skill_id)?,
2699            pending_removals,
2700            removal_approval,
2701        }),
2702        Err(e) => {
2703            let _ = store.update_skill_check_state(skill_id, None, "error", Some(&e.message));
2704            Err(e)
2705        }
2706    }
2707}
2708
2709pub fn store_installed_skill_unlocked(
2710    store: &SkillStore,
2711    result: &installer::InstallResult,
2712    metadata: &InstallSourceMetadata,
2713    active_scenario_id: Option<&str>,
2714) -> Result<String, AppError> {
2715    let now = chrono::Utc::now().timestamp_millis();
2716    let central_path = result.central_path.to_string_lossy().to_string();
2717
2718    if let Some(existing) = store
2719        .get_skill_by_central_path(&central_path)
2720        .map_err(AppError::db)?
2721    {
2722        store
2723            .update_skill_after_reinstall(
2724                &existing.id,
2725                &result.name,
2726                result.description.as_deref(),
2727                &metadata.source_type,
2728                metadata.source_ref.as_deref(),
2729                metadata.source_ref_resolved.as_deref(),
2730                metadata.source_subpath.as_deref(),
2731                metadata.source_branch.as_deref(),
2732                metadata.source_revision.as_deref(),
2733                metadata.remote_revision.as_deref(),
2734                Some(&result.content_hash),
2735                &metadata.update_status,
2736            )
2737            .map_err(AppError::db)?;
2738        if let Some(scenario_id) = active_scenario_id {
2739            store
2740                .add_skill_to_scenario(scenario_id, &existing.id)
2741                .map_err(AppError::db)?;
2742        }
2743        sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)?;
2744
2745        if let Some(scenario_id) = active_scenario_id {
2746            if let Err(e) = super::skill_groups::sync_skill_to_active_skill_group(
2747                store,
2748                scenario_id,
2749                &existing.id,
2750            ) {
2751                log::warn!("Failed to sync reinstalled skill to skill group: {e}");
2752            }
2753        }
2754
2755        return Ok(existing.id);
2756    }
2757
2758    let id = uuid::Uuid::new_v4().to_string();
2759
2760    let record = SkillRecord {
2761        id: id.clone(),
2762        name: result.name.clone(),
2763        description: result.description.clone(),
2764        source_type: metadata.source_type.clone(),
2765        source_ref: metadata.source_ref.clone(),
2766        source_ref_resolved: metadata.source_ref_resolved.clone(),
2767        source_subpath: metadata.source_subpath.clone(),
2768        source_branch: metadata.source_branch.clone(),
2769        source_revision: metadata.source_revision.clone(),
2770        source_agent: metadata.source_agent.clone(),
2771        remote_revision: metadata.remote_revision.clone(),
2772        central_path,
2773        content_hash: Some(result.content_hash.clone()),
2774        enabled: true,
2775        created_at: now,
2776        updated_at: now,
2777        status: "ok".to_string(),
2778        update_status: metadata.update_status.clone(),
2779        last_checked_at: Some(now),
2780        last_check_error: None,
2781    };
2782
2783    store.insert_skill(&record).map_err(AppError::db)?;
2784    if let Some(scenario_id) = active_scenario_id {
2785        store
2786            .add_skill_to_scenario(scenario_id, &id)
2787            .map_err(AppError::db)?;
2788    }
2789    sync_metadata::write_all_from_db_unlocked(store).map_err(AppError::db)?;
2790
2791    if let Some(scenario_id) = active_scenario_id {
2792        if let Err(e) =
2793            super::skill_groups::sync_skill_to_active_skill_group(store, scenario_id, &id)
2794        {
2795            log::warn!("Failed to sync newly installed skill to skill group: {e}");
2796        }
2797    }
2798
2799    Ok(id)
2800}
2801
2802/// Check one skill end to end: resolve its remote, then write the status.
2803///
2804/// The caller must **not** hold the central-repo lock — the resolution here is
2805/// a network call. Paths that need the lock take it around
2806/// [`check_skill_update_internal_with_remote`] only, after prefetching.
2807pub fn check_skill_update_internal(
2808    store: &SkillStore,
2809    skill_id: &str,
2810    force: bool,
2811    proxy_url: Option<&str>,
2812) -> Result<ManagedSkillDto, AppError> {
2813    let prefetched = prefetch_skill_remote(store, skill_id, force, proxy_url);
2814    check_skill_update_internal_with_remote(store, skill_id, force, prefetched)
2815}
2816
2817/// Write one skill's update status from an already-resolved remote revision.
2818///
2819/// This never touches the network — [`prefetch_skill_remote`] does that off the
2820/// central-repo lock, and callers hold the lock only for this write. A git
2821/// skill whose `prefetched` is missing or points at a remote the skill no
2822/// longer uses is left untouched for the next round.
2823pub fn check_skill_update_internal_with_remote(
2824    store: &SkillStore,
2825    skill_id: &str,
2826    force: bool,
2827    prefetched: Option<PrefetchedRemote>,
2828) -> Result<ManagedSkillDto, AppError> {
2829    let skill = store
2830        .get_skill_by_id(skill_id)
2831        .map_err(AppError::db)?
2832        .ok_or_else(|| AppError::not_found("Skill not found"))?;
2833
2834    if should_skip_update_check(store, &skill, force)? {
2835        return managed_skill_by_id(store, skill_id);
2836    }
2837
2838    match skill.source_type.as_str() {
2839        "git" | "skillssh" => {
2840            let git_source = git_source_from_skill(&skill)?;
2841            let metadata_updated = skill.source_ref_resolved.as_deref()
2842                != Some(git_source.clone_url.as_str())
2843                || skill.source_subpath.as_deref() != git_source.subpath.as_deref()
2844                || skill.source_branch.as_deref() != git_source.branch.as_deref();
2845            if metadata_updated {
2846                store
2847                    .update_skill_source_metadata(
2848                        &skill.id,
2849                        Some(&git_source.clone_url),
2850                        git_source.subpath.as_deref(),
2851                        git_source.branch.as_deref(),
2852                        skill.source_revision.as_deref(),
2853                    )
2854                    .map_err(AppError::db)?;
2855            }
2856
2857            // Apply the revision resolved off the lock — but only if the skill
2858            // still points at the remote it was resolved for. A reinstall keeps
2859            // the row and repoints its source, so a stale prefetch would record
2860            // a status computed against the wrong remote.
2861            //
2862            // When nothing usable was prefetched, skip the skill instead of
2863            // resolving here: every caller of this function holds the
2864            // central-repo lock, and a network call under that lock is the
2865            // 20s "busy" failure the off-lock split exists to remove (#315).
2866            // The next round picks the skill up.
2867            let Some(remote_result) = prefetched
2868                .filter(|prefetched| prefetched.key.matches(&git_source))
2869                .map(|prefetched| prefetched.result)
2870            else {
2871                log::debug!(
2872                    "check update: no usable prefetched remote for {}, skipping this round",
2873                    skill.id
2874                );
2875                return managed_skill_by_id(store, skill_id);
2876            };
2877            match remote_result {
2878                Ok(remote_revision) => {
2879                    let update_status = match skill.source_revision.as_deref() {
2880                        _ if skill.update_status == "central_newer"
2881                            && skill.remote_revision.as_deref()
2882                                == Some(remote_revision.as_str()) =>
2883                        {
2884                            "central_newer"
2885                        }
2886                        Some(current) if current == remote_revision => "up_to_date",
2887                        Some(_) => "update_available",
2888                        None => "unknown",
2889                    };
2890                    store
2891                        .update_skill_check_state(
2892                            &skill.id,
2893                            Some(&remote_revision),
2894                            update_status,
2895                            None,
2896                        )
2897                        .map_err(AppError::db)?;
2898                }
2899                Err(message) => {
2900                    store
2901                        .update_skill_check_state(
2902                            &skill.id,
2903                            skill.remote_revision.as_deref(),
2904                            "error",
2905                            Some(&message),
2906                        )
2907                        .map_err(AppError::db)?;
2908                    return Err(AppError::git(message));
2909                }
2910            }
2911        }
2912        "local" | "import" => {
2913            let (status, error): (&str, Option<String>) = match skill.source_ref.as_deref() {
2914                Some(path) => {
2915                    let source_path = Path::new(path);
2916                    if local_source_is_discarded(source_path) {
2917                        ("local_only", None)
2918                    } else {
2919                        match installer::hash_local_source(source_path) {
2920                            Ok(live_hash) => local_source_status(&skill, source_path, &live_hash),
2921                            Err(err) => ("error", Some(err.to_string())),
2922                        }
2923                    }
2924                }
2925                None => ("local_only", None),
2926            };
2927            store
2928                .update_skill_check_state(&skill.id, None, status, error.as_deref())
2929                .map_err(AppError::db)?;
2930        }
2931        _ => {
2932            store
2933                .update_skill_check_state(&skill.id, None, "unknown", None)
2934                .map_err(AppError::db)?;
2935        }
2936    }
2937
2938    managed_skill_by_id(store, skill_id)
2939}
2940
2941fn should_skip_update_check(
2942    store: &SkillStore,
2943    skill: &SkillRecord,
2944    force: bool,
2945) -> Result<bool, AppError> {
2946    if force {
2947        return Ok(false);
2948    }
2949
2950    let ttl_minutes = store
2951        .get_setting("update_check_ttl_minutes")
2952        .map_err(AppError::db)?
2953        .and_then(|value| value.parse::<i64>().ok())
2954        .unwrap_or(60);
2955    let ttl_ms = ttl_minutes * 60 * 1000;
2956    let stable_status = !matches!(
2957        skill.update_status.as_str(),
2958        "unknown" | "checking" | "updating" | "error"
2959    );
2960
2961    Ok(stable_status
2962        && skill
2963            .last_checked_at
2964            .map(|checked| chrono::Utc::now().timestamp_millis() - checked < ttl_ms)
2965            .unwrap_or(false))
2966}
2967
2968pub fn git_source_from_skill(skill: &SkillRecord) -> Result<GitSkillSource, AppError> {
2969    let mut source = recorded_git_source(skill)?;
2970    let legacy_repository = source
2971        .clone_url
2972        .trim_end_matches(".git")
2973        .eq_ignore_ascii_case("https://github.com/JTBlink/agent-hub");
2974    let published_content = match source.subpath.as_deref() {
2975        Some("skills/productivity/agent-hub-cli" | "skills/engineering/code-review") => true,
2976        None => matches!(
2977            source.locator_skill_id.as_deref(),
2978            Some("agent-hub-cli" | "code-review")
2979        ),
2980        _ => false,
2981    };
2982    if legacy_repository
2983        && published_content
2984        && matches!(source.branch.as_deref(), None | Some("main"))
2985    {
2986        source.clone_url = format!(
2987            "https://github.com/{}.git",
2988            env!("AGENT_HUB_CONTENT_REPOSITORY")
2989        );
2990    }
2991    Ok(source)
2992}
2993
2994fn recorded_git_source(skill: &SkillRecord) -> Result<GitSkillSource, AppError> {
2995    if let Some(resolved) = &skill.source_ref_resolved {
2996        return Ok(GitSkillSource {
2997            clone_url: resolved.clone(),
2998            branch: skill.source_branch.clone(),
2999            subpath: skill.source_subpath.clone(),
3000            locator_skill_id: skill_ssh_id(skill),
3001        });
3002    }
3003
3004    match skill.source_type.as_str() {
3005        "git" => {
3006            let source_ref = skill
3007                .source_ref
3008                .as_ref()
3009                .ok_or_else(|| AppError::invalid_input("Git skill is missing its source URL"))?;
3010            let parsed = git_fetcher::parse_git_source(source_ref);
3011            Ok(GitSkillSource {
3012                clone_url: parsed.clone_url,
3013                // Prefer the branch resolved at install time — it survives
3014                // slash-branch tree URLs that the sync parse can't disambiguate.
3015                branch: skill.source_branch.clone().or(parsed.branch),
3016                subpath: skill.source_subpath.clone().or(parsed.subpath),
3017                locator_skill_id: None,
3018            })
3019        }
3020        "skillssh" => {
3021            let source_ref = skill.source_ref.as_ref().ok_or_else(|| {
3022                AppError::invalid_input("skills.sh skill is missing its source reference")
3023            })?;
3024            let (repo_source, fallback_skill_id) = source_ref
3025                .rsplit_once('/')
3026                .ok_or_else(|| AppError::invalid_input("Invalid skills.sh source reference"))?;
3027            Ok(GitSkillSource {
3028                clone_url: format!("https://github.com/{}.git", repo_source),
3029                branch: skill.source_branch.clone(),
3030                subpath: skill.source_subpath.clone(),
3031                locator_skill_id: Some(fallback_skill_id.to_string()),
3032            })
3033        }
3034        _ => Err(AppError::invalid_input(
3035            "Skill does not support git-based updates",
3036        )),
3037    }
3038}
3039
3040fn skill_ssh_id(skill: &SkillRecord) -> Option<String> {
3041    if skill.source_type != "skillssh" {
3042        return None;
3043    }
3044
3045    skill.source_ref.as_deref().and_then(|source_ref| {
3046        source_ref
3047            .rsplit_once('/')
3048            .map(|(_, skill_id)| skill_id.to_string())
3049    })
3050}
3051
3052/// Return the list of individual skill directories to install from a resolved repo dir.
3053/// If `skill_dir` is itself a valid skill, returns `[skill_dir]`.
3054/// Otherwise recursively walks for skill dirs (e.g. `category/<skill>` layouts).
3055/// Returns an empty Vec when nothing is found — callers must handle that.
3056pub fn collect_git_skill_dirs(skill_dir: &Path) -> Vec<PathBuf> {
3057    if is_valid_skill_dir(skill_dir) {
3058        return vec![skill_dir.to_path_buf()];
3059    }
3060    let mut dirs = scanner::collect_skill_dirs(skill_dir);
3061    dirs.sort();
3062    dirs
3063}
3064
3065/// Validate and canonicalize a temp directory path used by the git preview/install flow.
3066/// Returns the canonicalized path if it passes security checks.
3067pub fn validate_clone_temp_path(temp_dir: &str) -> Result<PathBuf, AppError> {
3068    let raw_path = PathBuf::from(temp_dir);
3069    if !raw_path.exists() {
3070        return Err(AppError::invalid_input(
3071            "Clone session expired, please try again",
3072        ));
3073    }
3074    // Canonicalize to resolve symlinks and `..` segments before checking prefix.
3075    let temp_path = raw_path
3076        .canonicalize()
3077        .map_err(|_| AppError::invalid_input("Invalid temp directory"))?;
3078
3079    // Preview confirmation must operate on an isolated checkout, never the repo cache.
3080    let expected_prefix = std::env::temp_dir()
3081        .canonicalize()
3082        .unwrap_or_else(|_| std::env::temp_dir());
3083    if temp_path.starts_with(&expected_prefix) {
3084        let dir_name_str = temp_path
3085            .file_name()
3086            .map(|n| n.to_string_lossy().to_string())
3087            .unwrap_or_default();
3088        if dir_name_str.starts_with(git_fetcher::CLONE_TEMP_PREFIX) {
3089            return Ok(temp_path);
3090        }
3091    }
3092
3093    Err(AppError::invalid_input("Invalid temp directory"))
3094}
3095
3096/// Resolve which directory of a fresh checkout holds the skill.
3097///
3098/// Both inputs are attacker-reachable. `subpath` comes from the path segment of
3099/// a `…/tree/<branch>/<path>` URL the user pasted, and `skill_id` from the part
3100/// after `@` in a skills.sh shorthand, which `parse_skillssh_shorthand` does not
3101/// constrain to a single path segment. `Path::join` returns an absolute argument
3102/// verbatim and `..` segments climb out of the checkout, so both are checked for
3103/// containment: without that, `install` copies the resolved directory into the
3104/// library — which for a git-backed library can then be pushed to the user's
3105/// backup remote.
3106///
3107/// A subpath that stays inside the checkout but does not exist is a different
3108/// case: it is only recoverable when a skills.sh locator can find the skill by
3109/// id, which is how a skill that moved upstream is picked up again (#278).
3110/// Without a locator, falling through to repo-wide discovery would install or
3111/// update whatever that discovery happens to return — in a repository that
3112/// groups its skills, the entire `skills/` container.
3113pub fn resolve_skill_dir(
3114    repo_dir: &Path,
3115    subpath: Option<&str>,
3116    skill_id: Option<&str>,
3117) -> Result<PathBuf, AppError> {
3118    if let Some(subpath) = subpath {
3119        let candidate = repo_dir.join(subpath);
3120        if !path_guard::is_path_safe(repo_dir, &candidate) {
3121            return Err(AppError::invalid_input(format!(
3122                "Path '{subpath}' resolves outside the repository"
3123            )));
3124        }
3125        // With a locator to fall back on, the stored path is only taken when it
3126        // still holds a skill. An upstream reorganization can leave the path
3127        // occupied by a container or an unrelated directory, and copying that
3128        // over the installed skill is the same mistake as guessing — let the
3129        // locator look the skill up at its new home instead.
3130        let usable = if skill_id.is_some() {
3131            is_valid_skill_dir(&candidate)
3132        } else {
3133            candidate.is_dir()
3134        };
3135        if usable {
3136            return Ok(candidate);
3137        }
3138        if skill_id.is_none() {
3139            return Err(AppError::not_found(format!(
3140                "Path '{subpath}' does not exist in the repository"
3141            )));
3142        }
3143    }
3144
3145    // `find_skill_dir` joins the locator id onto the checkout in several places
3146    // before falling back to a recursive search, so its answer is checked too.
3147    let resolved = git_fetcher::find_skill_dir(repo_dir, skill_id).map_err(AppError::git)?;
3148    if !path_guard::is_path_safe(repo_dir, &resolved) {
3149        return Err(AppError::invalid_input(
3150            "Resolved skill directory is outside the repository",
3151        ));
3152    }
3153    Ok(resolved)
3154}
3155
3156pub fn resolve_skillssh_install_target(
3157    store: &SkillStore,
3158    source_ref: &str,
3159    skill_id: &str,
3160    source_hash: Option<&str>,
3161) -> Result<(String, PathBuf), AppError> {
3162    if let Some(existing) = store
3163        .get_skill_by_source_ref("skillssh", source_ref)
3164        .map_err(AppError::db)?
3165    {
3166        return Ok((existing.name, PathBuf::from(existing.central_path)));
3167    }
3168
3169    if let Some(source_hash) = source_hash {
3170        if let Some(existing) = store
3171            .get_all_skills()
3172            .map_err(AppError::db)?
3173            .into_iter()
3174            .find(|skill| {
3175                let same_content = skill.content_hash.as_deref() == Some(source_hash)
3176                    || (std::path::Path::new(&skill.central_path).is_dir()
3177                        && installer::hash_local_source(std::path::Path::new(&skill.central_path))
3178                            .ok()
3179                            .as_deref()
3180                            == Some(source_hash));
3181                let same_skill_key = skill.name.eq_ignore_ascii_case(skill_id)
3182                    || std::path::Path::new(&skill.central_path)
3183                        .file_name()
3184                        .is_some_and(|name| name.eq_ignore_ascii_case(skill_id));
3185                same_content && same_skill_key
3186            })
3187        {
3188            return Ok((existing.name, PathBuf::from(existing.central_path)));
3189        }
3190    }
3191
3192    let base_name = skill_id.trim();
3193    if base_name.is_empty() {
3194        return Err(AppError::invalid_input("Skill id is empty"));
3195    }
3196
3197    let candidate_path = central_repo::skills_dir().join(base_name);
3198    Ok((base_name.to_string(), candidate_path))
3199}
3200
3201pub fn staged_path_for(central_path: &str) -> PathBuf {
3202    let path = PathBuf::from(central_path);
3203    let file_name = path
3204        .file_name()
3205        .map(|name| name.to_string_lossy().to_string())
3206        .unwrap_or_else(|| "skill".to_string());
3207    path.with_file_name(format!(".{file_name}.staged-{}", uuid::Uuid::new_v4()))
3208}
3209
3210pub fn swap_skill_directory(staged_path: &Path, current_path: &Path) -> Result<(), AppError> {
3211    let backup_path = current_path.with_file_name(format!(
3212        ".{}.backup-{}",
3213        current_path
3214            .file_name()
3215            .map(|name| name.to_string_lossy().to_string())
3216            .unwrap_or_else(|| "skill".to_string()),
3217        uuid::Uuid::new_v4()
3218    ));
3219
3220    if current_path.exists() {
3221        std::fs::rename(current_path, &backup_path)?;
3222    }
3223
3224    if let Err(err) = std::fs::rename(staged_path, current_path) {
3225        if backup_path.exists() {
3226            let _ = std::fs::rename(&backup_path, current_path);
3227        }
3228        let _ = remove_path_if_exists(staged_path);
3229        return Err(err.into());
3230    }
3231
3232    remove_path_if_exists(&backup_path)?;
3233    Ok(())
3234}
3235
3236pub fn resync_copy_targets(store: &SkillStore, skill_id: &str) -> Result<(), AppError> {
3237    let skill = store
3238        .get_skill_by_id(skill_id)
3239        .map_err(AppError::db)?
3240        .ok_or_else(|| AppError::not_found("Skill not found"))?;
3241    let source = PathBuf::from(&skill.central_path);
3242    let targets = store
3243        .get_targets_for_skill(skill_id)
3244        .map_err(AppError::db)?;
3245
3246    for target in targets {
3247        if target.mode != "copy" {
3248            continue;
3249        }
3250
3251        // Recorded: this walks existing rows, so each path is one we wrote.
3252        // The row's mode is filtered to "copy" above, and sync_engine still
3253        // refuses if what is on disk no longer matches that record.
3254        sync_engine::sync_skill(
3255            &source,
3256            Path::new(&target.target_path),
3257            sync_engine::SyncMode::Copy,
3258            sync_engine::ReplacePolicy::Recorded {
3259                mode: target.mode.as_str(),
3260            },
3261        )
3262        .map_err(AppError::io)?;
3263
3264        let updated_target = SkillTargetRecord {
3265            synced_at: Some(chrono::Utc::now().timestamp_millis()),
3266            status: "ok".to_string(),
3267            last_error: None,
3268            // Refresh the hash so the startup freshness check (#153)
3269            // sees this resync as up-to-date instead of stale.
3270            source_hash: skill.content_hash.clone(),
3271            ..target
3272        };
3273        store.insert_target(&updated_target).map_err(AppError::db)?;
3274    }
3275
3276    Ok(())
3277}
3278
3279#[tauri::command]
3280pub async fn get_all_tags(store: State<'_, Arc<SkillStore>>) -> Result<Vec<String>, AppError> {
3281    let store = store.inner().clone();
3282    tauri::async_runtime::spawn_blocking(move || store.get_all_tags().map_err(AppError::db)).await?
3283}
3284
3285#[tauri::command]
3286pub async fn set_skill_tags(
3287    skill_id: String,
3288    tags: Vec<String>,
3289    store: State<'_, Arc<SkillStore>>,
3290) -> Result<(), AppError> {
3291    let store = store.inner().clone();
3292    tauri::async_runtime::spawn_blocking(move || set_skill_tags_internal(&store, &skill_id, &tags))
3293        .await?
3294}
3295
3296/// Shared implementation for GUI and CLI tag writes. Keeping the DB row and
3297/// its backup metadata under one repo lock prevents another process from
3298/// reindexing the half-written state between those two operations.
3299pub fn set_skill_tags_internal(
3300    store: &SkillStore,
3301    skill_id: &str,
3302    tags: &[String],
3303) -> Result<(), AppError> {
3304    let mut normalized = Vec::new();
3305    for tag in tags {
3306        let tag = tag.trim();
3307        if !tag.is_empty() && !normalized.iter().any(|existing| existing == tag) {
3308            normalized.push(tag.to_string());
3309        }
3310    }
3311
3312    sync_metadata::with_repo_lock("set skill tags", || {
3313        store.set_tags_for_skill(skill_id, &normalized)?;
3314        sync_metadata::ensure_skill_metadata_unlocked(store, skill_id)
3315    })
3316    .map_err(AppError::db)
3317}
3318
3319/// Globally rename a tag across all skills (used by the tag filter bar). If the
3320/// new name already exists, the tags are merged.
3321#[tauri::command]
3322pub async fn rename_tag(
3323    old_name: String,
3324    new_name: String,
3325    store: State<'_, Arc<SkillStore>>,
3326) -> Result<(), AppError> {
3327    let store = store.inner().clone();
3328    tauri::async_runtime::spawn_blocking(move || {
3329        rename_tag_internal(&store, &old_name, &new_name).map(|_| ())
3330    })
3331    .await?
3332}
3333
3334pub fn rename_tag_internal(
3335    store: &SkillStore,
3336    old_name: &str,
3337    new_name: &str,
3338) -> Result<Vec<String>, AppError> {
3339    let old_name = old_name.trim();
3340    let new_name = new_name.trim();
3341    if old_name.is_empty() || new_name.is_empty() {
3342        return Err(AppError::invalid_input("Tag name cannot be empty"));
3343    }
3344    if new_name == old_name {
3345        return Ok(Vec::new());
3346    }
3347    sync_metadata::with_repo_lock("rename tag", || {
3348        let affected = store.rename_tag(old_name, new_name)?;
3349        for skill_id in &affected {
3350            sync_metadata::ensure_skill_metadata_unlocked(store, skill_id)?;
3351        }
3352        Ok(affected)
3353    })
3354    .map_err(AppError::db)
3355}
3356
3357/// Globally delete a tag from all skills (used by the tag filter bar).
3358#[tauri::command]
3359pub async fn delete_tag(name: String, store: State<'_, Arc<SkillStore>>) -> Result<(), AppError> {
3360    let store = store.inner().clone();
3361    tauri::async_runtime::spawn_blocking(move || delete_tag_internal(&store, &name).map(|_| ()))
3362        .await?
3363}
3364
3365pub fn delete_tag_internal(store: &SkillStore, name: &str) -> Result<Vec<String>, AppError> {
3366    let name = name.trim();
3367    if name.is_empty() {
3368        return Err(AppError::invalid_input("Tag name cannot be empty"));
3369    }
3370    sync_metadata::with_repo_lock("delete tag", || {
3371        let affected = store.delete_tag(name)?;
3372        for skill_id in &affected {
3373            sync_metadata::ensure_skill_metadata_unlocked(store, skill_id)?;
3374        }
3375        Ok(affected)
3376    })
3377    .map_err(AppError::db)
3378}
3379
3380#[tauri::command]
3381pub async fn rename_skill(
3382    id: String,
3383    new_name: String,
3384    store: State<'_, Arc<SkillStore>>,
3385) -> Result<(), AppError> {
3386    let store = store.inner().clone();
3387    tauri::async_runtime::spawn_blocking(move || rename_skill_internal(&store, &id, &new_name))
3388        .await?
3389}
3390
3391pub fn rename_skill_internal(store: &SkillStore, id: &str, new_name: &str) -> Result<(), AppError> {
3392    crate::core::skill_rename::rename_skill(store, id, new_name).map_err(|error| {
3393        match error.downcast::<AppError>() {
3394            Ok(error) => error,
3395            Err(error) => AppError::io(format!("{error:#}")),
3396        }
3397    })
3398}
3399
3400#[tauri::command]
3401pub async fn cancel_install(
3402    key: String,
3403    cancel_registry: State<'_, Arc<InstallCancelRegistry>>,
3404) -> Result<bool, AppError> {
3405    Ok(cancel_registry.cancel(&key))
3406}
3407
3408#[derive(Debug, Serialize)]
3409pub struct BatchImportResult {
3410    pub imported: usize,
3411    pub skipped: usize,
3412    pub errors: Vec<String>,
3413}
3414
3415#[tauri::command]
3416pub async fn check_batch_import_conflicts(
3417    folder_path: String,
3418    store: State<'_, Arc<SkillStore>>,
3419) -> Result<Vec<String>, AppError> {
3420    let store = store.inner().clone();
3421    tauri::async_runtime::spawn_blocking(move || {
3422        let root = PathBuf::from(&folder_path);
3423        if !root.is_dir() {
3424            return Ok(vec![]);
3425        }
3426        let mut conflicts = Vec::new();
3427        let entries = std::fs::read_dir(&root)?;
3428        for entry in entries.flatten() {
3429            let path = entry.path();
3430            if is_valid_skill_dir(&path) {
3431                let name = skill_metadata::infer_skill_name(&path);
3432                let central_path = central_repo::skills_dir().join(&name);
3433                let central_str = central_path.to_string_lossy().to_string();
3434                if let Ok(Some(_)) = store.get_skill_by_central_path(&central_str) {
3435                    conflicts.push(name);
3436                }
3437            }
3438        }
3439        Ok(conflicts)
3440    })
3441    .await?
3442}
3443
3444#[tauri::command]
3445pub async fn batch_import_folder(
3446    folder_path: String,
3447    overwrite: Option<bool>,
3448    store: State<'_, Arc<SkillStore>>,
3449    app_handle: tauri::AppHandle,
3450) -> Result<BatchImportResult, AppError> {
3451    let store = store.inner().clone();
3452    tauri::async_runtime::spawn_blocking(move || {
3453        use tauri::Emitter;
3454
3455        let root = PathBuf::from(&folder_path);
3456        if !root.is_dir() {
3457            return Err(AppError::invalid_input("Selected path is not a directory"));
3458        }
3459
3460        // Collect valid skill subdirectories (depth=1)
3461        let mut skill_dirs: Vec<PathBuf> = Vec::new();
3462        let entries = std::fs::read_dir(&root)?;
3463        for entry in entries.flatten() {
3464            let path = entry.path();
3465            if is_valid_skill_dir(&path) {
3466                skill_dirs.push(path);
3467            }
3468        }
3469
3470        if skill_dirs.is_empty() {
3471            return Ok(BatchImportResult {
3472                imported: 0,
3473                skipped: 0,
3474                errors: vec![],
3475            });
3476        }
3477
3478        let total = skill_dirs.len();
3479        let mut imported = 0usize;
3480        let mut skipped = 0usize;
3481        let mut errors = Vec::new();
3482
3483        for (i, dir) in skill_dirs.iter().enumerate() {
3484            let name = skill_metadata::infer_skill_name(dir);
3485
3486            app_handle
3487                .emit(
3488                    "batch-import-progress",
3489                    serde_json::json!({
3490                        "current": i + 1,
3491                        "total": total,
3492                        "name": &name,
3493                    }),
3494                )
3495                .ok();
3496
3497            // Check if already imported by prospective central path
3498            let prospective_central = central_repo::skills_dir().join(&name);
3499            let central_str = prospective_central.to_string_lossy().to_string();
3500            if let Ok(Some(existing)) = store.get_skill_by_central_path(&central_str) {
3501                if overwrite.unwrap_or(false) {
3502                    let _ = store.delete_skill(&existing.id);
3503                    if prospective_central.exists() {
3504                        let _ = std::fs::remove_dir_all(&prospective_central);
3505                    }
3506                } else {
3507                    skipped += 1;
3508                    continue;
3509                }
3510            }
3511
3512            let install_result = (|| -> Result<String, AppError> {
3513                let _lock =
3514                    RepoLock::acquire_foreground("batch import skill").map_err(AppError::db)?;
3515                let result =
3516                    installer::install_from_local(dir, Some(&name)).map_err(AppError::io)?;
3517                let metadata = InstallSourceMetadata {
3518                    source_type: "local".to_string(),
3519                    source_ref: Some(dir.to_string_lossy().to_string()),
3520                    source_ref_resolved: None,
3521                    source_subpath: None,
3522                    source_branch: None,
3523                    source_revision: None,
3524                    source_agent: None,
3525                    remote_revision: None,
3526                    update_status: "local_only".to_string(),
3527                };
3528                store_installed_skill_unlocked(&store, &result, &metadata, None)
3529            })();
3530
3531            match install_result {
3532                Ok(_) => imported += 1,
3533                Err(e) => errors.push(format!("{}: {}", name, e)),
3534            }
3535        }
3536
3537        Ok(BatchImportResult {
3538            imported,
3539            skipped,
3540            errors,
3541        })
3542    })
3543    .await?
3544}
3545
3546fn remove_path_if_exists(path: &Path) -> Result<(), AppError> {
3547    if path.is_dir() {
3548        std::fs::remove_dir_all(path)?;
3549    } else if path.exists() {
3550        std::fs::remove_file(path)?;
3551    }
3552    Ok(())
3553}
3554
3555#[cfg(test)]
3556mod tests;