agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
use crate::core::central_repo;
use crate::core::git_credentials;
use crate::core::skill_metadata;
mod cache_cleanup;
mod cache_lock;
use anyhow::{bail, Context, Result};
pub use cache_cleanup::clear_repository_cache;
use cache_lock::{lock_repo_cache, RepoCacheLock};
use git2::{Direction, Repository};
use sha2::{Digest, Sha256};
use std::io::{BufReader, Read};
use std::path::{Path, PathBuf};
use std::process::{ChildStderr, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

const CLONE_TIMEOUT_SECS: u64 = 300;

/// Filename prefix shared by isolated install checkouts under `std::env::temp_dir()`.
/// Used by both `materialize_cached_repo` (writer) and `validate_clone_temp_path` (reader).
pub const CLONE_TEMP_PREFIX: &str = "agent-hub-clone-";

/// Callback type for reporting clone progress messages to the UI.
pub type ProgressCallback = Box<dyn Fn(&str) + Send>;

/// Create a `Command` for git that hides the console window on Windows.
fn git_command() -> Command {
    #[allow(unused_mut)]
    let mut cmd = Command::new("git");
    #[cfg(target_os = "windows")]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
    }
    cmd
}

#[derive(Debug, Clone)]
pub struct ParsedGitSource {
    pub original_url: String,
    pub clone_url: String,
    pub branch: Option<String>,
    pub subpath: Option<String>,
}

pub fn parse_git_source(url: &str) -> ParsedGitSource {
    let trimmed = url.trim().to_string();
    let (clone_url, branch, subpath) = normalize_url(&trimmed);

    ParsedGitSource {
        original_url: trimmed,
        clone_url,
        branch,
        subpath,
    }
}

/// Validate that a URL uses an allowed scheme for git operations.
/// Only permits `https://`, `http://`, `ssh://`, and SCP-style `git@` URLs,
/// plus shorthand like `user/repo` (no scheme). Rejects everything else
/// including `file://`, `ext::`, bare local paths, and UNC paths.
pub fn validate_git_url(url: &str) -> Result<()> {
    let trimmed = url.trim();
    let lower = trimmed.to_lowercase();

    // Explicitly allowed schemes
    if lower.starts_with("https://")
        || lower.starts_with("http://")
        || lower.starts_with("ssh://")
        || lower.starts_with("git@")
    {
        return Ok(());
    }

    // Allow GitHub/GitLab shorthand like "user/repo" or "user/repo.git"
    if !trimmed.contains("://")
        && !trimmed.contains('\\')
        && !trimmed.starts_with('/')
        && !trimmed.starts_with('.')
        && !trimmed.starts_with('~')
        && trimmed.contains('/')
    {
        let bytes = trimmed.as_bytes();
        let is_windows_path =
            bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':';
        if !is_windows_path {
            return Ok(());
        }
    }

    anyhow::bail!("URL scheme not allowed: only https, http, ssh, and git@ are permitted");
}

/// Strip clone-irrelevant differences from a URL so equivalent forms share a
/// cache slot and pass remote-equality checks. Specifically:
/// - Trims whitespace and a trailing `/`.
/// - Drops a trailing `.git` suffix (servers accept both forms).
///
/// This is intentionally conservative — no case folding, no scheme rewriting,
/// no path normalization beyond the suffix — so non-GitHub hosts that treat
/// paths case-sensitively or distinguish schemes are unaffected.
fn canonicalize_clone_url(url: &str) -> String {
    let trimmed = url.trim().trim_end_matches('/');
    trimmed.strip_suffix(".git").unwrap_or(trimmed).to_string()
}

/// Compute a stable cache directory name for a given clone URL. Hashes the
/// canonical form so e.g. `https://github.com/x/y` and `https://github.com/x/y.git`
/// share the same cache slot.
fn repo_cache_dir(url: &str) -> PathBuf {
    repo_cache_dir_for(url, false)
}

/// Cache slot for a URL. A subpath-scoped checkout gets its own `-sparse` slot
/// rather than sharing the full one, because the two are not interchangeable:
/// the flows that need a whole tree (repo preview with no subpath, the skills.sh
/// locator search, `resolve_skill_dir`'s repo-wide fallback) must never be handed
/// a checkout holding one directory. A repo used both ways simply keeps two
/// caches, and the full path keeps behaving exactly as it did before.
fn repo_cache_dir_for(url: &str, sparse: bool) -> PathBuf {
    let canonical = canonicalize_clone_url(url);
    let mut hasher = Sha256::new();
    hasher.update(canonical.as_bytes());
    let hash = format!("{:x}", hasher.finalize());
    let short = &hash[..16];
    let name = if sparse {
        format!("{short}-sparse")
    } else {
        short.to_string()
    };
    central_repo::cache_dir().join("repos").join(name)
}

/// Upper bound on the whole repo cache.
///
/// A backstop, not a quota. Nothing ever deleted a cache slot before, so a
/// library built from many repositories accumulated one checkout per repository
/// and kept it forever — measured at 569 MB across 48 repositories on an
/// ordinary machine, the oldest untouched for four months.
const REPO_CACHE_LIMIT_BYTES: u64 = 1024 * 1024 * 1024;

/// Delete least-recently-used cache slots until the cache is back under the limit.
///
/// Called only where a slot is about to be cloned fresh. Refreshing an existing
/// slot adds a delta; a new repository adds a whole checkout, so that is where the
/// growth comes from — and it keeps a batch update from paying for the walk once
/// per repository (the walk is ~0.8s over a 569 MB cache).
///
/// `keep` is the slot the caller is about to write. A slot another install holds
/// is skipped rather than waited for: deleting a checkout from under a running
/// install would break it. The lock *file* is deliberately left behind — unlinking
/// it while someone waits on it would let two installs each hold a lock on a
/// different inode for the same slot.
fn prune_repo_cache(keep: &Path) {
    prune_cache_root(
        &central_repo::cache_dir().join("repos"),
        keep,
        REPO_CACHE_LIMIT_BYTES,
    )
}

/// Takes its root and limit rather than reading them from the central config, so
/// it is a plain function of the directory in front of it — testable without
/// touching process-global state that parallel tests would fight over.
fn prune_cache_root(root: &Path, keep: &Path, limit: u64) {
    let Ok(entries) = std::fs::read_dir(root) else {
        return;
    };

    let mut slots: Vec<(PathBuf, u64, std::time::SystemTime)> = Vec::new();
    let mut total: u64 = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let (size, used) = slot_stats(&path);
        total = total.saturating_add(size);
        slots.push((path, size, used));
    }

    slots.sort_by_key(|(_, _, used)| *used);
    for (path, size, _) in slots {
        if total <= limit {
            break;
        }
        if path == keep {
            continue;
        }
        let Ok(_lock) = RepoCacheLock::try_acquire(&path) else {
            continue;
        };
        if std::fs::remove_dir_all(&path).is_ok() {
            log::info!("pruned repo cache slot {}", path.display());
            total = total.saturating_sub(size);
        }
    }
}

