Skip to main content

agent_hub_runtime/core/
git_fetcher.rs

1use crate::core::central_repo;
2use crate::core::git_credentials;
3use crate::core::skill_metadata;
4mod cache_cleanup;
5mod cache_lock;
6use anyhow::{bail, Context, Result};
7pub use cache_cleanup::clear_repository_cache;
8use cache_lock::{lock_repo_cache, RepoCacheLock};
9use git2::{Direction, Repository};
10use sha2::{Digest, Sha256};
11use std::io::{BufReader, Read};
12use std::path::{Path, PathBuf};
13use std::process::{ChildStderr, Command, Stdio};
14use std::sync::atomic::{AtomicBool, Ordering};
15use std::sync::Arc;
16use std::time::{Duration, Instant};
17
18const CLONE_TIMEOUT_SECS: u64 = 300;
19
20/// Filename prefix shared by isolated install checkouts under `std::env::temp_dir()`.
21/// Used by both `materialize_cached_repo` (writer) and `validate_clone_temp_path` (reader).
22pub const CLONE_TEMP_PREFIX: &str = "agent-hub-clone-";
23
24/// Callback type for reporting clone progress messages to the UI.
25pub type ProgressCallback = Box<dyn Fn(&str) + Send>;
26
27/// Create a `Command` for git that hides the console window on Windows.
28fn git_command() -> Command {
29    #[allow(unused_mut)]
30    let mut cmd = Command::new("git");
31    #[cfg(target_os = "windows")]
32    {
33        use std::os::windows::process::CommandExt;
34        cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
35    }
36    cmd
37}
38
39#[derive(Debug, Clone)]
40pub struct ParsedGitSource {
41    pub original_url: String,
42    pub clone_url: String,
43    pub branch: Option<String>,
44    pub subpath: Option<String>,
45}
46
47pub fn parse_git_source(url: &str) -> ParsedGitSource {
48    let trimmed = url.trim().to_string();
49    let (clone_url, branch, subpath) = normalize_url(&trimmed);
50
51    ParsedGitSource {
52        original_url: trimmed,
53        clone_url,
54        branch,
55        subpath,
56    }
57}
58
59/// Validate that a URL uses an allowed scheme for git operations.
60/// Only permits `https://`, `http://`, `ssh://`, and SCP-style `git@` URLs,
61/// plus shorthand like `user/repo` (no scheme). Rejects everything else
62/// including `file://`, `ext::`, bare local paths, and UNC paths.
63pub fn validate_git_url(url: &str) -> Result<()> {
64    let trimmed = url.trim();
65    let lower = trimmed.to_lowercase();
66
67    // Explicitly allowed schemes
68    if lower.starts_with("https://")
69        || lower.starts_with("http://")
70        || lower.starts_with("ssh://")
71        || lower.starts_with("git@")
72    {
73        return Ok(());
74    }
75
76    // Allow GitHub/GitLab shorthand like "user/repo" or "user/repo.git"
77    if !trimmed.contains("://")
78        && !trimmed.contains('\\')
79        && !trimmed.starts_with('/')
80        && !trimmed.starts_with('.')
81        && !trimmed.starts_with('~')
82        && trimmed.contains('/')
83    {
84        let bytes = trimmed.as_bytes();
85        let is_windows_path =
86            bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
87        if !is_windows_path {
88            return Ok(());
89        }
90    }
91
92    anyhow::bail!("URL scheme not allowed: only https, http, ssh, and git@ are permitted");
93}
94
95/// Strip clone-irrelevant differences from a URL so equivalent forms share a
96/// cache slot and pass remote-equality checks. Specifically:
97/// - Trims whitespace and a trailing `/`.
98/// - Drops a trailing `.git` suffix (servers accept both forms).
99///
100/// This is intentionally conservative — no case folding, no scheme rewriting,
101/// no path normalization beyond the suffix — so non-GitHub hosts that treat
102/// paths case-sensitively or distinguish schemes are unaffected.
103fn canonicalize_clone_url(url: &str) -> String {
104    let trimmed = url.trim().trim_end_matches('/');
105    trimmed.strip_suffix(".git").unwrap_or(trimmed).to_string()
106}
107
108/// Compute a stable cache directory name for a given clone URL. Hashes the
109/// canonical form so e.g. `https://github.com/x/y` and `https://github.com/x/y.git`
110/// share the same cache slot.
111fn repo_cache_dir(url: &str) -> PathBuf {
112    repo_cache_dir_for(url, false)
113}
114
115/// Cache slot for a URL. A subpath-scoped checkout gets its own `-sparse` slot
116/// rather than sharing the full one, because the two are not interchangeable:
117/// the flows that need a whole tree (repo preview with no subpath, the skills.sh
118/// locator search, `resolve_skill_dir`'s repo-wide fallback) must never be handed
119/// a checkout holding one directory. A repo used both ways simply keeps two
120/// caches, and the full path keeps behaving exactly as it did before.
121fn repo_cache_dir_for(url: &str, sparse: bool) -> PathBuf {
122    let canonical = canonicalize_clone_url(url);
123    let mut hasher = Sha256::new();
124    hasher.update(canonical.as_bytes());
125    let hash = format!("{:x}", hasher.finalize());
126    let short = &hash[..16];
127    let name = if sparse {
128        format!("{short}-sparse")
129    } else {
130        short.to_string()
131    };
132    central_repo::cache_dir().join("repos").join(name)
133}
134
135/// Upper bound on the whole repo cache.
136///
137/// A backstop, not a quota. Nothing ever deleted a cache slot before, so a
138/// library built from many repositories accumulated one checkout per repository
139/// and kept it forever — measured at 569 MB across 48 repositories on an
140/// ordinary machine, the oldest untouched for four months.
141const REPO_CACHE_LIMIT_BYTES: u64 = 1024 * 1024 * 1024;
142
143/// Delete least-recently-used cache slots until the cache is back under the limit.
144///
145/// Called only where a slot is about to be cloned fresh. Refreshing an existing
146/// slot adds a delta; a new repository adds a whole checkout, so that is where the
147/// growth comes from — and it keeps a batch update from paying for the walk once
148/// per repository (the walk is ~0.8s over a 569 MB cache).
149///
150/// `keep` is the slot the caller is about to write. A slot another install holds
151/// is skipped rather than waited for: deleting a checkout from under a running
152/// install would break it. The lock *file* is deliberately left behind — unlinking
153/// it while someone waits on it would let two installs each hold a lock on a
154/// different inode for the same slot.
155fn prune_repo_cache(keep: &Path) {
156    prune_cache_root(
157        &central_repo::cache_dir().join("repos"),
158        keep,
159        REPO_CACHE_LIMIT_BYTES,
160    )
161}
162
163/// Takes its root and limit rather than reading them from the central config, so
164/// it is a plain function of the directory in front of it — testable without
165/// touching process-global state that parallel tests would fight over.
166fn prune_cache_root(root: &Path, keep: &Path, limit: u64) {
167    let Ok(entries) = std::fs::read_dir(root) else {
168        return;
169    };
170
171    let mut slots: Vec<(PathBuf, u64, std::time::SystemTime)> = Vec::new();
172    let mut total: u64 = 0;
173    for entry in entries.flatten() {
174        let path = entry.path();
175        if !path.is_dir() {
176            continue;
177        }
178        let (size, used) = slot_stats(&path);
179        total = total.saturating_add(size);
180        slots.push((path, size, used));
181    }
182
183    slots.sort_by_key(|(_, _, used)| *used);
184    for (path, size, _) in slots {
185        if total <= limit {
186            break;
187        }
188        if path == keep {
189            continue;
190        }
191        let Ok(_lock) = RepoCacheLock::try_acquire(&path) else {
192            continue;
193        };
194        if std::fs::remove_dir_all(&path).is_ok() {
195            log::info!("pruned repo cache slot {}", path.display());
196            total = total.saturating_sub(size);
197        }
198    }
199}
200
201/// Bytes in a cache slot, and when anything inside it was last written.
202///
203/// The recency half cannot come from the slot directory's own mtime: a fetch
204/// writes objects deep inside `.git`, never in the slot root, so that mtime stays
205/// at creation time and "least recently used" would silently mean "oldest",
206/// evicting a repository that is updated weekly before one nobody has touched
207/// since it was cloned. The size walk visits every file anyway, so the real
208/// answer is free.
209fn slot_stats(dir: &Path) -> (u64, std::time::SystemTime) {
210    let mut size = 0u64;
211    let mut newest = std::time::UNIX_EPOCH;
212    for entry in walkdir::WalkDir::new(dir).into_iter().flatten() {
213        let Ok(meta) = entry.metadata() else {
214            continue;
215        };
216        if !meta.is_file() {
217            continue;
218        }
219        size = size.saturating_add(meta.len());
220        if let Ok(modified) = meta.modified() {
221            newest = newest.max(modified);
222        }
223    }
224    (size, newest)
225}
226
227fn materialize_cached_repo(cached: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<PathBuf> {
228    let temp_dir =
229        std::env::temp_dir().join(format!("{CLONE_TEMP_PREFIX}{}", uuid::Uuid::new_v4()));
230
231    // `git clone --local` with default hardlinks: cache objects are content-addressed
232    // and immutable, the flock above prevents the cache from being mutated mid-clone,
233    // and any later cache deletion leaves linked objects intact in the temp checkout.
234    let child = git_command()
235        .arg("clone")
236        .arg("--local")
237        .arg(cached)
238        .arg(&temp_dir)
239        .stdout(Stdio::null())
240        .stderr(Stdio::piped())
241        .spawn();
242
243    let mut system_git_stderr: Option<String> = None;
244    if let Ok(mut child) = child {
245        let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
246        loop {
247            if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
248                let _ = child.kill();
249                let _ = child.wait();
250                let _ = std::fs::remove_dir_all(&temp_dir);
251                anyhow::bail!("Installation cancelled");
252            }
253            match child.try_wait() {
254                Ok(Some(status)) => {
255                    if status.success() {
256                        return Ok(temp_dir);
257                    }
258                    let mut stderr_buf = String::new();
259                    if let Some(mut stderr) = child.stderr.take() {
260                        let _ = stderr.read_to_string(&mut stderr_buf);
261                    }
262                    let _ = std::fs::remove_dir_all(&temp_dir);
263                    system_git_stderr = Some(stderr_buf);
264                    break;
265                }
266                Ok(None) => {
267                    if Instant::now() > deadline {
268                        let _ = child.kill();
269                        let _ = child.wait();
270                        let _ = std::fs::remove_dir_all(&temp_dir);
271                        anyhow::bail!(
272                            "Local clone from cache timed out after {}s",
273                            CLONE_TIMEOUT_SECS
274                        );
275                    }
276                    std::thread::sleep(Duration::from_millis(100));
277                }
278                Err(_) => {
279                    let _ = std::fs::remove_dir_all(&temp_dir);
280                    break;
281                }
282            }
283        }
284    }
285
286    let source = cached
287        .to_str()
288        .ok_or_else(|| anyhow::anyhow!("Cached repo path is not valid UTF-8"))?;
289    match git2::build::RepoBuilder::new().clone(source, &temp_dir) {
290        Ok(_) => Ok(temp_dir),
291        Err(err) => {
292            let _ = std::fs::remove_dir_all(&temp_dir);
293            let detail = system_git_stderr
294                .filter(|s| !s.trim().is_empty())
295                .map(|s| format!(" (system git: {})", s.trim()))
296                .unwrap_or_default();
297            anyhow::bail!(
298                "Failed to create install checkout from cache: {}{}",
299                err,
300                detail
301            )
302        }
303    }
304}
305
306/// Try to update an existing cached repo via fetch + reset.
307/// Returns Ok(true) if the cache was reused, Ok(false) if it should be re-cloned.
308fn try_update_cached_repo(
309    cached: &Path,
310    url: &str,
311    branch: Option<&str>,
312    proxy_url: Option<&str>,
313    cancel: Option<&Arc<AtomicBool>>,
314    on_progress: &Option<ProgressCallback>,
315) -> Result<bool> {
316    if !cached.join(".git").exists() {
317        return Ok(false);
318    }
319
320    // Verify the remote URL still matches.
321    let current_remote = {
322        let mut cmd = git_command();
323        cmd.arg("-C")
324            .arg(cached)
325            .args(["remote", "get-url", "origin"]);
326        let output = cmd.output().ok();
327        output
328            .filter(|o| o.status.success())
329            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
330    };
331    let remote_matches = current_remote
332        .as_deref()
333        .is_some_and(|r| canonicalize_clone_url(r) == canonicalize_clone_url(url));
334    if !remote_matches {
335        // URL changed — discard cache.
336        let _ = std::fs::remove_dir_all(cached);
337        return Ok(false);
338    }
339
340    if let Some(cb) = on_progress {
341        cb("Updating cached repository…");
342    }
343
344    // `-c` is a *global* git option: `git fetch -c key=value` is rejected with
345    // "unknown switch `c`", so it has to precede the subcommand. It used to sit
346    // after `fetch`, which made every cache refresh fail outright whenever a
347    // proxy was configured — those users re-cloned the whole repository on every
348    // install and update instead of ever reusing the cache.
349    let mut fetch_cmd = git_command();
350    fetch_cmd.arg("-C").arg(cached);
351    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
352        fetch_cmd.arg("-c").arg(format!("http.proxy={proxy}"));
353        fetch_cmd.arg("-c").arg(format!("https.proxy={proxy}"));
354    }
355    fetch_cmd.arg("fetch").arg("--depth").arg("1");
356    fetch_cmd.arg("origin");
357    if let Some(branch) = branch {
358        fetch_cmd.arg(branch);
359    }
360    fetch_cmd.stdout(Stdio::null()).stderr(Stdio::null());
361
362    let child = fetch_cmd.spawn();
363    if let Ok(mut child) = child {
364        let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
365        loop {
366            if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
367                let _ = child.kill();
368                let _ = child.wait();
369                anyhow::bail!("Installation cancelled");
370            }
371            match child.try_wait() {
372                Ok(Some(status)) => {
373                    if !status.success() {
374                        // Fetch failed — discard cache and re-clone.
375                        let _ = std::fs::remove_dir_all(cached);
376                        return Ok(false);
377                    }
378                    break;
379                }
380                Ok(None) => {
381                    if Instant::now() > deadline {
382                        let _ = child.kill();
383                        let _ = child.wait();
384                        let _ = std::fs::remove_dir_all(cached);
385                        return Ok(false);
386                    }
387                    std::thread::sleep(Duration::from_millis(200));
388                }
389                Err(_) => {
390                    let _ = std::fs::remove_dir_all(cached);
391                    return Ok(false);
392                }
393            }
394        }
395    } else {
396        let _ = std::fs::remove_dir_all(cached);
397        return Ok(false);
398    }
399
400    // Reset to the fetched HEAD. A branch has a remote-tracking ref, but a tag
401    // does not — `origin/<tag>` is not a revision — so fall back to FETCH_HEAD,
402    // which the fetch above just wrote. Without the fallback a tag source never
403    // reuses its cache and silently re-clones on every check.
404    let targets: Vec<String> = match branch {
405        Some(b) => vec![format!("origin/{b}"), "FETCH_HEAD".to_string()],
406        None => vec!["origin/HEAD".to_string()],
407    };
408    // Against a full cache this reset is local and returns immediately. Against a
409    // sparse cache it is a partial clone, so writing the worktree lazily fetches
410    // the blobs it needs — which is why it runs under the same timeout and cancel
411    // flag as the fetch above instead of blocking forever on a dead network.
412    let mut cancelled = false;
413    let reset_ok = targets.iter().any(|target| {
414        match run_git_watched_at(
415            cached,
416            &["reset", "--hard", target],
417            proxy_url,
418            cancel,
419            &None,
420        ) {
421            Ok(()) => true,
422            Err(e) => {
423                cancelled |= is_cancellation(&e);
424                false
425            }
426        }
427    });
428    // A cancellation is not a broken cache. Collapsed into `reset_ok == false` it
429    // reads as "every target failed", and the cache below gets deleted — so
430    // cancelling an install would silently cost the user the next full download.
431    // The fetch above already treats cancellation this way; so must this.
432    if cancelled {
433        bail!("Installation cancelled");
434    }
435    match reset_ok {
436        true => Ok(true),
437        false => {
438            let _ = std::fs::remove_dir_all(cached);
439            Ok(false)
440        }
441    }
442}
443
444/// Filter out SSH informational warnings from stderr lines.
445fn is_ssh_warning(line: &str) -> bool {
446    let trimmed = line.trim().trim_start_matches("** ");
447    trimmed.starts_with("WARNING:")
448        || trimmed.starts_with("This session may")
449        || trimmed.starts_with("The server may")
450        || trimmed.starts_with("See https://openssh.com")
451}
452
453fn spawn_stderr_collector(
454    stderr: Option<ChildStderr>,
455    forward_progress: bool,
456) -> (
457    std::sync::mpsc::Receiver<String>,
458    std::thread::JoinHandle<String>,
459) {
460    let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
461    let stderr_thread = std::thread::spawn(move || {
462        let mut collected = String::new();
463        let Some(stderr) = stderr else {
464            return collected;
465        };
466
467        let mut reader = BufReader::new(stderr);
468        let mut line = Vec::new();
469        let mut byte = [0u8; 1];
470
471        loop {
472            match reader.read(&mut byte) {
473                Ok(0) => {
474                    if !line.is_empty() {
475                        emit_stderr_line(&line, forward_progress, &stderr_tx, &mut collected);
476                    }
477                    break;
478                }
479                Ok(_) if byte[0] == b'\n' || byte[0] == b'\r' => {
480                    if !line.is_empty() {
481                        emit_stderr_line(&line, forward_progress, &stderr_tx, &mut collected);
482                        line.clear();
483                    }
484                }
485                Ok(_) => line.push(byte[0]),
486                Err(_) => break,
487            }
488        }
489
490        collected
491    });
492
493    (stderr_rx, stderr_thread)
494}
495
496fn emit_stderr_line(
497    line: &[u8],
498    forward_progress: bool,
499    stderr_tx: &std::sync::mpsc::Sender<String>,
500    collected: &mut String,
501) {
502    let line = String::from_utf8_lossy(line).to_string();
503    if !is_ssh_warning(&line) {
504        collected.push_str(&line);
505        collected.push('\n');
506    }
507    if forward_progress {
508        let _ = stderr_tx.send(line);
509    }
510}
511
512pub fn clone_repo_ref(
513    url: &str,
514    branch: Option<&str>,
515    cancel: Option<&Arc<AtomicBool>>,
516    proxy_url: Option<&str>,
517) -> Result<PathBuf> {
518    clone_repo_ref_with_progress(url, branch, cancel, proxy_url, None)
519}
520
521pub fn clone_repo_ref_with_progress(
522    url: &str,
523    branch: Option<&str>,
524    cancel: Option<&Arc<AtomicBool>>,
525    proxy_url: Option<&str>,
526    on_progress: Option<ProgressCallback>,
527) -> Result<PathBuf> {
528    clone_repo_ref_scoped(url, branch, None, cancel, proxy_url, on_progress)
529}
530
531/// Clone `url`, narrowed to `subpath` when one is known.
532///
533/// With a subpath this fetches only that directory (`--filter=blob:none` plus a
534/// sparse-checkout), which is the difference between downloading a repository and
535/// downloading one skill — measured at 15 MB versus 472 KB for a single skill out
536/// of `anthropics/skills`. Every way that can fail — a server with
537/// `uploadpack.allowFilter` off, a git too old to read the sparse arguments the
538/// way we mean them, a subpath that upstream has since moved — falls back to the
539/// full checkout, so the narrow path can only ever be faster, never the reason an
540/// install stops working.
541///
542/// Pass `None` for `subpath` whenever the caller needs to search the repository
543/// rather than read one known directory.
544pub fn clone_repo_ref_scoped(
545    url: &str,
546    branch: Option<&str>,
547    subpath: Option<&str>,
548    cancel: Option<&Arc<AtomicBool>>,
549    proxy_url: Option<&str>,
550    on_progress: Option<ProgressCallback>,
551) -> Result<PathBuf> {
552    if let Some(subpath) = sparse_pattern(subpath) {
553        match clone_repo_sparse(url, branch, &subpath, cancel, proxy_url, &on_progress) {
554            Ok(dir) => return Ok(dir),
555            Err(e) if is_cancellation(&e) => return Err(e),
556            Err(e) => {
557                log::info!(
558                    "narrow clone of '{subpath}' from {url} unavailable, using a full checkout: {e}"
559                );
560            }
561        }
562    }
563
564    clone_repo_full(url, branch, cancel, proxy_url, on_progress)
565}
566
567/// Whether an error is a user cancellation rather than a fault worth retrying
568/// differently.
569fn is_cancellation(err: &anyhow::Error) -> bool {
570    let message = err.to_string();
571    message.contains("cancelled") || message.contains("canceled")
572}
573
574/// Turn a stored subpath into a sparse-checkout pattern, or `None` when it is not
575/// one we are willing to hand to git.
576///
577/// The pattern given to git must select the same directory the caller will later
578/// `join` onto the checkout. Tidying the string here — trimming, swapping
579/// separators — would break that: on unix a trailing space and a backslash are
580/// both legal parts of a directory name, so `skills/foo ` would narrow to
581/// `skills/foo`, pass the guard, and then leave the caller reading a directory the
582/// checkout does not contain, with no failure to fall back on. So nothing is
583/// rewritten; a path that is not already clean simply takes the full checkout.
584///
585/// Windows is the one exception, and only because `\` cannot be part of a name
586/// there — `content_hash` normalizes separators under the same `cfg` for the same
587/// reason.
588fn sparse_pattern(subpath: Option<&str>) -> Option<String> {
589    let raw = subpath?;
590    #[cfg(windows)]
591    let raw = &raw.replace('\\', "/");
592
593    if raw.is_empty()
594        || raw != raw.trim()
595        || raw.starts_with('/')
596        || raw.ends_with('/')
597        || raw.contains('\\')
598    {
599        return None;
600    }
601    if raw
602        .split('/')
603        .any(|segment| segment.is_empty() || segment == "." || segment == "..")
604    {
605        return None;
606    }
607    Some(raw.to_string())
608}
609
610/// Clone only `subpath` out of `url`, reusing (and widening) the sparse cache slot.
611fn clone_repo_sparse(
612    url: &str,
613    branch: Option<&str>,
614    subpath: &str,
615    cancel: Option<&Arc<AtomicBool>>,
616    proxy_url: Option<&str>,
617    on_progress: &Option<ProgressCallback>,
618) -> Result<PathBuf> {
619    let cached_dir = repo_cache_dir_for(url, true);
620    let _cache_lock = lock_repo_cache(&cached_dir, on_progress)?;
621
622    // One slot serves every skill from this repo: the objects are what is
623    // expensive, and they are shared. The lock holds until this call's copy is
624    // taken, so a later install re-scoping the worktree cannot disturb it.
625    let reusable = cached_dir.exists()
626        && try_update_cached_repo(&cached_dir, url, branch, proxy_url, cancel, on_progress)?;
627
628    if !reusable {
629        let _ = std::fs::remove_dir_all(&cached_dir);
630        prune_repo_cache(&cached_dir);
631        sparse_clone_into(&cached_dir, url, branch, cancel, proxy_url, on_progress).inspect_err(
632            |_| {
633                let _ = std::fs::remove_dir_all(&cached_dir);
634            },
635        )?;
636    }
637
638    set_sparse_scope(&cached_dir, subpath, cancel, proxy_url, on_progress)?;
639
640    // `sparse-checkout set` succeeds on a path the repository does not have — it
641    // just leaves that path absent, keeping the root files cone mode always
642    // includes. So the result has to be inspected rather than trusted.
643    if !sparse_checkout_holds_a_skill(&cached_dir, subpath) {
644        bail!("'{subpath}' is not a skill directory in the narrow checkout of {url}");
645    }
646
647    copy_cached_repo(&cached_dir, cancel)
648}
649
650fn sparse_clone_into(
651    dest: &Path,
652    url: &str,
653    branch: Option<&str>,
654    cancel: Option<&Arc<AtomicBool>>,
655    proxy_url: Option<&str>,
656    on_progress: &Option<ProgressCallback>,
657) -> Result<()> {
658    if let Some(cb) = on_progress {
659        cb("Fetching only the requested skill directory…");
660    }
661    if let Some(parent) = dest.parent() {
662        std::fs::create_dir_all(parent)?;
663    }
664
665    let mut command = git_command();
666    command
667        .arg("clone")
668        .arg("--filter=blob:none")
669        .arg("--no-checkout")
670        .arg("--sparse")
671        .arg("--depth")
672        .arg("1");
673    // `git clone -c` applies the value before the initial fetch, so unlike
674    // `git fetch` this really does route the clone through the proxy.
675    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
676        command.arg("-c").arg(format!("http.proxy={proxy}"));
677        command.arg("-c").arg(format!("https.proxy={proxy}"));
678    }
679    if let Some(branch) = branch {
680        command.arg("--branch").arg(branch);
681    }
682    command.arg("--progress").arg(url).arg(dest);
683    run_git_watched(command, cancel, on_progress)
684}
685
686/// Point the cache's sparse checkout at `subpath` and materialize it.
687///
688/// `set` rather than `add`: fetched objects stay in the cache either way, so
689/// carrying every previously requested skill in the worktree buys nothing.
690fn set_sparse_scope(
691    cached: &Path,
692    subpath: &str,
693    cancel: Option<&Arc<AtomicBool>>,
694    proxy_url: Option<&str>,
695    on_progress: &Option<ProgressCallback>,
696) -> Result<()> {
697    // `--cone` is explicit because cone mode is only the default on newer git,
698    // and the non-cone reading of the same argument is a gitignore-style pattern
699    // that would not bring the directory's contents with it.
700    run_git_watched_at(
701        cached,
702        &["sparse-checkout", "set", "--cone", subpath],
703        proxy_url,
704        cancel,
705        on_progress,
706    )?;
707    run_git_watched_at(cached, &["checkout"], proxy_url, cancel, on_progress)
708}
709
710/// Whether the narrow checkout produced a skill at exactly `subpath`.
711///
712/// Deliberately strict: a directory that merely *contains* skills is refused, so
713/// a container subpath takes the full checkout. That is not conservatism for its
714/// own sake — `resolve_skill_dir` accepts a stored path only when the path itself
715/// is a skill, and otherwise searches the whole repository for the locator id. Let
716/// a container through here and that search runs against a tree holding one
717/// directory, which does not fail cleanly: it can resolve a *different* skill that
718/// happens to be inside the narrow scope. Refusing containers keeps the repo-wide
719/// search on a repo-wide checkout, which is the only tree it is correct on.
720fn sparse_checkout_holds_a_skill(cached: &Path, subpath: &str) -> bool {
721    skill_metadata::is_valid_skill_dir(&cached.join(subpath))
722}
723
724/// Materialize an install checkout from a sparse cache by copying it.
725///
726/// `git clone --local` cannot be used here. Cloning from a partial clone asks the
727/// source to serve objects it does not have, and git aborts with "could not fetch
728/// <oid> from promisor remote", taking the whole install with it. A plain copy
729/// keeps the promisor and sparse configuration intact, and is cheap precisely
730/// because a sparse cache holds one skill instead of a repository.
731fn copy_cached_repo(cached: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<PathBuf> {
732    let temp_dir =
733        std::env::temp_dir().join(format!("{CLONE_TEMP_PREFIX}{}", uuid::Uuid::new_v4()));
734    if let Err(e) = copy_dir_contents(cached, &temp_dir, cancel) {
735        let _ = std::fs::remove_dir_all(&temp_dir);
736        return Err(e);
737    }
738    detach_from_promisor(&temp_dir);
739    Ok(temp_dir)
740}
741
742/// Cut an install checkout loose from the promisor remote it was copied from.
743///
744/// This is the boundary that keeps the narrow clone from becoming a permanent tax
745/// on everyone who touches this code. A partial clone carries IOUs: a git command
746/// that reaches an object we never fetched silently becomes a network round trip,
747/// which can hang, needs a proxy, and needs credentials. Callers run git against
748/// the checkout we hand back — `checkout_revision`, `get_head_revision`, whatever
749/// gets added next — and nothing in the type system would tell them that.
750///
751/// Dropping the config makes a missing object an immediate error instead, exactly
752/// as it has always been in a shallow full checkout.
753///
754/// The precise claim, because a broader one would be wrong: no git command against
755/// the returned checkout fetches an object *behind the caller's back*. An explicit
756/// `fetch`/`pull`/`ls-remote` still reaches origin, whose URL the copy keeps — no
757/// caller does that today, and one that started would be doing something visibly
758/// network-shaped. What this rules out is the invisible case, which is the one
759/// nobody would think to instrument.
760fn detach_from_promisor(repo_dir: &Path) {
761    // Three keys, because git registers a promisor remote from *any* of them.
762    // `git clone --filter` writes the two `remote.origin.*` ones and, since 2.25,
763    // not `extensions.partialClone` — but leaving that one out would mean the set
764    // is complete only for the git that happens to write our caches, and getting
765    // it wrong restores lazy fetching silently.
766    for key in [
767        "remote.origin.promisor",
768        "remote.origin.partialclonefilter",
769        "extensions.partialClone",
770    ] {
771        let _ = git_command()
772            .arg("-C")
773            .arg(repo_dir)
774            .args(["config", "--unset", key])
775            .stdout(Stdio::null())
776            .stderr(Stdio::null())
777            .status();
778    }
779}
780
781/// Recursive copy that skips symlinks, so it can never follow a link out of the
782/// cache. Nothing downstream misses them: the installer drops symlinks, and
783/// `content_hash` counts only regular files.
784fn copy_dir_contents(src: &Path, dst: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<()> {
785    if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
786        bail!("Installation cancelled");
787    }
788    std::fs::create_dir_all(dst).with_context(|| format!("Failed to create {}", dst.display()))?;
789    for entry in std::fs::read_dir(src)? {
790        let entry = entry?;
791        let file_type = entry.file_type()?;
792        if file_type.is_symlink() {
793            continue;
794        }
795        let target = dst.join(entry.file_name());
796        if file_type.is_dir() {
797            copy_dir_contents(&entry.path(), &target, cancel)?;
798        } else {
799            std::fs::copy(entry.path(), &target).with_context(|| {
800                format!(
801                    "Failed to copy {} to {}",
802                    entry.path().display(),
803                    target.display()
804                )
805            })?;
806        }
807    }
808    Ok(())
809}
810
811/// `git -C <dir> <args…>` under the shared cancel/timeout policy.
812///
813/// These are not local-only commands. In a partial clone both `sparse-checkout`
814/// and `checkout` fetch the blobs they are about to write, so they block on the
815/// network exactly like a clone does and have to be just as cancellable — the
816/// reason this exists rather than a plain `Command::output()`.
817///
818/// The proxy is passed per invocation rather than read from the cache's config:
819/// `git clone -c` persisted whatever proxy was in effect when the cache was
820/// created, and a command line `-c` is what lets a since-changed proxy win over
821/// that stale value.
822fn run_git_watched_at(
823    dir: &Path,
824    args: &[&str],
825    proxy_url: Option<&str>,
826    cancel: Option<&Arc<AtomicBool>>,
827    on_progress: &Option<ProgressCallback>,
828) -> Result<()> {
829    let mut command = git_command();
830    command.arg("-C").arg(dir);
831    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
832        command.arg("-c").arg(format!("http.proxy={proxy}"));
833        command.arg("-c").arg(format!("https.proxy={proxy}"));
834    }
835    command.args(args);
836    run_git_watched(command, cancel, on_progress)
837}
838
839/// Run a git subprocess under the shared cancel/timeout policy, forwarding its
840/// stderr to `on_progress`.
841///
842/// The full-clone loop below is deliberately left inline rather than reshaped to
843/// call this: it has no end-to-end test coverage, so the safe move is to add a
844/// path beside it, not to rewrite it.
845fn run_git_watched(
846    mut command: Command,
847    cancel: Option<&Arc<AtomicBool>>,
848    on_progress: &Option<ProgressCallback>,
849) -> Result<()> {
850    let mut child = command
851        .stdout(Stdio::null())
852        .stderr(Stdio::piped())
853        .spawn()
854        .context("Failed to start git")?;
855
856    let (stderr_rx, stderr_thread) =
857        spawn_stderr_collector(child.stderr.take(), on_progress.is_some());
858    let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
859
860    loop {
861        if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
862            let _ = child.kill();
863            let _ = child.wait();
864            bail!("Installation cancelled");
865        }
866
867        if let Some(ref cb) = on_progress {
868            while let Ok(line) = stderr_rx.try_recv() {
869                if !is_ssh_warning(&line) && !line.trim().is_empty() {
870                    cb(&line);
871                }
872            }
873        }
874
875        match child.try_wait() {
876            Ok(Some(status)) => {
877                let collected = stderr_thread.join().unwrap_or_default();
878                if status.success() {
879                    return Ok(());
880                }
881                bail!("git exited with {}: {}", status, collected.trim());
882            }
883            Ok(None) => {
884                if Instant::now() > deadline {
885                    let _ = child.kill();
886                    let _ = child.wait();
887                    bail!("git timed out after {}s", CLONE_TIMEOUT_SECS);
888                }
889                std::thread::sleep(Duration::from_millis(100));
890            }
891            Err(e) => {
892                let _ = child.kill();
893                let _ = child.wait();
894                bail!("Failed to wait for git: {e}")
895            }
896        }
897    }
898}
899
900fn clone_repo_full(
901    url: &str,
902    branch: Option<&str>,
903    cancel: Option<&Arc<AtomicBool>>,
904    proxy_url: Option<&str>,
905    on_progress: Option<ProgressCallback>,
906) -> Result<PathBuf> {
907    let cached_dir = repo_cache_dir(url);
908    let _cache_lock = lock_repo_cache(&cached_dir, &on_progress)?;
909
910    // Try cached repo first.
911    if cached_dir.exists() {
912        match try_update_cached_repo(&cached_dir, url, branch, proxy_url, cancel, &on_progress) {
913            Ok(true) => return materialize_cached_repo(&cached_dir, cancel),
914            Ok(false) => { /* cache invalid, fall through to clone */ }
915            Err(e) => {
916                // Propagate cancellation.
917                if e.to_string().contains("cancelled") || e.to_string().contains("canceled") {
918                    return Err(e);
919                }
920                // Otherwise fall through to clone.
921            }
922        }
923    }
924
925    // Remove any leftover partial clone.
926    let _ = std::fs::remove_dir_all(&cached_dir);
927    prune_repo_cache(&cached_dir);
928
929    let timeout = Duration::from_secs(CLONE_TIMEOUT_SECS);
930    let mut system_git_stderr: Option<String> = None;
931
932    // Try system git first (faster, supports SSH).
933    let mut command = git_command();
934    command.arg("clone").arg("--depth").arg("1");
935    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
936        command.arg("-c").arg(format!("http.proxy={proxy}"));
937        command.arg("-c").arg(format!("https.proxy={proxy}"));
938    }
939    if let Some(branch) = branch {
940        command.arg("--branch").arg(branch);
941    }
942    command.arg("--progress"); // Force progress output to stderr.
943    let child = command
944        .arg(url)
945        .arg(&cached_dir)
946        .stdout(Stdio::null())
947        .stderr(Stdio::piped())
948        .spawn();
949
950    if let Ok(mut child) = child {
951        let (stderr_rx, stderr_thread) =
952            spawn_stderr_collector(child.stderr.take(), on_progress.is_some());
953
954        let deadline = Instant::now() + timeout;
955        loop {
956            if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
957                let _ = child.kill();
958                let _ = child.wait();
959                let _ = std::fs::remove_dir_all(&cached_dir);
960                anyhow::bail!("Installation cancelled");
961            }
962
963            // Forward progress lines from stderr thread.
964            if let Some(ref cb) = on_progress {
965                while let Ok(line) = stderr_rx.try_recv() {
966                    if !is_ssh_warning(&line) && !line.trim().is_empty() {
967                        cb(&line);
968                    }
969                }
970            }
971
972            match child.try_wait() {
973                Ok(Some(status)) => {
974                    let collected = stderr_thread.join().unwrap_or_default();
975                    if status.success() {
976                        return materialize_cached_repo(&cached_dir, cancel);
977                    }
978                    system_git_stderr = Some(collected);
979                    // Clean up failed clone.
980                    let _ = std::fs::remove_dir_all(&cached_dir);
981                    break; // fall through to git2
982                }
983                Ok(None) => {
984                    if Instant::now() > deadline {
985                        let _ = child.kill();
986                        let _ = child.wait();
987                        let _ = std::fs::remove_dir_all(&cached_dir);
988                        anyhow::bail!(
989                            "Git clone timed out after {}s — check your network connection",
990                            CLONE_TIMEOUT_SECS
991                        );
992                    }
993                    std::thread::sleep(Duration::from_millis(200));
994                }
995                Err(_) => {
996                    let _ = std::fs::remove_dir_all(&cached_dir);
997                    break;
998                }
999            }
1000        }
1001    }
1002
1003    // Fallback to git2 with timeout and shallow clone.
1004    if let Some(ref cb) = on_progress {
1005        cb("Trying alternative clone method…");
1006    }
1007
1008    let mut builder = git2::build::RepoBuilder::new();
1009    if let Some(branch) = branch {
1010        builder.branch(branch);
1011    }
1012
1013    let cancel_clone = cancel.cloned();
1014    let clone_deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
1015    let mut callbacks = git2::RemoteCallbacks::new();
1016
1017    let progress_for_cb: Option<Arc<std::sync::Mutex<ProgressCallback>>> =
1018        on_progress.map(|cb| Arc::new(std::sync::Mutex::new(cb)));
1019    let progress_for_transfer = progress_for_cb.clone();
1020
1021    callbacks.transfer_progress(move |stats| {
1022        if let Some(ref c) = cancel_clone {
1023            if c.load(Ordering::SeqCst) {
1024                return false;
1025            }
1026        }
1027        if Instant::now() > clone_deadline {
1028            return false;
1029        }
1030        if let Some(ref cb) = progress_for_transfer {
1031            if let Ok(cb) = cb.lock() {
1032                let msg = format!(
1033                    "Receiving objects: {}/{} ({:.1} KB)",
1034                    stats.received_objects(),
1035                    stats.total_objects(),
1036                    stats.received_bytes() as f64 / 1024.0
1037                );
1038                cb(&msg);
1039            }
1040        }
1041        true
1042    });
1043
1044    git_credentials::install_git2_credentials(&mut callbacks, url);
1045    let mut fetch_opts = git2::FetchOptions::new();
1046    fetch_opts.remote_callbacks(callbacks);
1047    fetch_opts.depth(1);
1048    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1049        let mut proxy_opts = git2::ProxyOptions::new();
1050        proxy_opts.url(proxy);
1051        fetch_opts.proxy_options(proxy_opts);
1052    }
1053    builder.fetch_options(fetch_opts);
1054
1055    match builder.clone(url, &cached_dir) {
1056        Ok(_) => materialize_cached_repo(&cached_dir, cancel),
1057        Err(git2_err) => {
1058            // The pinned ref may be a tag, which the clone above cannot check
1059            // out. Retry in the shape that works before giving up.
1060            if let Some(pinned) = branch {
1061                if clone_tag_with_git2(url, pinned, &cached_dir, cancel, proxy_url).is_ok() {
1062                    return materialize_cached_repo(&cached_dir, cancel);
1063                }
1064            }
1065            let _ = std::fs::remove_dir_all(&cached_dir);
1066            // Include system git stderr in the error if available.
1067            let detail = system_git_stderr
1068                .filter(|s| !s.trim().is_empty())
1069                .map(|s| format!(" (system git: {})", s.trim()))
1070                .unwrap_or_default();
1071            anyhow::bail!("Failed to clone {}: {}{}", url, git2_err, detail)
1072        }
1073    }
1074}
1075
1076/// Fetch a repository pinned to a **tag** with libgit2.
1077///
1078/// `RepoBuilder::branch` resolves its argument under `refs/remotes/origin/`, so
1079/// a tag fails there with "reference 'refs/remotes/origin/<tag>' not found".
1080/// Init an empty repo and shallow-fetch the tag ref directly instead, then
1081/// detach onto the commit it peels to — cloning the default branch first would
1082/// download a second snapshot nobody wants.
1083///
1084/// Integration tests accept an explicit HTTPS fixture; `file://` cannot do shallow fetches.
1085///
1086/// Only reachable when system git is missing or failed: system git's
1087/// `clone --branch` already accepts tags.
1088fn clone_tag_with_git2(
1089    url: &str,
1090    tag: &str,
1091    cached_dir: &Path,
1092    cancel: Option<&Arc<AtomicBool>>,
1093    proxy_url: Option<&str>,
1094) -> Result<()> {
1095    let _ = std::fs::remove_dir_all(cached_dir);
1096    let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
1097    let fetch_opts = || {
1098        let cancel = cancel.cloned();
1099        let mut callbacks = git2::RemoteCallbacks::new();
1100        callbacks.transfer_progress(move |_| {
1101            if cancel.as_ref().is_some_and(|c| c.load(Ordering::SeqCst)) {
1102                return false;
1103            }
1104            Instant::now() <= deadline
1105        });
1106        git_credentials::install_git2_credentials(&mut callbacks, url);
1107        let mut opts = git2::FetchOptions::new();
1108        opts.remote_callbacks(callbacks);
1109        opts.depth(1);
1110        if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1111            let mut proxy_opts = git2::ProxyOptions::new();
1112            proxy_opts.url(proxy);
1113            opts.proxy_options(proxy_opts);
1114        }
1115        opts
1116    };
1117
1118    let repo = git2::Repository::init(cached_dir)?;
1119    {
1120        // A named remote, not an anonymous one: the cache-reuse path identifies
1121        // a cached repo by `git remote get-url origin`.
1122        let mut remote = repo.remote("origin", url)?;
1123        let refspec = format!("+refs/tags/{tag}:refs/tags/{tag}");
1124        remote.fetch(&[refspec.as_str()], Some(&mut fetch_opts()), None)?;
1125    }
1126    let commit = repo.revparse_single(&format!("refs/tags/{tag}^{{commit}}"))?;
1127    repo.set_head_detached(commit.id())?;
1128    repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
1129    Ok(())
1130}
1131
1132pub fn get_head_revision(repo_dir: &Path) -> Result<String> {
1133    let output = git_command()
1134        .arg("-C")
1135        .arg(repo_dir)
1136        .args(["rev-parse", "HEAD"])
1137        .output();
1138
1139    if let Ok(output) = output {
1140        if output.status.success() {
1141            return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string());
1142        }
1143    }
1144
1145    let repo = Repository::open(repo_dir)?;
1146    let head = repo.head()?.peel_to_commit()?;
1147    Ok(head.id().to_string())
1148}
1149
1150pub fn resolve_remote_revision(
1151    url: &str,
1152    branch: Option<&str>,
1153    proxy_url: Option<&str>,
1154) -> Result<String> {
1155    if let Ok(revision) = resolve_remote_revision_with_git(url, branch, proxy_url) {
1156        return Ok(revision);
1157    }
1158
1159    let repo = Repository::init_bare(
1160        std::env::temp_dir().join(format!("agent-hub-remote-{}", uuid::Uuid::new_v4())),
1161    )?;
1162    let mut remote = repo.remote_anonymous(url)?;
1163    let mut proxy_opts = git2::ProxyOptions::new();
1164    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1165        proxy_opts.url(proxy);
1166    }
1167    let mut callbacks = git2::RemoteCallbacks::new();
1168    git_credentials::install_git2_credentials(&mut callbacks, url);
1169    remote.connect_auth(Direction::Fetch, Some(callbacks), Some(proxy_opts))?;
1170    let refs = remote.list()?;
1171
1172    for wanted in candidate_ref_names(branch) {
1173        if let Some(head) = refs.iter().find(|head| head.name() == wanted) {
1174            return Ok(head.oid().to_string());
1175        }
1176    }
1177
1178    anyhow::bail!("Unable to resolve remote revision for {}", url)
1179}
1180
1181pub fn checkout_revision(repo_dir: &Path, revision: &str) -> Result<()> {
1182    let status = git_command()
1183        .arg("-C")
1184        .arg(repo_dir)
1185        .args(["checkout", "--detach", revision])
1186        .stdout(std::process::Stdio::null())
1187        .stderr(std::process::Stdio::null())
1188        .status();
1189
1190    if let Ok(status) = status {
1191        if status.success() {
1192            return Ok(());
1193        }
1194    }
1195
1196    let repo = Repository::open(repo_dir)?;
1197    let oid = git2::Oid::from_str(revision)?;
1198    repo.set_head_detached(oid)?;
1199    repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
1200    Ok(())
1201}
1202
1203pub fn relative_subpath(repo_dir: &Path, skill_dir: &Path) -> Option<String> {
1204    let relative = skill_dir.strip_prefix(repo_dir).ok()?;
1205    if relative.as_os_str().is_empty() {
1206        None
1207    } else {
1208        Some(relative.to_string_lossy().to_string())
1209    }
1210}
1211
1212fn normalize_url(url: &str) -> (String, Option<String>, Option<String>) {
1213    let trimmed = url.trim();
1214
1215    // Already a full URL
1216    if trimmed.starts_with("http://")
1217        || trimmed.starts_with("https://")
1218        || trimmed.starts_with("ssh://")
1219        || trimmed.starts_with("git@")
1220    {
1221        if let Some((clone_url, branch, subpath)) = parse_github_tree_url(trimmed) {
1222            return (clone_url, Some(branch), subpath);
1223        }
1224        return (trimmed.to_string(), None, None);
1225    }
1226
1227    // Shorthand: user/repo
1228    if trimmed.contains('/') && !trimmed.contains(' ') {
1229        return (format!("https://github.com/{}.git", trimmed), None, None);
1230    }
1231
1232    (trimmed.to_string(), None, None)
1233}
1234
1235pub fn find_skill_dir(repo_dir: &Path, skill_id: Option<&str>) -> Result<PathBuf> {
1236    // If skill_id provided, look for it specifically. Each branch must validate
1237    // that the resolved dir actually contains a SKILL.md — otherwise it returns
1238    // a container/category dir that the installer will reject later with a
1239    // worse error.
1240    if let Some(id) = skill_id {
1241        let direct = repo_dir.join(id);
1242        if skill_metadata::is_valid_skill_dir(&direct) {
1243            return Ok(direct);
1244        }
1245
1246        let in_skills = repo_dir.join("skills").join(id);
1247        if skill_metadata::is_valid_skill_dir(&in_skills) {
1248            return Ok(in_skills);
1249        }
1250
1251        // Prefer the unified agent skills location over provider-specific
1252        // variants (e.g. `.cursor/skills`, `.claude/skills`). Repos that
1253        // publish per-provider variants typically also ship a generic copy
1254        // at `.agents/skills`; the recursive fallback below is non-deterministic
1255        // across filesystems, so without this check we may pick an arbitrary
1256        // provider's transformed variant.
1257        let in_agents = repo_dir.join(".agents").join("skills").join(id);
1258        if skill_metadata::is_valid_skill_dir(&in_agents) {
1259            return Ok(in_agents);
1260        }
1261
1262        // Recursive search: match by directory name or SKILL.md name field.
1263        // The basename branch must check validity; the SKILL.md-name branch is
1264        // implicitly validated by parsing the frontmatter.
1265        let mut name_match: Option<PathBuf> = None;
1266        for e in walkdir::WalkDir::new(repo_dir)
1267            .max_depth(6)
1268            .into_iter()
1269            .flatten()
1270        {
1271            if e.file_type().is_dir() {
1272                if e.file_name().to_string_lossy() == id
1273                    && skill_metadata::is_valid_skill_dir(e.path())
1274                {
1275                    return Ok(e.path().to_path_buf());
1276                }
1277                if name_match.is_none() {
1278                    let meta = skill_metadata::parse_skill_md(e.path());
1279                    if meta.name.as_deref() == Some(id) {
1280                        name_match = Some(e.path().to_path_buf());
1281                    }
1282                }
1283            }
1284        }
1285        if let Some(path) = name_match {
1286            return Ok(path);
1287        }
1288
1289        // A specific skill id was requested but nothing matched. Error instead
1290        // of falling through to a container/root — otherwise the installer would
1291        // copy the entire `skills/` container (or an unrelated root skill) under
1292        // the requested name, duplicating every skill in the repo. See issue #278.
1293        bail!("Skill '{}' not found in {}", id, repo_dir.display());
1294    }
1295
1296    // No skill id requested — resolve a repo-wide skill location. The fallbacks
1297    // below are intended for enumeration flows (collect_git_skill_dirs walks the
1298    // resolved container to list individual skills), not for a single install.
1299    // Check if root is a skill
1300    let has_skill_md = ["SKILL.md", "skill.md"]
1301        .iter()
1302        .any(|f| repo_dir.join(f).exists());
1303    if has_skill_md {
1304        return Ok(repo_dir.to_path_buf());
1305    }
1306
1307    // Check skills/ subdirectory
1308    let skills_subdir = repo_dir.join("skills");
1309    if skills_subdir.is_dir() {
1310        return Ok(skills_subdir);
1311    }
1312
1313    let skill_subdir = repo_dir.join("skill");
1314    if skill_subdir.is_dir() {
1315        return Ok(skill_subdir);
1316    }
1317
1318    // Default to root
1319    Ok(repo_dir.to_path_buf())
1320}
1321
1322pub fn cleanup_temp(path: &Path) {
1323    let _ = std::fs::remove_dir_all(path);
1324}
1325
1326fn parse_github_tree_url(url: &str) -> Option<(String, String, Option<String>)> {
1327    let (clone_url, path) = parse_github_tree_url_path(url)?;
1328    let (branch, subpath) = split_tree_branch_path(&path, &[]);
1329    Some((clone_url, branch, subpath))
1330}
1331
1332/// Match a GitHub `…/tree/<path>` URL and return `(clone_url, path_after_tree)`.
1333/// The path is left unsplit so callers can disambiguate branch-vs-subpath with
1334/// knowledge of the actual remote branches.
1335fn parse_github_tree_url_path(url: &str) -> Option<(String, String)> {
1336    let re = regex::Regex::new(r"^(https://github\.com/[^/]+/[^/]+?)(?:\.git)?/tree/(.+)$").ok()?;
1337    let caps = re.captures(url)?;
1338    let clone_url = format!("{}.git", caps.get(1)?.as_str());
1339    let path = caps.get(2)?.as_str().to_string();
1340    Some((clone_url, path))
1341}
1342
1343/// Split a `tree/<path>` tail against the remote's actual refs.
1344///
1345/// Branches are matched first: a tag may only claim a URL that no branch
1346/// explains. Matching the longest ref across heads and tags at once would let
1347/// a tag named `main/v1` swallow a URL that means branch `main` plus subpath
1348/// `v1/...`.
1349fn split_tree_path_with_known_refs(path: &str, known: &RemoteRefNames) -> (String, Option<String>) {
1350    match_known_ref(path, &known.heads)
1351        .or_else(|| match_known_ref(path, &known.tags))
1352        .unwrap_or_else(|| split_tree_branch_path(path, &[]))
1353}
1354
1355/// Longest ref in `known` that matches a `/`-bounded prefix of `path`, split
1356/// into `(ref, optional subpath)`. `None` when nothing matches.
1357///
1358/// Callers must try branches before tags: taking the longest match across both
1359/// at once lets a tag named `main/v1` steal a URL that means branch `main`
1360/// plus subpath `v1/...`.
1361fn match_known_ref(path: &str, known: &[String]) -> Option<(String, Option<String>)> {
1362    let mut best: Option<&str> = None;
1363    for name in known {
1364        if name.is_empty() {
1365            continue;
1366        }
1367        let matches = path == name.as_str()
1368            || path
1369                .strip_prefix(name.as_str())
1370                .is_some_and(|rest| rest.starts_with('/'));
1371        if matches && best.map_or(true, |b: &str| name.len() > b.len()) {
1372            best = Some(name);
1373        }
1374    }
1375    best.map(|name| {
1376        let subpath = path
1377            .strip_prefix(name)
1378            .and_then(|rest| rest.strip_prefix('/'))
1379            .filter(|s| !s.is_empty())
1380            .map(|s| s.to_string());
1381        (name.to_string(), subpath)
1382    })
1383}
1384
1385/// Split a `tree/<path>` tail into `(branch, optional subpath)`.
1386///
1387/// GitHub tree URLs are ambiguous when the branch name contains a `/`
1388/// (e.g. `feature/x`). With an empty `known_branches`, fall back to the
1389/// optimistic interpretation: first segment is the branch, rest is subpath
1390/// (correct for the vast majority of repos that use single-segment branch names).
1391/// With a populated `known_branches`, pick the longest branch that matches a
1392/// `/`-bounded prefix of `path`.
1393fn split_tree_branch_path(path: &str, known_branches: &[String]) -> (String, Option<String>) {
1394    if let Some(hit) = match_known_ref(path, known_branches) {
1395        return hit;
1396    }
1397
1398    let mut parts = path.splitn(2, '/');
1399    let branch = parts.next().unwrap_or("").to_string();
1400    let subpath = parts
1401        .next()
1402        .filter(|s| !s.is_empty())
1403        .map(|s| s.to_string());
1404    (branch, subpath)
1405}
1406
1407/// Network-aware variant of `parse_git_source`. For GitHub `…/tree/<path>` URLs
1408/// with multi-segment paths, queries `git ls-remote --heads` to resolve which
1409/// segments belong to the branch and which to the subpath. Falls back to the
1410/// optimistic (single-segment-branch) parse on network failure.
1411pub fn parse_git_source_resolved(url: &str, proxy_url: Option<&str>) -> ParsedGitSource {
1412    let mut parsed = parse_git_source(url);
1413    let original_url = parsed.original_url.clone();
1414
1415    let Some((clone_url, path)) = parse_github_tree_url_path(&original_url) else {
1416        return parsed;
1417    };
1418    // No ambiguity if the tree path is a single segment.
1419    if !path.contains('/') {
1420        return parsed;
1421    }
1422
1423    let known = match list_remote_ref_names(&clone_url, proxy_url) {
1424        Ok(refs) if !refs.is_empty() => refs,
1425        Ok(_) => {
1426            log::warn!(
1427                "ls-remote returned no refs for {}; using optimistic tree-URL parse",
1428                clone_url
1429            );
1430            return parsed;
1431        }
1432        Err(e) => {
1433            log::warn!(
1434                "ls-remote failed for {}: {} — using optimistic tree-URL parse (slash-ref URLs may parse incorrectly)",
1435                clone_url,
1436                e
1437            );
1438            return parsed;
1439        }
1440    };
1441    let (branch, subpath) = split_tree_path_with_known_refs(&path, &known);
1442    parsed.branch = Some(branch);
1443    parsed.subpath = subpath;
1444    parsed
1445}
1446
1447/// Branch and tag names on the remote, used to split a `tree/<path>` URL.
1448///
1449/// Tags count: `tree/release/v1.0/skills/foo` is as valid a tag URL as it is a
1450/// branch URL, and listing only heads would silently split it as branch
1451/// `release` plus subpath `v1.0/skills/foo`. They stay in separate lists
1452/// because branches must be matched first.
1453#[derive(Debug, Default, PartialEq)]
1454struct RemoteRefNames {
1455    heads: Vec<String>,
1456    tags: Vec<String>,
1457}
1458
1459impl RemoteRefNames {
1460    fn is_empty(&self) -> bool {
1461        self.heads.is_empty() && self.tags.is_empty()
1462    }
1463}
1464
1465fn list_remote_ref_names(url: &str, proxy_url: Option<&str>) -> Result<RemoteRefNames> {
1466    let mut cmd = git_command();
1467    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1468        cmd.arg("-c").arg(format!("http.proxy={proxy}"));
1469        cmd.arg("-c").arg(format!("https.proxy={proxy}"));
1470    }
1471    let output = cmd
1472        .args(["ls-remote", "--heads", "--tags", url])
1473        .output()
1474        .with_context(|| format!("Failed to list remote refs for {}", url))?;
1475
1476    if !output.status.success() {
1477        anyhow::bail!("git ls-remote exited with {}", output.status);
1478    }
1479
1480    let stdout = String::from_utf8_lossy(&output.stdout);
1481    Ok(parse_remote_ref_names(&stdout))
1482}
1483
1484fn parse_remote_ref_names(stdout: &str) -> RemoteRefNames {
1485    let mut refs = RemoteRefNames::default();
1486    for line in stdout.lines() {
1487        let mut parts = line.split_whitespace();
1488        let Some(_sha) = parts.next() else { continue };
1489        let Some(refname) = parts.next() else {
1490            continue;
1491        };
1492        // Peeled entries name the same tag; keep one entry per ref.
1493        if refname.ends_with("^{}") {
1494            continue;
1495        }
1496        if let Some(name) = refname.strip_prefix("refs/heads/") {
1497            refs.heads.push(name.to_string());
1498        } else if let Some(name) = refname.strip_prefix("refs/tags/") {
1499            refs.tags.push(name.to_string());
1500        }
1501    }
1502    refs
1503}
1504
1505/// Ref names that a stored source ref may resolve to, most preferred first.
1506///
1507/// A source ref is stored as a bare name (`main`, `v0.8.0`) with no record of
1508/// whether it is a branch or a tag — GitHub `tree/` URLs do not distinguish
1509/// them either. Branches win over tags so an ambiguous name keeps its historic
1510/// meaning, and the peeled tag (`^{}`) wins over the tag object because only
1511/// the peeled line carries the commit an annotated tag points at.
1512fn candidate_ref_names(source_ref: Option<&str>) -> Vec<String> {
1513    match source_ref {
1514        Some(name) => vec![
1515            format!("refs/heads/{name}"),
1516            format!("refs/tags/{name}^{{}}"),
1517            format!("refs/tags/{name}"),
1518        ],
1519        None => vec!["HEAD".to_string()],
1520    }
1521}
1522
1523/// Pick a revision out of `git ls-remote` output by exact ref name.
1524///
1525/// Never take "the first line": querying a tag returns both the tag object and
1526/// its peeled commit, and their order is the remote's business, not ours.
1527fn select_remote_revision(stdout: &str, candidates: &[String]) -> Option<String> {
1528    let refs: Vec<(&str, &str)> = stdout
1529        .lines()
1530        .filter_map(|line| {
1531            let mut parts = line.split_whitespace();
1532            let sha = parts.next()?;
1533            let name = parts.next()?;
1534            (!sha.is_empty()).then_some((name, sha))
1535        })
1536        .collect();
1537
1538    candidates.iter().find_map(|wanted| {
1539        refs.iter()
1540            .find(|(name, _)| *name == wanted.as_str())
1541            .map(|(_, sha)| sha.to_string())
1542    })
1543}
1544
1545fn resolve_remote_revision_with_git(
1546    url: &str,
1547    branch: Option<&str>,
1548    proxy_url: Option<&str>,
1549) -> Result<String> {
1550    let candidates = candidate_ref_names(branch);
1551    let mut cmd = git_command();
1552    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
1553        cmd.arg("-c").arg(format!("http.proxy={proxy}"));
1554        cmd.arg("-c").arg(format!("https.proxy={proxy}"));
1555    }
1556    cmd.args(["ls-remote", url]);
1557    cmd.args(&candidates);
1558    let output = cmd
1559        .output()
1560        .with_context(|| format!("Failed to query remote {}", url))?;
1561
1562    if !output.status.success() {
1563        anyhow::bail!("git ls-remote exited with {}", output.status);
1564    }
1565
1566    let stdout = String::from_utf8_lossy(&output.stdout);
1567    select_remote_revision(&stdout, &candidates)
1568        .ok_or_else(|| anyhow::anyhow!("No remote revision found"))
1569}
1570
1571#[cfg(test)]
1572mod tests;
1573
1574#[cfg(test)]
1575#[path = "git_fetcher/tag_tests.rs"]
1576mod tag_tests;