/// Bytes in a cache slot, and when anything inside it was last written.
///
/// The recency half cannot come from the slot directory's own mtime: a fetch
/// writes objects deep inside `.git`, never in the slot root, so that mtime stays
/// at creation time and "least recently used" would silently mean "oldest",
/// evicting a repository that is updated weekly before one nobody has touched
/// since it was cloned. The size walk visits every file anyway, so the real
/// answer is free.
fn slot_stats(dir: &Path) -> (u64, std::time::SystemTime) {
    let mut size = 0u64;
    let mut newest = std::time::UNIX_EPOCH;
    for entry in walkdir::WalkDir::new(dir).into_iter().flatten() {
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        if !meta.is_file() {
            continue;
        }
        size = size.saturating_add(meta.len());
        if let Ok(modified) = meta.modified() {
            newest = newest.max(modified);
        }
    }
    (size, newest)
}

fn materialize_cached_repo(cached: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<PathBuf> {
    let temp_dir =
        std::env::temp_dir().join(format!("{CLONE_TEMP_PREFIX}{}", uuid::Uuid::new_v4()));

    // `git clone --local` with default hardlinks: cache objects are content-addressed
    // and immutable, the flock above prevents the cache from being mutated mid-clone,
    // and any later cache deletion leaves linked objects intact in the temp checkout.
    let child = git_command()
        .arg("clone")
        .arg("--local")
        .arg(cached)
        .arg(&temp_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn();

    let mut system_git_stderr: Option<String> = None;
    if let Ok(mut child) = child {
        let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
        loop {
            if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
                let _ = child.kill();
                let _ = child.wait();
                let _ = std::fs::remove_dir_all(&temp_dir);
                anyhow::bail!("Installation cancelled");
            }
            match child.try_wait() {
                Ok(Some(status)) => {
                    if status.success() {
                        return Ok(temp_dir);
                    }
                    let mut stderr_buf = String::new();
                    if let Some(mut stderr) = child.stderr.take() {
                        let _ = stderr.read_to_string(&mut stderr_buf);
                    }
                    let _ = std::fs::remove_dir_all(&temp_dir);
                    system_git_stderr = Some(stderr_buf);
                    break;
                }
                Ok(None) => {
                    if Instant::now() > deadline {
                        let _ = child.kill();
                        let _ = child.wait();
                        let _ = std::fs::remove_dir_all(&temp_dir);
                        anyhow::bail!(
                            "Local clone from cache timed out after {}s",
                            CLONE_TIMEOUT_SECS
                        );
                    }
                    std::thread::sleep(Duration::from_millis(100));
                }
                Err(_) => {
                    let _ = std::fs::remove_dir_all(&temp_dir);
                    break;
                }
            }
        }
    }

    let source = cached
        .to_str()
        .ok_or_else(|| anyhow::anyhow!("Cached repo path is not valid UTF-8"))?;
    match git2::build::RepoBuilder::new().clone(source, &temp_dir) {
        Ok(_) => Ok(temp_dir),
        Err(err) => {
            let _ = std::fs::remove_dir_all(&temp_dir);
            let detail = system_git_stderr
                .filter(|s| !s.trim().is_empty())
                .map(|s| format!(" (system git: {})", s.trim()))
                .unwrap_or_default();
            anyhow::bail!(
                "Failed to create install checkout from cache: {}{}",
                err,
                detail
            )
        }
    }
}

/// Try to update an existing cached repo via fetch + reset.
/// Returns Ok(true) if the cache was reused, Ok(false) if it should be re-cloned.
fn try_update_cached_repo(
    cached: &Path,
    url: &str,
    branch: Option<&str>,
    proxy_url: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    on_progress: &Option<ProgressCallback>,
) -> Result<bool> {
    if !cached.join(".git").exists() {
        return Ok(false);
    }

    // Verify the remote URL still matches.
    let current_remote = {
        let mut cmd = git_command();
        cmd.arg("-C")
            .arg(cached)
            .args(["remote", "get-url", "origin"]);
        let output = cmd.output().ok();
        output
            .filter(|o| o.status.success())
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
    };
    let remote_matches = current_remote
        .as_deref()
        .is_some_and(|r| canonicalize_clone_url(r) == canonicalize_clone_url(url));
    if !remote_matches {
        // URL changed — discard cache.
        let _ = std::fs::remove_dir_all(cached);
        return Ok(false);
    }

    if let Some(cb) = on_progress {
        cb("Updating cached repository…");
    }

    // `-c` is a *global* git option: `git fetch -c key=value` is rejected with
    // "unknown switch `c`", so it has to precede the subcommand. It used to sit
    // after `fetch`, which made every cache refresh fail outright whenever a
    // proxy was configured — those users re-cloned the whole repository on every
    // install and update instead of ever reusing the cache.
    let mut fetch_cmd = git_command();
    fetch_cmd.arg("-C").arg(cached);
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        fetch_cmd.arg("-c").arg(format!("http.proxy={proxy}"));
        fetch_cmd.arg("-c").arg(format!("https.proxy={proxy}"));
    }
    fetch_cmd.arg("fetch").arg("--depth").arg("1");
    fetch_cmd.arg("origin");
    if let Some(branch) = branch {
        fetch_cmd.arg(branch);
    }
    fetch_cmd.stdout(Stdio::null()).stderr(Stdio::null());

    let child = fetch_cmd.spawn();
    if let Ok(mut child) = child {
        let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
        loop {
            if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
                let _ = child.kill();
                let _ = child.wait();
                anyhow::bail!("Installation cancelled");
            }
            match child.try_wait() {
                Ok(Some(status)) => {
                    if !status.success() {
                        // Fetch failed — discard cache and re-clone.
                        let _ = std::fs::remove_dir_all(cached);
                        return Ok(false);
                    }
                    break;
                }
                Ok(None) => {
                    if Instant::now() > deadline {
                        let _ = child.kill();
                        let _ = child.wait();
                        let _ = std::fs::remove_dir_all(cached);
                        return Ok(false);
                    }
                    std::thread::sleep(Duration::from_millis(200));
                }
                Err(_) => {
                    let _ = std::fs::remove_dir_all(cached);
                    return Ok(false);
                }
            }
        }
    } else {
        let _ = std::fs::remove_dir_all(cached);
        return Ok(false);
    }

    // Reset to the fetched HEAD. A branch has a remote-tracking ref, but a tag
    // does not — `origin/<tag>` is not a revision — so fall back to FETCH_HEAD,
    // which the fetch above just wrote. Without the fallback a tag source never
    // reuses its cache and silently re-clones on every check.
    let targets: Vec<String> = match branch {
        Some(b) => vec![format!("origin/{b}"), "FETCH_HEAD".to_string()],
        None => vec!["origin/HEAD".to_string()],
    };
    // Against a full cache this reset is local and returns immediately. Against a
    // sparse cache it is a partial clone, so writing the worktree lazily fetches
    // the blobs it needs — which is why it runs under the same timeout and cancel
    // flag as the fetch above instead of blocking forever on a dead network.
    let mut cancelled = false;
    let reset_ok = targets.iter().any(|target| {
        match run_git_watched_at(
            cached,
            &["reset", "--hard", target],
            proxy_url,
            cancel,
            &None,
        ) {
            Ok(()) => true,
            Err(e) => {
                cancelled |= is_cancellation(&e);
                false
            }
        }
    });
    // A cancellation is not a broken cache. Collapsed into `reset_ok == false` it
    // reads as "every target failed", and the cache below gets deleted — so
    // cancelling an install would silently cost the user the next full download.
    // The fetch above already treats cancellation this way; so must this.
    if cancelled {
        bail!("Installation cancelled");
    }
    match reset_ok {
        true => Ok(true),
        false => {
            let _ = std::fs::remove_dir_all(cached);
            Ok(false)
        }
    }
}

/// Filter out SSH informational warnings from stderr lines.
fn is_ssh_warning(line: &str) -> bool {
    let trimmed = line.trim().trim_start_matches("** ");
    trimmed.starts_with("WARNING:")
        || trimmed.starts_with("This session may")
        || trimmed.starts_with("The server may")
        || trimmed.starts_with("See https://openssh.com")
}

fn spawn_stderr_collector(
    stderr: Option<ChildStderr>,
    forward_progress: bool,
) -> (
    std::sync::mpsc::Receiver<String>,
    std::thread::JoinHandle<String>,
) {
    let (stderr_tx, stderr_rx) = std::sync::mpsc::channel::<String>();
    let stderr_thread = std::thread::spawn(move || {
        let mut collected = String::new();
        let Some(stderr) = stderr else {
            return collected;
        };

        let mut reader = BufReader::new(stderr);
        let mut line = Vec::new();
        let mut byte = [0u8; 1];

        loop {
            match reader.read(&mut byte) {
                Ok(0) => {
                    if !line.is_empty() {
                        emit_stderr_line(&line, forward_progress, &stderr_tx, &mut collected);
                    }
                    break;
                }
                Ok(_) if byte[0] == b'\n' || byte[0] == b'\r' => {
                    if !line.is_empty() {
                        emit_stderr_line(&line, forward_progress, &stderr_tx, &mut collected);
                        line.clear();
                    }
                }
                Ok(_) => line.push(byte[0]),
                Err(_) => break,
            }
        }

        collected
    });

    (stderr_rx, stderr_thread)
}

fn emit_stderr_line(
    line: &[u8],
    forward_progress: bool,
    stderr_tx: &std::sync::mpsc::Sender<String>,
    collected: &mut String,
) {
    let line = String::from_utf8_lossy(line).to_string();
    if !is_ssh_warning(&line) {
        collected.push_str(&line);
        collected.push('\n');
    }
    if forward_progress {
        let _ = stderr_tx.send(line);
    }
}

pub fn clone_repo_ref(
    url: &str,
    branch: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
) -> Result<PathBuf> {
    clone_repo_ref_with_progress(url, branch, cancel, proxy_url, None)
}

pub fn clone_repo_ref_with_progress(
    url: &str,
    branch: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
    on_progress: Option<ProgressCallback>,
) -> Result<PathBuf> {
    clone_repo_ref_scoped(url, branch, None, cancel, proxy_url, on_progress)
}

/// Clone `url`, narrowed to `subpath` when one is known.
///
/// With a subpath this fetches only that directory (`--filter=blob:none` plus a
/// sparse-checkout), which is the difference between downloading a repository and
/// downloading one skill — measured at 15 MB versus 472 KB for a single skill out
/// of `anthropics/skills`. Every way that can fail — a server with
/// `uploadpack.allowFilter` off, a git too old to read the sparse arguments the
/// way we mean them, a subpath that upstream has since moved — falls back to the
/// full checkout, so the narrow path can only ever be faster, never the reason an
/// install stops working.
///
/// Pass `None` for `subpath` whenever the caller needs to search the repository
/// rather than read one known directory.
pub fn clone_repo_ref_scoped(
    url: &str,
    branch: Option<&str>,
    subpath: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
    on_progress: Option<ProgressCallback>,
) -> Result<PathBuf> {
    if let Some(subpath) = sparse_pattern(subpath) {
        match clone_repo_sparse(url, branch, &subpath, cancel, proxy_url, &on_progress) {
            Ok(dir) => return Ok(dir),
            Err(e) if is_cancellation(&e) => return Err(e),
            Err(e) => {
                log::info!(
                    "narrow clone of '{subpath}' from {url} unavailable, using a full checkout: {e}"
                );
            }
        }
    }

    clone_repo_full(url, branch, cancel, proxy_url, on_progress)
}

/// Whether an error is a user cancellation rather than a fault worth retrying
/// differently.
fn is_cancellation(err: &anyhow::Error) -> bool {
    let message = err.to_string();
    message.contains("cancelled") || message.contains("canceled")
}

/// Turn a stored subpath into a sparse-checkout pattern, or `None` when it is not
/// one we are willing to hand to git.
///
/// The pattern given to git must select the same directory the caller will later
/// `join` onto the checkout. Tidying the string here — trimming, swapping
/// separators — would break that: on unix a trailing space and a backslash are
/// both legal parts of a directory name, so `skills/foo ` would narrow to
/// `skills/foo`, pass the guard, and then leave the caller reading a directory the
/// checkout does not contain, with no failure to fall back on. So nothing is
/// rewritten; a path that is not already clean simply takes the full checkout.
///
/// Windows is the one exception, and only because `\` cannot be part of a name
/// there — `content_hash` normalizes separators under the same `cfg` for the same
/// reason.
fn sparse_pattern(subpath: Option<&str>) -> Option<String> {
    let raw = subpath?;
    #[cfg(windows)]
    let raw = &raw.replace('\\', "/");

    if raw.is_empty()
        || raw != raw.trim()
        || raw.starts_with('/')
        || raw.ends_with('/')
        || raw.contains('\\')
    {
        return None;
    }
    if raw
        .split('/')
        .any(|segment| segment.is_empty() || segment == "." || segment == "..")
    {
        return None;
    }
    Some(raw.to_string())
}

/// Clone only `subpath` out of `url`, reusing (and widening) the sparse cache slot.
fn clone_repo_sparse(
    url: &str,
    branch: Option<&str>,
    subpath: &str,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
    on_progress: &Option<ProgressCallback>,
) -> Result<PathBuf> {
    let cached_dir = repo_cache_dir_for(url, true);
    let _cache_lock = lock_repo_cache(&cached_dir, on_progress)?;

    // One slot serves every skill from this repo: the objects are what is
    // expensive, and they are shared. The lock holds until this call's copy is
    // taken, so a later install re-scoping the worktree cannot disturb it.
    let reusable = cached_dir.exists()
        && try_update_cached_repo(&cached_dir, url, branch, proxy_url, cancel, on_progress)?;

    if !reusable {
        let _ = std::fs::remove_dir_all(&cached_dir);
        prune_repo_cache(&cached_dir);
        sparse_clone_into(&cached_dir, url, branch, cancel, proxy_url, on_progress).inspect_err(
            |_| {
                let _ = std::fs::remove_dir_all(&cached_dir);
            },
        )?;
    }

    set_sparse_scope(&cached_dir, subpath, cancel, proxy_url, on_progress)?;

    // `sparse-checkout set` succeeds on a path the repository does not have — it
    // just leaves that path absent, keeping the root files cone mode always
    // includes. So the result has to be inspected rather than trusted.
    if !sparse_checkout_holds_a_skill(&cached_dir, subpath) {
        bail!("'{subpath}' is not a skill directory in the narrow checkout of {url}");
    }

    copy_cached_repo(&cached_dir, cancel)
}

fn sparse_clone_into(
    dest: &Path,
    url: &str,
    branch: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
    on_progress: &Option<ProgressCallback>,
) -> Result<()> {
    if let Some(cb) = on_progress {
        cb("Fetching only the requested skill directory…");
    }
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent)?;
    }

    let mut command = git_command();
    command
        .arg("clone")
        .arg("--filter=blob:none")
        .arg("--no-checkout")
        .arg("--sparse")
        .arg("--depth")
        .arg("1");
    // `git clone -c` applies the value before the initial fetch, so unlike
    // `git fetch` this really does route the clone through the proxy.
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        command.arg("-c").arg(format!("http.proxy={proxy}"));
        command.arg("-c").arg(format!("https.proxy={proxy}"));
    }
    if let Some(branch) = branch {
        command.arg("--branch").arg(branch);
    }
    command.arg("--progress").arg(url).arg(dest);
    run_git_watched(command, cancel, on_progress)
}

/// Point the cache's sparse checkout at `subpath` and materialize it.
///
/// `set` rather than `add`: fetched objects stay in the cache either way, so
/// carrying every previously requested skill in the worktree buys nothing.
fn set_sparse_scope(
    cached: &Path,
    subpath: &str,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
    on_progress: &Option<ProgressCallback>,
) -> Result<()> {
    // `--cone` is explicit because cone mode is only the default on newer git,
    // and the non-cone reading of the same argument is a gitignore-style pattern
    // that would not bring the directory's contents with it.
    run_git_watched_at(
        cached,
        &["sparse-checkout", "set", "--cone", subpath],
        proxy_url,
        cancel,
        on_progress,
    )?;
    run_git_watched_at(cached, &["checkout"], proxy_url, cancel, on_progress)
}

/// Whether the narrow checkout produced a skill at exactly `subpath`.
///
/// Deliberately strict: a directory that merely *contains* skills is refused, so
/// a container subpath takes the full checkout. That is not conservatism for its
/// own sake — `resolve_skill_dir` accepts a stored path only when the path itself
/// is a skill, and otherwise searches the whole repository for the locator id. Let
/// a container through here and that search runs against a tree holding one
/// directory, which does not fail cleanly: it can resolve a *different* skill that
/// happens to be inside the narrow scope. Refusing containers keeps the repo-wide
/// search on a repo-wide checkout, which is the only tree it is correct on.
fn sparse_checkout_holds_a_skill(cached: &Path, subpath: &str) -> bool {
    skill_metadata::is_valid_skill_dir(&cached.join(subpath))
}

/// Materialize an install checkout from a sparse cache by copying it.
///
/// `git clone --local` cannot be used here. Cloning from a partial clone asks the
/// source to serve objects it does not have, and git aborts with "could not fetch
/// <oid> from promisor remote", taking the whole install with it. A plain copy
/// keeps the promisor and sparse configuration intact, and is cheap precisely
/// because a sparse cache holds one skill instead of a repository.
fn copy_cached_repo(cached: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<PathBuf> {
    let temp_dir =
        std::env::temp_dir().join(format!("{CLONE_TEMP_PREFIX}{}", uuid::Uuid::new_v4()));
    if let Err(e) = copy_dir_contents(cached, &temp_dir, cancel) {
        let _ = std::fs::remove_dir_all(&temp_dir);
        return Err(e);
    }
    detach_from_promisor(&temp_dir);
    Ok(temp_dir)
}

/// Cut an install checkout loose from the promisor remote it was copied from.
///
/// This is the boundary that keeps the narrow clone from becoming a permanent tax
/// on everyone who touches this code. A partial clone carries IOUs: a git command
/// that reaches an object we never fetched silently becomes a network round trip,
/// which can hang, needs a proxy, and needs credentials. Callers run git against
/// the checkout we hand back — `checkout_revision`, `get_head_revision`, whatever
/// gets added next — and nothing in the type system would tell them that.
///
/// Dropping the config makes a missing object an immediate error instead, exactly
/// as it has always been in a shallow full checkout.
///
/// The precise claim, because a broader one would be wrong: no git command against
/// the returned checkout fetches an object *behind the caller's back*. An explicit
/// `fetch`/`pull`/`ls-remote` still reaches origin, whose URL the copy keeps — no
/// caller does that today, and one that started would be doing something visibly
/// network-shaped. What this rules out is the invisible case, which is the one
/// nobody would think to instrument.
fn detach_from_promisor(repo_dir: &Path) {
    // Three keys, because git registers a promisor remote from *any* of them.
    // `git clone --filter` writes the two `remote.origin.*` ones and, since 2.25,
    // not `extensions.partialClone` — but leaving that one out would mean the set
    // is complete only for the git that happens to write our caches, and getting
    // it wrong restores lazy fetching silently.
    for key in [
        "remote.origin.promisor",
        "remote.origin.partialclonefilter",
        "extensions.partialClone",
    ] {
        let _ = git_command()
            .arg("-C")
            .arg(repo_dir)
            .args(["config", "--unset", key])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
}

/// Recursive copy that skips symlinks, so it can never follow a link out of the
/// cache. Nothing downstream misses them: the installer drops symlinks, and
/// `content_hash` counts only regular files.
fn copy_dir_contents(src: &Path, dst: &Path, cancel: Option<&Arc<AtomicBool>>) -> Result<()> {
    if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
        bail!("Installation cancelled");
    }
    std::fs::create_dir_all(dst).with_context(|| format!("Failed to create {}", dst.display()))?;
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            continue;
        }
        let target = dst.join(entry.file_name());
        if file_type.is_dir() {
            copy_dir_contents(&entry.path(), &target, cancel)?;
        } else {
            std::fs::copy(entry.path(), &target).with_context(|| {
                format!(
                    "Failed to copy {} to {}",
                    entry.path().display(),
                    target.display()
                )
            })?;
        }
    }
    Ok(())
}

/// `git -C <dir> <args…>` under the shared cancel/timeout policy.
///
/// These are not local-only commands. In a partial clone both `sparse-checkout`
/// and `checkout` fetch the blobs they are about to write, so they block on the
/// network exactly like a clone does and have to be just as cancellable — the
/// reason this exists rather than a plain `Command::output()`.
///
/// The proxy is passed per invocation rather than read from the cache's config:
/// `git clone -c` persisted whatever proxy was in effect when the cache was
/// created, and a command line `-c` is what lets a since-changed proxy win over
/// that stale value.
fn run_git_watched_at(
    dir: &Path,
    args: &[&str],
    proxy_url: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    on_progress: &Option<ProgressCallback>,
) -> Result<()> {
    let mut command = git_command();
    command.arg("-C").arg(dir);
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        command.arg("-c").arg(format!("http.proxy={proxy}"));
        command.arg("-c").arg(format!("https.proxy={proxy}"));
    }
    command.args(args);
    run_git_watched(command, cancel, on_progress)
}

/// Run a git subprocess under the shared cancel/timeout policy, forwarding its
/// stderr to `on_progress`.
///
/// The full-clone loop below is deliberately left inline rather than reshaped to
/// call this: it has no end-to-end test coverage, so the safe move is to add a
/// path beside it, not to rewrite it.
fn run_git_watched(
    mut command: Command,
    cancel: Option<&Arc<AtomicBool>>,
    on_progress: &Option<ProgressCallback>,
) -> Result<()> {
    let mut child = command
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn()
        .context("Failed to start git")?;

    let (stderr_rx, stderr_thread) =
        spawn_stderr_collector(child.stderr.take(), on_progress.is_some());
    let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);

    loop {
        if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
            let _ = child.kill();
            let _ = child.wait();
            bail!("Installation cancelled");
        }

        if let Some(ref cb) = on_progress {
            while let Ok(line) = stderr_rx.try_recv() {
                if !is_ssh_warning(&line) && !line.trim().is_empty() {
                    cb(&line);
                }
            }
        }

        match child.try_wait() {
            Ok(Some(status)) => {
                let collected = stderr_thread.join().unwrap_or_default();
                if status.success() {
                    return Ok(());
                }
                bail!("git exited with {}: {}", status, collected.trim());
            }
            Ok(None) => {
                if Instant::now() > deadline {
                    let _ = child.kill();
                    let _ = child.wait();
                    bail!("git timed out after {}s", CLONE_TIMEOUT_SECS);
                }
                std::thread::sleep(Duration::from_millis(100));
            }
            Err(e) => {
                let _ = child.kill();
                let _ = child.wait();
                bail!("Failed to wait for git: {e}")
            }
        }
    }
}

fn clone_repo_full(
    url: &str,
    branch: Option<&str>,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
    on_progress: Option<ProgressCallback>,
) -> Result<PathBuf> {
    let cached_dir = repo_cache_dir(url);
    let _cache_lock = lock_repo_cache(&cached_dir, &on_progress)?;

    // Try cached repo first.
    if cached_dir.exists() {
        match try_update_cached_repo(&cached_dir, url, branch, proxy_url, cancel, &on_progress) {
            Ok(true) => return materialize_cached_repo(&cached_dir, cancel),
            Ok(false) => { /* cache invalid, fall through to clone */ }
            Err(e) => {
                // Propagate cancellation.
                if e.to_string().contains("cancelled") || e.to_string().contains("canceled") {
                    return Err(e);
                }
                // Otherwise fall through to clone.
            }
        }
    }

    // Remove any leftover partial clone.
    let _ = std::fs::remove_dir_all(&cached_dir);
    prune_repo_cache(&cached_dir);

    let timeout = Duration::from_secs(CLONE_TIMEOUT_SECS);
    let mut system_git_stderr: Option<String> = None;

    // Try system git first (faster, supports SSH).
    let mut command = git_command();
    command.arg("clone").arg("--depth").arg("1");
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        command.arg("-c").arg(format!("http.proxy={proxy}"));
        command.arg("-c").arg(format!("https.proxy={proxy}"));
    }
    if let Some(branch) = branch {
        command.arg("--branch").arg(branch);
    }
    command.arg("--progress"); // Force progress output to stderr.
    let child = command
        .arg(url)
        .arg(&cached_dir)
        .stdout(Stdio::null())
        .stderr(Stdio::piped())
        .spawn();

    if let Ok(mut child) = child {
        let (stderr_rx, stderr_thread) =
            spawn_stderr_collector(child.stderr.take(), on_progress.is_some());

        let deadline = Instant::now() + timeout;
        loop {
            if cancel.is_some_and(|c| c.load(Ordering::SeqCst)) {
                let _ = child.kill();
                let _ = child.wait();
                let _ = std::fs::remove_dir_all(&cached_dir);
                anyhow::bail!("Installation cancelled");
            }

            // Forward progress lines from stderr thread.
            if let Some(ref cb) = on_progress {
                while let Ok(line) = stderr_rx.try_recv() {
                    if !is_ssh_warning(&line) && !line.trim().is_empty() {
                        cb(&line);
                    }
                }
            }

            match child.try_wait() {
                Ok(Some(status)) => {
                    let collected = stderr_thread.join().unwrap_or_default();
                    if status.success() {
                        return materialize_cached_repo(&cached_dir, cancel);
                    }
                    system_git_stderr = Some(collected);
                    // Clean up failed clone.
                    let _ = std::fs::remove_dir_all(&cached_dir);
                    break; // fall through to git2
                }
                Ok(None) => {
                    if Instant::now() > deadline {
                        let _ = child.kill();
                        let _ = child.wait();
                        let _ = std::fs::remove_dir_all(&cached_dir);
                        anyhow::bail!(
                            "Git clone timed out after {}s — check your network connection",
                            CLONE_TIMEOUT_SECS
                        );
                    }
                    std::thread::sleep(Duration::from_millis(200));
                }
                Err(_) => {
                    let _ = std::fs::remove_dir_all(&cached_dir);
                    break;
                }
            }
        }
    }

    // Fallback to git2 with timeout and shallow clone.
    if let Some(ref cb) = on_progress {
        cb("Trying alternative clone method…");
    }

    let mut builder = git2::build::RepoBuilder::new();
    if let Some(branch) = branch {
        builder.branch(branch);
    }

    let cancel_clone = cancel.cloned();
    let clone_deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
    let mut callbacks = git2::RemoteCallbacks::new();

    let progress_for_cb: Option<Arc<std::sync::Mutex<ProgressCallback>>> =
        on_progress.map(|cb| Arc::new(std::sync::Mutex::new(cb)));
    let progress_for_transfer = progress_for_cb.clone();

    callbacks.transfer_progress(move |stats| {
        if let Some(ref c) = cancel_clone {
            if c.load(Ordering::SeqCst) {
                return false;
            }
        }
        if Instant::now() > clone_deadline {
            return false;
        }
        if let Some(ref cb) = progress_for_transfer {
            if let Ok(cb) = cb.lock() {
                let msg = format!(
                    "Receiving objects: {}/{} ({:.1} KB)",
                    stats.received_objects(),
                    stats.total_objects(),
                    stats.received_bytes() as f64 / 1024.0
                );
                cb(&msg);
            }
        }
        true
    });

    git_credentials::install_git2_credentials(&mut callbacks, url);
    let mut fetch_opts = git2::FetchOptions::new();
    fetch_opts.remote_callbacks(callbacks);
    fetch_opts.depth(1);
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        let mut proxy_opts = git2::ProxyOptions::new();
        proxy_opts.url(proxy);
        fetch_opts.proxy_options(proxy_opts);
    }
    builder.fetch_options(fetch_opts);

    match builder.clone(url, &cached_dir) {
        Ok(_) => materialize_cached_repo(&cached_dir, cancel),
        Err(git2_err) => {
            // The pinned ref may be a tag, which the clone above cannot check
            // out. Retry in the shape that works before giving up.
            if let Some(pinned) = branch {
                if clone_tag_with_git2(url, pinned, &cached_dir, cancel, proxy_url).is_ok() {
                    return materialize_cached_repo(&cached_dir, cancel);
                }
            }
            let _ = std::fs::remove_dir_all(&cached_dir);
            // Include system git stderr in the error if available.
            let detail = system_git_stderr
                .filter(|s| !s.trim().is_empty())
                .map(|s| format!(" (system git: {})", s.trim()))
                .unwrap_or_default();
            anyhow::bail!("Failed to clone {}: {}{}", url, git2_err, detail)
        }
    }
}

/// Fetch a repository pinned to a **tag** with libgit2.
///
/// `RepoBuilder::branch` resolves its argument under `refs/remotes/origin/`, so
/// a tag fails there with "reference 'refs/remotes/origin/<tag>' not found".
/// Init an empty repo and shallow-fetch the tag ref directly instead, then
/// detach onto the commit it peels to — cloning the default branch first would
/// download a second snapshot nobody wants.
///
/// Integration tests accept an explicit HTTPS fixture; `file://` cannot do shallow fetches.
///
/// Only reachable when system git is missing or failed: system git's
/// `clone --branch` already accepts tags.
fn clone_tag_with_git2(
    url: &str,
    tag: &str,
    cached_dir: &Path,
    cancel: Option<&Arc<AtomicBool>>,
    proxy_url: Option<&str>,
) -> Result<()> {
    let _ = std::fs::remove_dir_all(cached_dir);
    let deadline = Instant::now() + Duration::from_secs(CLONE_TIMEOUT_SECS);
    let fetch_opts = || {
        let cancel = cancel.cloned();
        let mut callbacks = git2::RemoteCallbacks::new();
        callbacks.transfer_progress(move |_| {
            if cancel.as_ref().is_some_and(|c| c.load(Ordering::SeqCst)) {
                return false;
            }
            Instant::now() <= deadline
        });
        git_credentials::install_git2_credentials(&mut callbacks, url);
        let mut opts = git2::FetchOptions::new();
        opts.remote_callbacks(callbacks);
        opts.depth(1);
        if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
            let mut proxy_opts = git2::ProxyOptions::new();
            proxy_opts.url(proxy);
            opts.proxy_options(proxy_opts);
        }
        opts
    };

    let repo = git2::Repository::init(cached_dir)?;
    {
        // A named remote, not an anonymous one: the cache-reuse path identifies
        // a cached repo by `git remote get-url origin`.
        let mut remote = repo.remote("origin", url)?;
        let refspec = format!("+refs/tags/{tag}:refs/tags/{tag}");
        remote.fetch(&[refspec.as_str()], Some(&mut fetch_opts()), None)?;
    }
    let commit = repo.revparse_single(&format!("refs/tags/{tag}^{{commit}}"))?;
    repo.set_head_detached(commit.id())?;
    repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
    Ok(())
}

pub fn get_head_revision(repo_dir: &Path) -> Result<String> {
    let output = git_command()
        .arg("-C")
        .arg(repo_dir)
        .args(["rev-parse", "HEAD"])
        .output();

    if let Ok(output) = output {
        if output.status.success() {
            return Ok(String::from_utf8_lossy(&output.stdout).trim().to_string());
        }
    }

    let repo = Repository::open(repo_dir)?;
    let head = repo.head()?.peel_to_commit()?;
    Ok(head.id().to_string())
}

pub fn resolve_remote_revision(
    url: &str,
    branch: Option<&str>,
    proxy_url: Option<&str>,
) -> Result<String> {
    if let Ok(revision) = resolve_remote_revision_with_git(url, branch, proxy_url) {
        return Ok(revision);
    }

    let repo = Repository::init_bare(
        std::env::temp_dir().join(format!("agent-hub-remote-{}", uuid::Uuid::new_v4())),
    )?;
    let mut remote = repo.remote_anonymous(url)?;
    let mut proxy_opts = git2::ProxyOptions::new();
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        proxy_opts.url(proxy);
    }
    let mut callbacks = git2::RemoteCallbacks::new();
    git_credentials::install_git2_credentials(&mut callbacks, url);
    remote.connect_auth(Direction::Fetch, Some(callbacks), Some(proxy_opts))?;
    let refs = remote.list()?;

    for wanted in candidate_ref_names(branch) {
        if let Some(head) = refs.iter().find(|head| head.name() == wanted) {
            return Ok(head.oid().to_string());
        }
    }

    anyhow::bail!("Unable to resolve remote revision for {}", url)
}

pub fn checkout_revision(repo_dir: &Path, revision: &str) -> Result<()> {
    let status = git_command()
        .arg("-C")
        .arg(repo_dir)
        .args(["checkout", "--detach", revision])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status();

    if let Ok(status) = status {
        if status.success() {
            return Ok(());
        }
    }

    let repo = Repository::open(repo_dir)?;
    let oid = git2::Oid::from_str(revision)?;
    repo.set_head_detached(oid)?;
    repo.checkout_head(Some(git2::build::CheckoutBuilder::new().force()))?;
    Ok(())
}

pub fn relative_subpath(repo_dir: &Path, skill_dir: &Path) -> Option<String> {
    let relative = skill_dir.strip_prefix(repo_dir).ok()?;
    if relative.as_os_str().is_empty() {
        None
    } else {
        Some(relative.to_string_lossy().to_string())
    }
}

fn normalize_url(url: &str) -> (String, Option<String>, Option<String>) {
    let trimmed = url.trim();

    // Already a full URL
    if trimmed.starts_with("http://")
        || trimmed.starts_with("https://")
        || trimmed.starts_with("ssh://")
        || trimmed.starts_with("git@")
    {
        if let Some((clone_url, branch, subpath)) = parse_github_tree_url(trimmed) {
            return (clone_url, Some(branch), subpath);
        }
        return (trimmed.to_string(), None, None);
    }

    // Shorthand: user/repo
    if trimmed.contains('/') && !trimmed.contains(' ') {
        return (format!("https://github.com/{}.git", trimmed), None, None);
    }

    (trimmed.to_string(), None, None)
}

pub fn find_skill_dir(repo_dir: &Path, skill_id: Option<&str>) -> Result<PathBuf> {
    // If skill_id provided, look for it specifically. Each branch must validate
    // that the resolved dir actually contains a SKILL.md — otherwise it returns
    // a container/category dir that the installer will reject later with a
    // worse error.
    if let Some(id) = skill_id {
        let direct = repo_dir.join(id);
        if skill_metadata::is_valid_skill_dir(&direct) {
            return Ok(direct);
        }

        let in_skills = repo_dir.join("skills").join(id);
        if skill_metadata::is_valid_skill_dir(&in_skills) {
            return Ok(in_skills);
        }

        // Prefer the unified agent skills location over provider-specific
        // variants (e.g. `.cursor/skills`, `.claude/skills`). Repos that
        // publish per-provider variants typically also ship a generic copy
        // at `.agents/skills`; the recursive fallback below is non-deterministic
        // across filesystems, so without this check we may pick an arbitrary
        // provider's transformed variant.
        let in_agents = repo_dir.join(".agents").join("skills").join(id);
        if skill_metadata::is_valid_skill_dir(&in_agents) {
            return Ok(in_agents);
        }

        // Recursive search: match by directory name or SKILL.md name field.
        // The basename branch must check validity; the SKILL.md-name branch is
        // implicitly validated by parsing the frontmatter.
        let mut name_match: Option<PathBuf> = None;
        for e in walkdir::WalkDir::new(repo_dir)
            .max_depth(6)
            .into_iter()
            .flatten()
        {
            if e.file_type().is_dir() {
                if e.file_name().to_string_lossy() == id
                    && skill_metadata::is_valid_skill_dir(e.path())
                {
                    return Ok(e.path().to_path_buf());
                }
                if name_match.is_none() {
                    let meta = skill_metadata::parse_skill_md(e.path());
                    if meta.name.as_deref() == Some(id) {
                        name_match = Some(e.path().to_path_buf());
                    }
                }
            }
        }
        if let Some(path) = name_match {
            return Ok(path);
        }

        // A specific skill id was requested but nothing matched. Error instead
        // of falling through to a container/root — otherwise the installer would
        // copy the entire `skills/` container (or an unrelated root skill) under
        // the requested name, duplicating every skill in the repo. See issue #278.
        bail!("Skill '{}' not found in {}", id, repo_dir.display());
    }

    // No skill id requested — resolve a repo-wide skill location. The fallbacks
    // below are intended for enumeration flows (collect_git_skill_dirs walks the
    // resolved container to list individual skills), not for a single install.
    // Check if root is a skill
    let has_skill_md = ["SKILL.md", "skill.md"]
        .iter()
        .any(|f| repo_dir.join(f).exists());
    if has_skill_md {
        return Ok(repo_dir.to_path_buf());
    }

    // Check skills/ subdirectory
    let skills_subdir = repo_dir.join("skills");
    if skills_subdir.is_dir() {
        return Ok(skills_subdir);
    }

    let skill_subdir = repo_dir.join("skill");
    if skill_subdir.is_dir() {
        return Ok(skill_subdir);
    }

    // Default to root
    Ok(repo_dir.to_path_buf())
}

pub fn cleanup_temp(path: &Path) {
    let _ = std::fs::remove_dir_all(path);
}

fn parse_github_tree_url(url: &str) -> Option<(String, String, Option<String>)> {
    let (clone_url, path) = parse_github_tree_url_path(url)?;
    let (branch, subpath) = split_tree_branch_path(&path, &[]);
    Some((clone_url, branch, subpath))
}

/// Match a GitHub `…/tree/<path>` URL and return `(clone_url, path_after_tree)`.
/// The path is left unsplit so callers can disambiguate branch-vs-subpath with
/// knowledge of the actual remote branches.
fn parse_github_tree_url_path(url: &str) -> Option<(String, String)> {
    let re = regex::Regex::new(r"^(https://github\.com/[^/]+/[^/]+?)(?:\.git)?/tree/(.+)$").ok()?;
    let caps = re.captures(url)?;
    let clone_url = format!("{}.git", caps.get(1)?.as_str());
    let path = caps.get(2)?.as_str().to_string();
    Some((clone_url, path))
}

/// Split a `tree/<path>` tail against the remote's actual refs.
///
/// Branches are matched first: a tag may only claim a URL that no branch
/// explains. Matching the longest ref across heads and tags at once would let
/// a tag named `main/v1` swallow a URL that means branch `main` plus subpath
/// `v1/...`.
fn split_tree_path_with_known_refs(path: &str, known: &RemoteRefNames) -> (String, Option<String>) {
    match_known_ref(path, &known.heads)
        .or_else(|| match_known_ref(path, &known.tags))
        .unwrap_or_else(|| split_tree_branch_path(path, &[]))
}

/// Longest ref in `known` that matches a `/`-bounded prefix of `path`, split
/// into `(ref, optional subpath)`. `None` when nothing matches.
///
/// Callers must try branches before tags: taking the longest match across both
/// at once lets a tag named `main/v1` steal a URL that means branch `main`
/// plus subpath `v1/...`.
fn match_known_ref(path: &str, known: &[String]) -> Option<(String, Option<String>)> {
    let mut best: Option<&str> = None;
    for name in known {
        if name.is_empty() {
            continue;
        }
        let matches = path == name.as_str()
            || path
                .strip_prefix(name.as_str())
                .is_some_and(|rest| rest.starts_with('/'));
        if matches && best.map_or(true, |b: &str| name.len() > b.len()) {
            best = Some(name);
        }
    }
    best.map(|name| {
        let subpath = path
            .strip_prefix(name)
            .and_then(|rest| rest.strip_prefix('/'))
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string());
        (name.to_string(), subpath)
    })
}

/// Split a `tree/<path>` tail into `(branch, optional subpath)`.
///
/// GitHub tree URLs are ambiguous when the branch name contains a `/`
/// (e.g. `feature/x`). With an empty `known_branches`, fall back to the
/// optimistic interpretation: first segment is the branch, rest is subpath
/// (correct for the vast majority of repos that use single-segment branch names).
/// With a populated `known_branches`, pick the longest branch that matches a
/// `/`-bounded prefix of `path`.
fn split_tree_branch_path(path: &str, known_branches: &[String]) -> (String, Option<String>) {
    if let Some(hit) = match_known_ref(path, known_branches) {
        return hit;
    }

    let mut parts = path.splitn(2, '/');
    let branch = parts.next().unwrap_or("").to_string();
    let subpath = parts
        .next()
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string());
    (branch, subpath)
}

/// Network-aware variant of `parse_git_source`. For GitHub `…/tree/<path>` URLs
/// with multi-segment paths, queries `git ls-remote --heads` to resolve which
/// segments belong to the branch and which to the subpath. Falls back to the
/// optimistic (single-segment-branch) parse on network failure.
pub fn parse_git_source_resolved(url: &str, proxy_url: Option<&str>) -> ParsedGitSource {
    let mut parsed = parse_git_source(url);
    let original_url = parsed.original_url.clone();

    let Some((clone_url, path)) = parse_github_tree_url_path(&original_url) else {
        return parsed;
    };
    // No ambiguity if the tree path is a single segment.
    if !path.contains('/') {
        return parsed;
    }

    let known = match list_remote_ref_names(&clone_url, proxy_url) {
        Ok(refs) if !refs.is_empty() => refs,
        Ok(_) => {
            log::warn!(
                "ls-remote returned no refs for {}; using optimistic tree-URL parse",
                clone_url
            );
            return parsed;
        }
        Err(e) => {
            log::warn!(
                "ls-remote failed for {}: {} — using optimistic tree-URL parse (slash-ref URLs may parse incorrectly)",
                clone_url,
                e
            );
            return parsed;
        }
    };
    let (branch, subpath) = split_tree_path_with_known_refs(&path, &known);
    parsed.branch = Some(branch);
    parsed.subpath = subpath;
    parsed
}

/// Branch and tag names on the remote, used to split a `tree/<path>` URL.
///
/// Tags count: `tree/release/v1.0/skills/foo` is as valid a tag URL as it is a
/// branch URL, and listing only heads would silently split it as branch
/// `release` plus subpath `v1.0/skills/foo`. They stay in separate lists
/// because branches must be matched first.
#[derive(Debug, Default, PartialEq)]
struct RemoteRefNames {
    heads: Vec<String>,
    tags: Vec<String>,
}

impl RemoteRefNames {
    fn is_empty(&self) -> bool {
        self.heads.is_empty() && self.tags.is_empty()
    }
}

fn list_remote_ref_names(url: &str, proxy_url: Option<&str>) -> Result<RemoteRefNames> {
    let mut cmd = git_command();
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        cmd.arg("-c").arg(format!("http.proxy={proxy}"));
        cmd.arg("-c").arg(format!("https.proxy={proxy}"));
    }
    let output = cmd
        .args(["ls-remote", "--heads", "--tags", url])
        .output()
        .with_context(|| format!("Failed to list remote refs for {}", url))?;

    if !output.status.success() {
        anyhow::bail!("git ls-remote exited with {}", output.status);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(parse_remote_ref_names(&stdout))
}

fn parse_remote_ref_names(stdout: &str) -> RemoteRefNames {
    let mut refs = RemoteRefNames::default();
    for line in stdout.lines() {
        let mut parts = line.split_whitespace();
        let Some(_sha) = parts.next() else { continue };
        let Some(refname) = parts.next() else {
            continue;
        };
        // Peeled entries name the same tag; keep one entry per ref.
        if refname.ends_with("^{}") {
            continue;
        }
        if let Some(name) = refname.strip_prefix("refs/heads/") {
            refs.heads.push(name.to_string());
        } else if let Some(name) = refname.strip_prefix("refs/tags/") {
            refs.tags.push(name.to_string());
        }
    }
    refs
}

/// Ref names that a stored source ref may resolve to, most preferred first.
///
/// A source ref is stored as a bare name (`main`, `v0.8.0`) with no record of
/// whether it is a branch or a tag — GitHub `tree/` URLs do not distinguish
/// them either. Branches win over tags so an ambiguous name keeps its historic
/// meaning, and the peeled tag (`^{}`) wins over the tag object because only
/// the peeled line carries the commit an annotated tag points at.
fn candidate_ref_names(source_ref: Option<&str>) -> Vec<String> {
    match source_ref {
        Some(name) => vec![
            format!("refs/heads/{name}"),
            format!("refs/tags/{name}^{{}}"),
            format!("refs/tags/{name}"),
        ],
        None => vec!["HEAD".to_string()],
    }
}

/// Pick a revision out of `git ls-remote` output by exact ref name.
///
/// Never take "the first line": querying a tag returns both the tag object and
/// its peeled commit, and their order is the remote's business, not ours.
fn select_remote_revision(stdout: &str, candidates: &[String]) -> Option<String> {
    let refs: Vec<(&str, &str)> = stdout
        .lines()
        .filter_map(|line| {
            let mut parts = line.split_whitespace();
            let sha = parts.next()?;
            let name = parts.next()?;
            (!sha.is_empty()).then_some((name, sha))
        })
        .collect();

    candidates.iter().find_map(|wanted| {
        refs.iter()
            .find(|(name, _)| *name == wanted.as_str())
            .map(|(_, sha)| sha.to_string())
    })
}

fn resolve_remote_revision_with_git(
    url: &str,
    branch: Option<&str>,
    proxy_url: Option<&str>,
) -> Result<String> {
    let candidates = candidate_ref_names(branch);
    let mut cmd = git_command();
    if let Some(proxy) = proxy_url.filter(|s| !s.is_empty()) {
        cmd.arg("-c").arg(format!("http.proxy={proxy}"));
        cmd.arg("-c").arg(format!("https.proxy={proxy}"));
    }
    cmd.args(["ls-remote", url]);
    cmd.args(&candidates);
    let output = cmd
        .output()
        .with_context(|| format!("Failed to query remote {}", url))?;

    if !output.status.success() {
        anyhow::bail!("git ls-remote exited with {}", output.status);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    select_remote_revision(&stdout, &candidates)
        .ok_or_else(|| anyhow::anyhow!("No remote revision found"))
}

#[cfg(test)]
mod tests;

#[cfg(test)]
#[path = "git_fetcher/tag_tests.rs"]
mod tag_tests;