agpm-cli 0.4.3

AGent Package Manager - A Git-based package manager for Claude agents
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
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
//! Source repository management
//!
//! This module manages source repositories that contain Claude Code resources (agents, snippets, etc.).
//! Sources are Git repositories that are cloned/cached locally for efficient access and installation.
//! The module provides secure, efficient, and cross-platform repository handling with comprehensive
//! caching and authentication support.
//!
//! # Architecture Overview
//!
//! The source management system is built around two main components:
//!
//! - [`Source`] - Represents an individual repository with metadata and caching information
//! - [`SourceManager`] - Manages multiple sources with operations for syncing, verification, and caching
//!
//! # Source Configuration
//!
//! Sources can be defined in two locations with different purposes:
//!
//! 1. **Project manifest** (`agpm.toml`) - Committed to version control, shared with team
//!    ```toml
//!    [sources]
//!    community = "https://github.com/example/agpm-community.git"
//!    official = "https://github.com/example/agpm-official.git"
//!    ```
//!
//! 2. **Global config** (`~/.agpm/config.toml`) - User-specific with authentication tokens
//!    ```toml
//!    [sources]
//!    private = "https://oauth2:ghp_xxxx@github.com/company/private-agpm.git"
//!    ```
//!
//! ## Source Priority and Security
//!
//! When sources are defined in both locations with the same name:
//! - Global sources are loaded first (contain authentication tokens)
//! - Local sources override global ones (for project-specific customization)
//! - Authentication tokens are kept separate from version control for security
//!
//! # Caching Architecture
//!
//! The caching system provides efficient repository management:
//!
//! ## Cache Directory Structure
//!
//! ```text
//! ~/.agpm/cache/
//! └── sources/
//!     ├── owner1_repo1/          # Cached repository
//!     │   ├── .git/              # Git metadata
//!     │   ├── agents/            # Resource files
//!     │   └── snippets/
//!     └── owner2_repo2/
//!         └── ...
//! ```
//!
//! ## Cache Naming Convention
//!
//! Cache directories are named using the pattern `{owner}_{repository}` parsed from the Git URL.
//! For invalid URLs, falls back to `unknown_{source_name}`.
//!
//! ## Caching Strategy
//!
//! - **First Access**: Repository is cloned to cache directory
//! - **Subsequent Access**: Use cached copy, fetch updates if needed  
//! - **Validation**: Cache integrity is verified before use
//! - **Cleanup**: Invalid cache directories are automatically removed and re-cloned
//!
//! # Authentication Integration
//!
//! Authentication is handled transparently through the global configuration:
//!
//! - **Public repositories**: No authentication required
//! - **Private repositories**: Authentication tokens embedded in URLs in global config
//! - **Security**: Tokens never stored in project manifests or committed to version control
//! - **Format**: Standard Git URL format with embedded credentials
//!
//! ## Supported Authentication Methods
//!
//! - OAuth tokens: `https://oauth2:token@github.com/repo.git`
//! - Personal access tokens: `https://username:token@github.com/repo.git`
//! - SSH keys: `git@github.com:owner/repo.git` (uses system SSH configuration)
//!
//! # Repository Types
//!
//! The module supports multiple repository types:
//!
//! ## Remote Repositories
//! - **HTTPS**: `https://github.com/owner/repo.git`
//! - **SSH**: `git@github.com:owner/repo.git`
//!
//! ## Local Repositories
//! - **Absolute paths**: `/path/to/local/repo`
//! - **Relative paths**: `../local-repo` or `./local-repo`
//! - **File URLs**: `file:///absolute/path/to/repo`
//!
//! # Synchronization Operations
//!
//! Synchronization ensures local caches are up-to-date with remote repositories:
//!
//! ## Sync Operations
//! - **Clone**: First-time repository retrieval
//! - **Fetch**: Update remote references without merging
//! - **Validation**: Verify repository integrity and accessibility
//! - **Parallel**: Multiple repositories can be synced concurrently
//!
//! ## Offline Capabilities
//! - Cached repositories can be used offline
//! - Sync operations gracefully handle network failures
//! - Local repositories work without network access
//!
//! # Error Handling
//!
//! The module provides comprehensive error handling for common scenarios:
//!
//! - **Network failures**: Graceful degradation with cached repositories
//! - **Authentication failures**: Clear error messages with resolution hints
//! - **Invalid repositories**: Automatic cleanup and re-cloning
//! - **Path issues**: Cross-platform path handling and validation
//!
//! # Performance Considerations
//!
//! ## Optimization Strategies
//! - **Lazy loading**: Sources are only cloned when needed
//! - **Incremental updates**: Only fetch changes, not full re-clone
//! - **Parallel operations**: Multiple repositories synced concurrently
//! - **Cache reuse**: Minimize redundant network operations
//!
//! ## Resource Management
//! - **Memory efficient**: Repositories are accessed on-demand
//! - **Disk usage**: Cache cleanup for removed sources
//! - **Network optimization**: Minimal data transfer through Git's efficient protocol
//!
//! # Cross-Platform Compatibility
//!
//! Full support for Windows, macOS, and Linux:
//! - **Path handling**: Correct path separators and absolute path resolution
//! - **Git command**: Uses system git with platform-specific optimizations
//! - **File permissions**: Proper handling across different filesystems
//! - **Authentication**: Works with platform-specific credential managers
//!
//! # Usage Examples
//!
//! ## Basic Source Management
//! ```rust,no_run
//! use agpm_cli::source::{Source, SourceManager};
//! use agpm_cli::manifest::Manifest;
//! use std::path::Path;
//!
//! # async fn example() -> anyhow::Result<()> {
//! // Load from manifest with global config integration
//! let manifest = Manifest::load(Path::new("agpm.toml"))?;
//! let mut manager = SourceManager::from_manifest_with_global(&manifest).await?;
//!
//! // Sync a specific source
//! let repo = manager.sync("community").await?;
//! println!("Repository ready at: {:?}", repo.path());
//!
//! // List all available sources
//! for source in manager.list() {
//!     println!("Source: {} -> {}", source.name, source.url);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! ## Progress Monitoring
//! ```rust,no_run
//! use agpm_cli::source::SourceManager;
//! use indicatif::ProgressBar;
//!
//! # async fn example(manager: &mut SourceManager) -> anyhow::Result<()> {
//! let progress = ProgressBar::new(100);
//! progress.set_message("Syncing repositories...");
//!
//! // Sync all sources
//! manager.sync_all().await?;
//!
//! progress.finish_with_message("All sources synced successfully");
//! # Ok(())
//! # }
//! ```
//!
//! ## Direct URL Operations
//! ```rust,no_run
//! use agpm_cli::source::SourceManager;
//!
//! # async fn example(manager: &mut SourceManager) -> anyhow::Result<()> {
//! // Sync a repository by URL (for direct dependencies)
//! let repo = manager.sync_by_url(
//!     "https://github.com/example/dependency.git"
//! ).await?;
//!
//! // Access the cached repository
//! let cache_path = manager.get_cached_path(
//!     "https://github.com/example/dependency.git"
//! )?;
//! # Ok(())
//! # }
//! ```

use crate::cache::lock::CacheLock;
use crate::config::GlobalConfig;
use crate::core::AgpmError;
use crate::git::{GitRepo, parse_git_url};
use crate::manifest::Manifest;
use crate::utils::fs::ensure_dir;
use crate::utils::security::validate_path_security;
use anyhow::{Context, Result};
use futures::future::join_all;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Represents a Git repository source containing Claude Code resources.
///
/// A [`Source`] defines a repository location and metadata for accessing Claude Code
/// resources like agents and snippets. Sources can be remote repositories (GitHub, GitLab, etc.)
/// or local file paths, and support various authentication mechanisms.
///
/// # Fields
///
/// - `name`: Unique identifier for the source (used in manifests and commands)
/// - `url`: Repository location (HTTPS, SSH, file://, or local path)
/// - `description`: Optional human-readable description
/// - `enabled`: Whether this source should be used for operations
/// - `local_path`: Runtime cache location (not serialized, set during sync operations)
///
/// # Repository URL Formats
///
/// ## Remote Repositories
/// - HTTPS: `https://github.com/owner/repo.git`
/// - SSH: `git@github.com:owner/repo.git`
/// - HTTPS with auth: `https://token@github.com/owner/repo.git`
///
/// ## Local Repositories
/// - Absolute path: `/path/to/repository`
/// - Relative path: `../relative/path` or `./local-path`
/// - File URL: `file:///absolute/path/to/repository`
///
/// # Security Considerations
///
/// Authentication tokens should never be stored in [`Source`] instances that are
/// serialized to project manifests. Use the global configuration for credentials.
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::source::Source;
///
/// // Public repository
/// let source = Source::new(
///     "community".to_string(),
///     "https://github.com/example/agpm-community.git".to_string()
/// ).with_description("Community resources".to_string());
///
/// // Local development repository
/// let local = Source::new(
///     "local-dev".to_string(),
///     "/path/to/local/repo".to_string()
/// );
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Source {
    /// Unique identifier for this source
    pub name: String,
    /// Repository URL or local path
    pub url: String,
    /// Optional human-readable description
    pub description: Option<String>,
    /// Whether this source is enabled for operations
    pub enabled: bool,
    /// Runtime path to cached repository (not serialized)
    #[serde(skip)]
    pub local_path: Option<PathBuf>,
}

impl Source {
    /// Creates a new source with the given name and URL.
    ///
    /// The source is created with default settings:
    /// - No description
    /// - Enabled by default
    /// - No local path (will be set during sync operations)
    ///
    /// # Arguments
    ///
    /// * `name` - Unique identifier for this source
    /// * `url` - Repository URL or local path
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::Source;
    ///
    /// let source = Source::new(
    ///     "official".to_string(),
    ///     "https://github.com/example/agpm-official.git".to_string()
    /// );
    ///
    /// assert_eq!(source.name, "official");
    /// assert!(source.enabled);
    /// assert!(source.description.is_none());
    /// ```
    #[must_use]
    pub const fn new(name: String, url: String) -> Self {
        Self {
            name,
            url,
            description: None,
            enabled: true,
            local_path: None,
        }
    }

    /// Adds a human-readable description to this source.
    ///
    /// This is a builder pattern method that consumes the source and returns it
    /// with the description field set. Descriptions help users understand the
    /// purpose and contents of each source.
    ///
    /// # Arguments
    ///
    /// * `desc` - Human-readable description of the source
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::Source;
    ///
    /// let source = Source::new(
    ///     "community".to_string(),
    ///     "https://github.com/example/agpm-community.git".to_string()
    /// ).with_description("Community-contributed agents and snippets".to_string());
    ///
    /// assert_eq!(source.description, Some("Community-contributed agents and snippets".to_string()));
    /// ```
    #[must_use]
    pub fn with_description(mut self, desc: String) -> Self {
        self.description = Some(desc);
        self
    }

    /// Generates the cache directory path for this source.
    ///
    /// Creates a unique cache directory name based on the repository URL to avoid
    /// conflicts between sources. The directory name follows the pattern `{owner}_{repo}`
    /// parsed from the Git URL.
    ///
    /// # Cache Directory Structure
    ///
    /// - For `https://github.com/owner/repo.git` → `{base_dir}/sources/owner_repo`
    /// - For invalid URLs → `{base_dir}/sources/unknown_{source_name}`
    ///
    /// # Arguments
    ///
    /// * `base_dir` - Base cache directory (typically `~/.agpm/cache`)
    ///
    /// # Returns
    ///
    /// [`PathBuf`] pointing to the cache directory for this source
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::Source;
    /// use std::path::Path;
    ///
    /// let source = Source::new(
    ///     "community".to_string(),
    ///     "https://github.com/example/agpm-community.git".to_string()
    /// );
    ///
    /// let base_dir = Path::new("/home/user/.agpm/cache");
    /// let cache_dir = source.cache_dir(base_dir);
    ///
    /// assert_eq!(
    ///     cache_dir,
    ///     Path::new("/home/user/.agpm/cache/sources/example_agpm-community")
    /// );
    /// ```
    #[must_use]
    pub fn cache_dir(&self, base_dir: &Path) -> PathBuf {
        let (owner, repo) =
            parse_git_url(&self.url).unwrap_or(("unknown".to_string(), self.name.clone()));
        base_dir.join("sources").join(format!("{owner}_{repo}"))
    }
}

/// Manages multiple source repositories with caching, synchronization, and verification.
///
/// [`SourceManager`] is the central component for handling source repositories in AGPM.
/// It provides operations for adding, removing, syncing, and verifying sources while
/// maintaining a local cache for efficient access. The manager handles both remote
/// repositories and local file paths with comprehensive error handling and progress reporting.
///
/// # Core Responsibilities
///
/// - **Source Registry**: Maintains a collection of named sources
/// - **Cache Management**: Handles local caching of repository content
/// - **Synchronization**: Keeps cached repositories up-to-date
/// - **Verification**: Ensures repositories are accessible and valid
/// - **Authentication**: Integrates with global configuration for private repositories
/// - **Progress Reporting**: Provides feedback during long-running operations
///
/// # Cache Management
///
/// The manager maintains a cache directory (typically `~/.agpm/cache/sources/`) where
/// each source is stored in a subdirectory named after the repository owner and name.
/// The cache provides:
///
/// - **Persistence**: Repositories remain cached between operations
/// - **Efficiency**: Avoid re-downloading unchanged repositories
/// - **Offline Access**: Use cached content when network is unavailable
/// - **Integrity**: Validate cache consistency and auto-repair when needed
///
/// # Thread Safety
///
/// [`SourceManager`] is designed for single-threaded use but can be cloned for use
/// across multiple operations. For concurrent access, wrap in appropriate synchronization
/// primitives like `Arc` and `Mutex`.
///
/// # Examples
///
/// ## Basic Usage
/// ```rust,no_run
/// use agpm_cli::source::{Source, SourceManager};
/// use anyhow::Result;
///
/// # async fn example() -> Result<()> {
/// // Create a new manager
/// let mut manager = SourceManager::new()?;
///
/// // Add a source
/// let source = Source::new(
///     "community".to_string(),
///     "https://github.com/example/agpm-community.git".to_string()
/// );
/// manager.add(source)?;
///
/// // Sync the repository
/// let repo = manager.sync("community").await?;
/// println!("Repository synced to: {:?}", repo.path());
/// # Ok(())
/// # }
/// ```
///
/// ## Loading from Manifest
/// ```rust,no_run
/// use agpm_cli::source::SourceManager;
/// use agpm_cli::manifest::Manifest;
/// use std::path::Path;
///
/// # async fn example() -> anyhow::Result<()> {
/// // Load sources from project manifest and global config
/// let manifest = Manifest::load(Path::new("agpm.toml"))?;
/// let manager = SourceManager::from_manifest_with_global(&manifest).await?;
///
/// println!("Loaded {} sources", manager.list().len());
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct SourceManager {
    /// Collection of managed sources, indexed by name
    sources: HashMap<String, Source>,
    /// Base directory for caching repositories
    cache_dir: PathBuf,
}

/// Helper function to detect if a URL represents a local filesystem path
fn is_local_filesystem_path(url: &str) -> bool {
    // Unix-style relative paths
    if url.starts_with('/') || url.starts_with("./") || url.starts_with("../") {
        return true;
    }

    // Windows absolute paths (e.g., C:\path or C:/path)
    #[cfg(windows)]
    {
        // Check for drive letter pattern: X:\ or X:/
        if url.len() >= 3 {
            let chars: Vec<char> = url.chars().collect();
            if chars.len() >= 3
                && chars[0].is_ascii_alphabetic()
                && chars[1] == ':'
                && (chars[2] == '\\' || chars[2] == '/')
            {
                return true;
            }
        }
        // UNC paths (\\server\share)
        if url.starts_with("\\\\") {
            return true;
        }
    }

    false
}

impl SourceManager {
    /// Creates a new source manager with the default cache directory.
    ///
    /// The cache directory is determined by the system configuration, typically
    /// `~/.agpm/cache/` on Unix systems or `%APPDATA%\agpm\cache\` on Windows.
    ///
    /// # Errors
    ///
    /// Returns an error if the cache directory cannot be determined or created.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let manager = SourceManager::new()?;
    /// println!("Manager created with {} sources", manager.list().len());
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Result<Self> {
        let cache_dir = crate::config::get_cache_dir()?;
        Ok(Self {
            sources: HashMap::new(),
            cache_dir,
        })
    }

    /// Creates a new source manager with a custom cache directory.
    ///
    /// This constructor is primarily used for testing and scenarios where a specific
    /// cache location is required. For normal usage, prefer [`SourceManager::new()`].
    ///
    /// # Arguments
    ///
    /// * `cache_dir` - Custom directory for caching repositories
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    /// use std::path::PathBuf;
    ///
    /// let custom_cache = PathBuf::from("/custom/cache/location");
    /// let manager = SourceManager::new_with_cache(custom_cache);
    /// ```
    #[must_use]
    pub fn new_with_cache(cache_dir: PathBuf) -> Self {
        Self {
            sources: HashMap::new(),
            cache_dir,
        }
    }

    /// Creates a source manager from a manifest file (without global config integration).
    ///
    /// This method loads only sources defined in the project manifest, without merging
    /// with global configuration. Use [`from_manifest_with_global()`] for full integration
    /// that includes authentication tokens and private repositories.
    ///
    /// This method is primarily for backward compatibility and testing scenarios.
    ///
    /// # Arguments
    ///
    /// * `manifest` - Project manifest containing source definitions
    ///
    /// # Errors
    ///
    /// Returns an error if the cache directory cannot be determined.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    /// use agpm_cli::manifest::Manifest;
    /// use std::path::Path;
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let manifest = Manifest::load(Path::new("agpm.toml"))?;
    /// let manager = SourceManager::from_manifest(&manifest)?;
    ///
    /// println!("Loaded {} sources from manifest", manager.list().len());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`from_manifest_with_global()`]: SourceManager::from_manifest_with_global
    pub fn from_manifest(manifest: &Manifest) -> Result<Self> {
        let cache_dir = crate::config::get_cache_dir()?;
        let mut manager = Self::new_with_cache(cache_dir);

        // Load all sources from the manifest
        for (name, url) in &manifest.sources {
            let source = Source::new(name.clone(), url.clone());
            manager.sources.insert(name.clone(), source);
        }

        Ok(manager)
    }

    /// Creates a source manager from manifest with global configuration integration.
    ///
    /// This is the recommended method for creating a [`SourceManager`] in production use.
    /// It merges sources from both the project manifest and global configuration, enabling:
    ///
    /// - **Authentication**: Access to private repositories with embedded credentials
    /// - **User customization**: Global sources that extend project-defined sources
    /// - **Security**: Credentials stored safely outside version control
    ///
    /// # Source Resolution Priority
    ///
    /// 1. **Global sources**: Loaded first (may contain authentication tokens)
    /// 2. **Local sources**: Override global sources with same names
    /// 3. **Merged result**: Final source collection used by the manager
    ///
    /// # Arguments
    ///
    /// * `manifest` - Project manifest containing source definitions
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Cache directory cannot be determined
    /// - Global configuration cannot be loaded (though this is non-fatal)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    /// use agpm_cli::manifest::Manifest;
    /// use std::path::Path;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let manifest = Manifest::load(Path::new("agpm.toml"))?;
    /// let manager = SourceManager::from_manifest_with_global(&manifest).await?;
    ///
    /// // Manager now includes both project and global sources
    /// for source in manager.list() {
    ///     println!("Available source: {} -> {}", source.name, source.url);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn from_manifest_with_global(manifest: &Manifest) -> Result<Self> {
        let cache_dir = crate::config::get_cache_dir()?;
        let mut manager = Self::new_with_cache(cache_dir);

        // Load global config and merge sources
        let global_config = GlobalConfig::load().await.unwrap_or_default();
        let merged_sources = global_config.merge_sources(&manifest.sources);

        // Load all merged sources
        for (name, url) in &merged_sources {
            let source = Source::new(name.clone(), url.clone());
            manager.sources.insert(name.clone(), source);
        }

        Ok(manager)
    }

    /// Creates a source manager from manifest with a custom cache directory.
    ///
    /// This method is primarily used for testing where a specific cache location is needed.
    /// It loads only sources from the manifest without global configuration integration.
    ///
    /// # Arguments
    ///
    /// * `manifest` - Project manifest containing source definitions  
    /// * `cache_dir` - Custom directory for caching repositories
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    /// use agpm_cli::manifest::Manifest;
    /// use std::path::{Path, PathBuf};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let manifest = Manifest::load(Path::new("agpm.toml"))?;
    /// let custom_cache = PathBuf::from("/tmp/test-cache");
    /// let manager = SourceManager::from_manifest_with_cache(&manifest, custom_cache);
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn from_manifest_with_cache(manifest: &Manifest, cache_dir: PathBuf) -> Self {
        let mut manager = Self::new_with_cache(cache_dir);

        // Load all sources from the manifest
        for (name, url) in &manifest.sources {
            let source = Source::new(name.clone(), url.clone());
            manager.sources.insert(name.clone(), source);
        }

        manager
    }

    /// Adds a new source to the manager.
    ///
    /// The source name must be unique within this manager. Adding a source with an
    /// existing name will return an error.
    ///
    /// # Arguments
    ///
    /// * `source` - The source to add to the manager
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::ConfigError`] if a source with the same name already exists.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    ///
    /// let source = Source::new(
    ///     "community".to_string(),
    ///     "https://github.com/example/agpm-community.git".to_string()
    /// );
    ///
    /// manager.add(source)?;
    /// assert!(manager.get("community").is_some());
    /// # Ok(())
    /// # }
    /// ```
    pub fn add(&mut self, source: Source) -> Result<()> {
        if self.sources.contains_key(&source.name) {
            return Err(AgpmError::ConfigError {
                message: format!("Source '{}' already exists", source.name),
            }
            .into());
        }

        self.sources.insert(source.name.clone(), source);
        Ok(())
    }

    /// Removes a source from the manager and cleans up its cache.
    ///
    /// This operation permanently removes the source from the manager and deletes
    /// its cached repository data from disk. This cannot be undone, though the
    /// repository can be re-added and will be cloned again on next sync.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to remove
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The source does not exist ([`AgpmError::SourceNotFound`])
    /// - The cache directory cannot be removed due to filesystem permissions
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    ///
    /// // Add and then remove a source
    /// let source = Source::new("temp".to_string(), "https://github.com/temp/repo.git".to_string());
    /// manager.add(source)?;
    /// manager.remove("temp").await?;
    ///
    /// assert!(manager.get("temp").is_none());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn remove(&mut self, name: &str) -> Result<()> {
        if !self.sources.contains_key(name) {
            return Err(AgpmError::SourceNotFound {
                name: name.to_string(),
            }
            .into());
        }

        self.sources.remove(name);

        let source_cache = self.cache_dir.join("sources").join(name);
        if source_cache.exists() {
            tokio::fs::remove_dir_all(&source_cache)
                .await
                .context("Failed to remove source cache")?;
        }

        Ok(())
    }

    /// Gets a reference to a source by name.
    ///
    /// Returns [`None`] if no source with the given name exists.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to retrieve
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
    /// manager.add(source)?;
    ///
    /// if let Some(source) = manager.get("test") {
    ///     println!("Found source: {} -> {}", source.name, source.url);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&Source> {
        self.sources.get(name)
    }

    /// Gets a mutable reference to a source by name.
    ///
    /// Returns [`None`] if no source with the given name exists. Use this method
    /// when you need to modify source properties like description or enabled status.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to retrieve
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
    /// manager.add(source)?;
    ///
    /// if let Some(source) = manager.get_mut("test") {
    ///     source.description = Some("Updated description".to_string());
    ///     source.enabled = false;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_mut(&mut self, name: &str) -> Option<&mut Source> {
        self.sources.get_mut(name)
    }

    /// Returns a list of all sources managed by this manager.
    ///
    /// The returned vector contains references to all sources, both enabled and disabled.
    /// For only enabled sources, use [`list_enabled()`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let manager = SourceManager::new()?;
    ///
    /// for source in manager.list() {
    ///     println!("Source: {} -> {} (enabled: {})",
    ///         source.name, source.url, source.enabled);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`list_enabled()`]: SourceManager::list_enabled
    #[must_use]
    pub fn list(&self) -> Vec<&Source> {
        self.sources.values().collect()
    }

    /// Returns a list of enabled sources managed by this manager.
    ///
    /// Only sources with `enabled: true` are included in the result. This is useful
    /// for operations that should only work with active sources.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let manager = SourceManager::new()?;
    ///
    /// println!("Enabled sources: {}", manager.list_enabled().len());
    /// for source in manager.list_enabled() {
    ///     println!("  {} -> {}", source.name, source.url);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn list_enabled(&self) -> Vec<&Source> {
        self.sources.values().filter(|s| s.enabled).collect()
    }

    /// Gets the URL of a source by name.
    ///
    /// Returns the repository URL for the named source, or [`None`] if the source doesn't exist.
    /// This is useful for logging and debugging purposes.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to get the URL for
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
    /// manager.add(source)?;
    ///
    /// if let Some(url) = manager.get_source_url("test") {
    ///     println!("Source URL: {}", url);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn get_source_url(&self, name: &str) -> Option<String> {
        self.sources.get(name).map(|s| s.url.clone())
    }

    /// Synchronizes a source repository to the local cache.
    ///
    /// This is the core method for ensuring a source repository is available locally.
    /// It handles both initial cloning and subsequent updates, with intelligent caching
    /// and error recovery.
    ///
    /// # Synchronization Process
    ///
    /// 1. **Validation**: Check that the source exists and is enabled
    /// 2. **Cache Check**: Determine if repository is already cached
    /// 3. **Repository Type Detection**: Handle remote vs local repositories
    /// 4. **Sync Operation**:
    ///    - **First time**: Clone the repository to cache
    ///    - **Subsequent**: Fetch updates from remote
    ///    - **Invalid cache**: Remove corrupted cache and re-clone
    /// 5. **Cache Update**: Update source's `local_path` with cache location
    ///
    /// # Repository Types Supported
    ///
    /// ## Remote Repositories
    /// - **HTTPS**: `https://github.com/owner/repo.git`  
    /// - **SSH**: `git@github.com:owner/repo.git`
    ///
    /// ## Local Repositories  
    /// - **Absolute paths**: `/absolute/path/to/repo`
    /// - **Relative paths**: `../relative/path` or `./local-path`
    /// - **File URLs**: `file:///absolute/path/to/repo`
    ///
    /// # Authentication
    ///
    /// Authentication is handled transparently through URLs with embedded credentials
    /// from the global configuration. Private repositories should have their authentication
    /// tokens configured in `~/.agpm/config.toml`.
    ///
    /// # Error Handling
    ///
    /// The method provides comprehensive error handling for common scenarios:
    /// - **Source not found**: Clear error with source name
    /// - **Disabled source**: Prevents operations on disabled sources  
    /// - **Network failures**: Graceful handling with context
    /// - **Invalid repositories**: Validation of Git repository structure
    /// - **Cache corruption**: Automatic cleanup and re-cloning
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to synchronize
    /// * `progress` - Optional progress bar for user feedback during long operations
    ///
    /// # Returns
    ///
    /// Returns a [`GitRepo`] instance pointing to the synchronized repository cache.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Source doesn't exist ([`AgpmError::SourceNotFound`])
    /// - Source is disabled ([`AgpmError::ConfigError`])
    /// - Repository is not accessible (network, permissions, etc.)
    /// - Local path doesn't exist or isn't a Git repository
    /// - Cache directory cannot be created
    ///
    /// # Examples
    ///
    /// ## Basic Synchronization
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new(
    ///     "community".to_string(),
    ///     "https://github.com/example/agpm-community.git".to_string()
    /// );
    /// manager.add(source)?;
    ///
    /// // Sync without progress feedback
    /// let repo = manager.sync("community").await?;
    /// println!("Repository available at: {:?}", repo.path());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Synchronization with Progress
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    /// use indicatif::ProgressBar;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new(
    ///     "large-repo".to_string(),
    ///     "https://github.com/example/large-repository.git".to_string()
    /// );
    /// manager.add(source)?;
    ///
    /// // Sync repository
    /// let progress = ProgressBar::new(100);
    /// progress.set_message("Syncing large repository...");
    ///
    /// let repo = manager.sync("large-repo").await?;
    /// progress.finish_with_message("Repository synced successfully");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sync(&mut self, name: &str) -> Result<GitRepo> {
        let source = self.sources.get(name).ok_or_else(|| AgpmError::SourceNotFound {
            name: name.to_string(),
        })?;

        if !source.enabled {
            return Err(AgpmError::ConfigError {
                message: format!("Source '{name}' is disabled"),
            }
            .into());
        }

        let cache_path = source.cache_dir(&self.cache_dir);
        ensure_dir(cache_path.parent().unwrap())?;

        // Use the URL directly (auth tokens are already embedded in URLs from global config)
        let url = source.url.clone();

        // Distinguish between plain directories and git repositories
        let is_local_path = is_local_filesystem_path(&url);
        let is_file_url = url.starts_with("file://");

        // Acquire lock for this source to prevent concurrent git operations
        // This prevents issues like concurrent "git remote set-url" commands
        let _lock = CacheLock::acquire(&self.cache_dir, name).await?;

        let repo = if is_local_path {
            // Local paths are treated as plain directories (not git repositories)
            // Apply security validation for local paths
            let resolved_path = crate::utils::platform::resolve_path(&url)?;

            // Security check: Validate path against blacklist and symlinks BEFORE canonicalization
            validate_path_security(&resolved_path, true)?;

            let canonical_path = crate::utils::safe_canonicalize(&resolved_path)
                .map_err(|_| anyhow::anyhow!("Local path is not accessible or does not exist"))?;

            // For local paths, we just return a GitRepo pointing to the local directory
            // No cloning or fetching needed - these are treated as plain directories
            GitRepo::new(canonical_path)
        } else if is_file_url {
            // file:// URLs must point to valid git repositories
            let path_str = url.strip_prefix("file://").unwrap();

            // On Windows, convert forward slashes back to backslashes
            #[cfg(windows)]
            let path_str = path_str.replace('/', "\\");
            #[cfg(not(windows))]
            let path_str = path_str.to_string();

            let abs_path = PathBuf::from(path_str);

            // Check if the local path exists and is a git repo
            if !abs_path.exists() {
                return Err(anyhow::anyhow!(
                    "Local repository path does not exist or is not accessible: {}",
                    abs_path.display()
                ));
            }

            // Check if it's a git repository (either regular or bare)
            if !crate::git::is_git_repository(&abs_path) {
                return Err(anyhow::anyhow!(
                    "Specified path is not a git repository. file:// URLs must point to valid git repositories."
                ));
            }

            if cache_path.exists() {
                let repo = GitRepo::new(&cache_path);
                if repo.is_git_repo() {
                    // For file:// repos, fetch to get latest changes
                    repo.fetch(Some(&url)).await?;
                    repo
                } else {
                    tokio::fs::remove_dir_all(&cache_path)
                        .await
                        .context("Failed to remove invalid cache directory")?;
                    GitRepo::clone(&url, &cache_path).await?
                }
            } else {
                GitRepo::clone(&url, &cache_path).await?
            }
        } else if cache_path.exists() {
            let repo = GitRepo::new(&cache_path);
            if repo.is_git_repo() {
                // Always fetch for all URLs to get latest changes
                repo.fetch(Some(&url)).await?;
                repo
            } else {
                tokio::fs::remove_dir_all(&cache_path)
                    .await
                    .context("Failed to remove invalid cache directory")?;
                GitRepo::clone(&url, &cache_path).await?
            }
        } else {
            GitRepo::clone(&url, &cache_path).await?
        };

        if let Some(source) = self.sources.get_mut(name) {
            source.local_path = Some(cache_path);
        }

        Ok(repo)
    }

    /// Synchronizes a repository by URL without adding it as a named source.
    ///
    /// This method is used for direct Git dependencies that are referenced by URL rather
    /// than by source name. It's particularly useful for one-off repository access or
    /// when dealing with dependencies that don't need to be permanently registered.
    ///
    /// # Key Differences from `sync()`
    ///
    /// - **No source registration**: Repository is not added to the manager's source list
    /// - **URL-based caching**: Cache directory is derived from the URL structure
    /// - **Direct access**: Bypasses source name resolution and enablement checks
    /// - **Temporary usage**: Ideal for short-lived or one-time repository access
    ///
    /// # Cache Management
    ///
    /// The cache directory is generated using the same pattern as named sources:
    /// `{cache_dir}/sources/{owner}_{repository}` where owner and repository are
    /// parsed from the Git URL.
    ///
    /// # Repository Types
    ///
    /// Supports the same repository types as `sync()`:
    /// - Remote HTTPS/SSH repositories
    /// - Local file paths and file:// URLs
    /// - Proper validation for all repository types
    ///
    /// # Arguments
    ///
    /// * `url` - Repository URL or local path to synchronize
    /// * `progress` - Optional progress bar for user feedback
    ///
    /// # Returns
    ///
    /// Returns a [`GitRepo`] instance pointing to the cached repository.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Repository URL is invalid or inaccessible
    /// - Local path doesn't exist or isn't a Git repository  
    /// - Network connectivity issues for remote repositories
    /// - Filesystem permission issues
    ///
    /// # Examples
    ///
    /// ## Direct Repository Access
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    ///
    /// // Sync a repository directly by URL
    /// let repo = manager.sync_by_url(
    ///     "https://github.com/example/direct-dependency.git"
    /// ).await?;
    ///
    /// println!("Direct repository available at: {:?}", repo.path());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Local Repository Access
    /// ```rust,no_run
    /// use agpm_cli::source::SourceManager;
    /// use std::env;
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    ///
    /// // Access a local development repository
    /// let local_path = env::temp_dir().join("development").join("repo");
    /// let repo = manager.sync_by_url(
    ///     &local_path.to_string_lossy()
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sync_by_url(&self, url: &str) -> Result<GitRepo> {
        // Generate a cache directory based on the URL
        let (owner, repo_name) =
            parse_git_url(url).unwrap_or(("direct".to_string(), "repo".to_string()));
        let cache_path = self.cache_dir.join("sources").join(format!("{owner}_{repo_name}"));
        ensure_dir(cache_path.parent().unwrap())?;

        // Check URL type
        let is_local_path = is_local_filesystem_path(url);
        let is_file_url = url.starts_with("file://");

        // Handle local paths (not git repositories, just directories)
        if is_local_path {
            // Apply security validation for local paths
            let resolved_path = crate::utils::platform::resolve_path(url)?;

            // Security check: Validate path against blacklist and symlinks BEFORE canonicalization
            validate_path_security(&resolved_path, true)?;

            let canonical_path = crate::utils::safe_canonicalize(&resolved_path)
                .map_err(|_| anyhow::anyhow!("Local path is not accessible or does not exist"))?;

            // For local paths, we just return a GitRepo pointing to the local directory
            // No cloning or fetching needed - these are treated as plain directories
            return Ok(GitRepo::new(canonical_path));
        }

        // For file:// URLs, verify they're git repositories
        if is_file_url {
            let path_str = url.strip_prefix("file://").unwrap();

            // On Windows, convert forward slashes back to backslashes
            #[cfg(windows)]
            let path_str = path_str.replace('/', "\\");
            #[cfg(not(windows))]
            let path_str = path_str.to_string();

            let abs_path = PathBuf::from(path_str);

            if !abs_path.exists() {
                return Err(anyhow::anyhow!(
                    "Local repository path does not exist or is not accessible: {}",
                    abs_path.display()
                ));
            }

            // Check if it's a git repository (either regular or bare)
            if !crate::git::is_git_repository(&abs_path) {
                return Err(anyhow::anyhow!(
                    "Specified path is not a git repository. file:// URLs must point to valid git repositories."
                ));
            }
        }

        // Acquire lock for this URL-based source to prevent concurrent git operations
        // Use a deterministic lock name based on owner and repo
        let lock_name = format!("{owner}_{repo_name}");
        let _lock = CacheLock::acquire(&self.cache_dir, &lock_name).await?;

        // Use the URL directly (auth tokens are already embedded in URLs from global config)
        let authenticated_url = url.to_string();

        let repo = if cache_path.exists() {
            let repo = GitRepo::new(&cache_path);
            if repo.is_git_repo() {
                // For file:// URLs, always fetch to update refs
                // For remote URLs, also fetch
                repo.fetch(Some(&authenticated_url)).await?;
                repo
            } else {
                tokio::fs::remove_dir_all(&cache_path)
                    .await
                    .context("Failed to remove invalid cache directory")?;
                GitRepo::clone(&authenticated_url, &cache_path).await?
            }
        } else {
            GitRepo::clone(&authenticated_url, &cache_path).await?
        };

        Ok(repo)
    }

    /// Synchronizes all enabled sources by fetching latest changes
    ///
    /// This method iterates through all enabled sources and synchronizes each one
    /// by fetching the latest changes from their remote repositories.
    ///
    /// # Arguments
    ///
    /// * `progress` - Optional progress bar for displaying sync progress
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if all sources sync successfully
    ///
    /// # Errors
    ///
    /// Returns an error if any source fails to sync
    pub async fn sync_all(&mut self) -> Result<()> {
        let enabled_sources: Vec<String> =
            self.list_enabled().iter().map(|s| s.name.clone()).collect();

        for name in enabled_sources {
            self.sync(&name).await?;
        }

        Ok(())
    }

    /// Sync multiple sources by URL in parallel
    ///
    /// Executes all sync operations concurrently using tokio tasks. Each sync operation
    /// uses file-level locking via `CacheLock` to ensure thread safety, preventing
    /// concurrent modifications to the same repository.
    ///
    /// # Performance
    ///
    /// This method provides significant performance improvements when syncing multiple
    /// repositories, especially over network connections. All sync operations execute
    /// concurrently, limited only by system resources and network bandwidth.
    ///
    /// # Thread Safety
    ///
    /// - Each repository sync acquires a file-based lock to prevent concurrent access
    /// - Different repositories can sync simultaneously without blocking each other
    /// - Lock contention only occurs if the same repository is synced multiple times
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::source::SourceManager;
    /// # use tempfile::TempDir;
    /// # async fn example() -> anyhow::Result<()> {
    /// # let temp = TempDir::new()?;
    /// # let mut manager = SourceManager::new_with_cache(temp.path().to_path_buf());
    /// let urls = vec![
    ///     "https://github.com/example/repo1.git".to_string(),
    ///     "https://github.com/example/repo2.git".to_string(),
    ///     "https://github.com/example/repo3.git".to_string(),
    /// ];
    /// let repos = manager.sync_multiple_by_url(&urls).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sync_multiple_by_url(&self, urls: &[String]) -> Result<Vec<GitRepo>> {
        if urls.is_empty() {
            return Ok(Vec::new());
        }

        // Create async tasks for each URL
        let futures: Vec<_> =
            urls.iter().map(|url| async move { self.sync_by_url(url).await }).collect();

        // Execute all syncs in parallel and collect results
        let results = join_all(futures).await;

        // Convert Vec<Result<GitRepo>> to Result<Vec<GitRepo>>
        results.into_iter().collect()
    }

    /// Enables a source for use in operations.
    ///
    /// Enabled sources are included in operations like [`sync_all()`] and [`verify_all()`].
    /// Sources are enabled by default when created.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to enable
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::SourceNotFound`] if no source with the given name exists.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
    /// manager.add(source)?;
    ///
    /// // Disable then re-enable
    /// manager.disable("test")?;
    /// manager.enable("test")?;
    ///
    /// assert!(manager.get("test").unwrap().enabled);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`sync_all()`]: SourceManager::sync_all
    /// [`verify_all()`]: SourceManager::verify_all
    pub fn enable(&mut self, name: &str) -> Result<()> {
        let source = self.sources.get_mut(name).ok_or_else(|| AgpmError::SourceNotFound {
            name: name.to_string(),
        })?;

        source.enabled = true;
        Ok(())
    }

    /// Disables a source to exclude it from operations.
    ///
    /// Disabled sources are excluded from bulk operations like [`sync_all()`] and
    /// [`verify_all()`], and cannot be synced individually. This is useful for
    /// temporarily disabling problematic sources without removing them entirely.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to disable
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::SourceNotFound`] if no source with the given name exists.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
    /// manager.add(source)?;
    ///
    /// // Disable the source
    /// manager.disable("test")?;
    ///
    /// assert!(!manager.get("test").unwrap().enabled);
    /// assert_eq!(manager.list_enabled().len(), 0);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`sync_all()`]: SourceManager::sync_all
    /// [`verify_all()`]: SourceManager::verify_all
    pub fn disable(&mut self, name: &str) -> Result<()> {
        let source = self.sources.get_mut(name).ok_or_else(|| AgpmError::SourceNotFound {
            name: name.to_string(),
        })?;

        source.enabled = false;
        Ok(())
    }

    /// Gets the cache directory path for a source by URL.
    ///
    /// Searches through managed sources to find one with a matching URL and returns
    /// its cache directory path. This is useful when you have a URL and need to
    /// determine where its cached content would be stored.
    ///
    /// # Arguments
    ///
    /// * `url` - Repository URL to look up
    ///
    /// # Returns
    ///
    /// [`PathBuf`] pointing to the cache directory for the source.
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::SourceNotFound`] if no source with the given URL exists.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let url = "https://github.com/example/repo.git".to_string();
    /// let source = Source::new("example".to_string(), url.clone());
    /// manager.add(source)?;
    ///
    /// let cache_path = manager.get_cached_path(&url)?;
    /// println!("Cache path: {:?}", cache_path);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_cached_path(&self, url: &str) -> Result<PathBuf> {
        // Try to find the source by URL
        let source = self.sources.values().find(|s| s.url == url).ok_or_else(|| {
            AgpmError::SourceNotFound {
                name: url.to_string(),
            }
        })?;

        Ok(source.cache_dir(&self.cache_dir))
    }

    /// Gets the cache directory path for a source by name.
    ///
    /// Returns the cache directory path where the named source's repository
    /// content is or would be stored.
    ///
    /// # Arguments
    ///
    /// * `name` - Name of the source to get the cache path for
    ///
    /// # Returns
    ///
    /// [`PathBuf`] pointing to the cache directory for the source.
    ///
    /// # Errors
    ///
    /// Returns [`AgpmError::SourceNotFound`] if no source with the given name exists.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    /// let source = Source::new(
    ///     "community".to_string(),
    ///     "https://github.com/example/agpm-community.git".to_string()
    /// );
    /// manager.add(source)?;
    ///
    /// let cache_path = manager.get_cached_path_by_name("community")?;
    /// println!("Community cache: {:?}", cache_path);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_cached_path_by_name(&self, name: &str) -> Result<PathBuf> {
        let source = self.sources.get(name).ok_or_else(|| AgpmError::SourceNotFound {
            name: name.to_string(),
        })?;

        Ok(source.cache_dir(&self.cache_dir))
    }

    /// Verifies that all enabled sources are accessible.
    ///
    /// This method performs lightweight verification checks on all enabled sources
    /// without performing full synchronization. It's useful for validating source
    /// configurations and network connectivity before attempting operations.
    ///
    /// # Verification Process
    ///
    /// For each enabled source:
    /// 1. **URL validation**: Check URL format and structure
    /// 2. **Connectivity test**: Verify remote repositories are reachable
    /// 3. **Local path validation**: Ensure local repositories exist and are Git repos
    /// 4. **Authentication check**: Validate credentials for private repositories
    ///
    /// # Performance Characteristics
    ///
    /// - **Lightweight**: No cloning or downloading of repository content
    /// - **Fast**: Quick network checks rather than full Git operations
    /// - **Sequential**: Sources verified one at a time for clear error reporting
    ///
    /// # Arguments
    ///
    /// * `progress` - Optional progress bar for user feedback
    ///
    /// # Errors
    ///
    /// Returns an error if any enabled source fails verification:
    /// - Network connectivity issues
    /// - Authentication failures
    /// - Invalid repository URLs
    /// - Local paths that don't exist or aren't Git repositories
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::source::{Source, SourceManager};
    ///
    /// # async fn example() -> anyhow::Result<()> {
    /// let mut manager = SourceManager::new()?;
    ///
    /// // Add some sources
    /// manager.add(Source::new(
    ///     "community".to_string(),
    ///     "https://github.com/example/agpm-community.git".to_string()
    /// ))?;
    ///
    /// // Verify all sources
    /// manager.verify_all().await?;
    ///
    /// println!("All sources verified successfully");
    /// # Ok(())
    /// # }
    /// ```
    pub async fn verify_all(&self) -> Result<()> {
        let enabled_sources: Vec<&Source> = self.list_enabled();

        if enabled_sources.is_empty() {
            return Ok(());
        }

        for source in enabled_sources {
            // Check if source URL is reachable by attempting a quick operation
            self.verify_source(&source.url).await?;
        }

        Ok(())
    }

    /// Verifies that a single source URL is accessible.
    ///
    /// Performs a lightweight check to determine if a repository URL is accessible
    /// without downloading content. The verification method depends on the URL type:
    ///
    /// - **file:// URLs**: Check if the local path exists
    /// - **Remote URLs**: Perform network connectivity check
    /// - **Local paths**: Validate path exists and is a Git repository
    ///
    /// # Arguments
    ///
    /// * `url` - Repository URL or local path to verify
    ///
    /// # Errors
    ///
    /// Returns an error if the source is not accessible, with specific error
    /// messages based on the failure type (network, authentication, path, etc.).
    async fn verify_source(&self, url: &str) -> Result<()> {
        // For file:// URLs (used in tests), just check if the path exists
        if url.starts_with("file://") {
            let path = url.strip_prefix("file://").unwrap();
            if std::path::Path::new(path).exists() {
                return Ok(());
            }
            return Err(anyhow::anyhow!("Local path does not exist: {path}"));
        }

        // For other URLs, try to create a GitRepo object and verify it's accessible
        // This is a lightweight check - we don't actually clone the repo
        match crate::git::GitRepo::verify_url(url).await {
            Ok(()) => Ok(()),
            Err(e) => Err(anyhow::anyhow!("Source not accessible: {e}")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_source_creation() {
        let source =
            Source::new("test".to_string(), "https://github.com/user/repo.git".to_string())
                .with_description("Test source".to_string());

        assert_eq!(source.name, "test");
        assert_eq!(source.url, "https://github.com/user/repo.git");
        assert_eq!(source.description, Some("Test source".to_string()));
        assert!(source.enabled);
    }

    #[tokio::test]
    async fn test_source_manager_add_remove() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        let source =
            Source::new("test".to_string(), "https://github.com/user/repo.git".to_string());

        manager.add(source.clone()).unwrap();
        assert!(manager.get("test").is_some());

        let result = manager.add(source);
        assert!(result.is_err());

        manager.remove("test").await.unwrap();
        assert!(manager.get("test").is_none());

        let result = manager.remove("test").await;
        assert!(result.is_err());
    }

    #[test]
    fn test_source_enable_disable() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        let source =
            Source::new("test".to_string(), "https://github.com/user/repo.git".to_string());

        manager.add(source).unwrap();
        assert!(manager.get("test").unwrap().enabled);

        manager.disable("test").unwrap();
        assert!(!manager.get("test").unwrap().enabled);

        manager.enable("test").unwrap();
        assert!(manager.get("test").unwrap().enabled);
    }

    #[test]
    fn test_list_enabled() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        manager.add(Source::new("source1".to_string(), "url1".to_string())).unwrap();
        manager.add(Source::new("source2".to_string(), "url2".to_string())).unwrap();
        manager.add(Source::new("source3".to_string(), "url3".to_string())).unwrap();

        assert_eq!(manager.list_enabled().len(), 3);

        manager.disable("source2").unwrap();
        assert_eq!(manager.list_enabled().len(), 2);
    }

    #[test]
    fn test_source_cache_dir() {
        let temp_dir = TempDir::new().unwrap();
        let base_dir = temp_dir.path();

        let source =
            Source::new("test".to_string(), "https://github.com/user/repo.git".to_string());

        let cache_dir = source.cache_dir(base_dir);
        assert!(cache_dir.to_string_lossy().contains("sources"));
        assert!(cache_dir.to_string_lossy().contains("user_repo"));
    }

    #[test]
    fn test_source_cache_dir_invalid_url() {
        let temp_dir = TempDir::new().unwrap();
        let base_dir = temp_dir.path();

        let source = Source::new("test".to_string(), "not-a-valid-url".to_string());

        let cache_dir = source.cache_dir(base_dir);
        assert!(cache_dir.to_string_lossy().contains("sources"));
        assert!(cache_dir.to_string_lossy().contains("unknown_test"));
    }

    #[test]
    fn test_from_manifest() {
        let mut manifest = Manifest::new();
        manifest.add_source(
            "official".to_string(),
            "https://github.com/example-org/agpm-official.git".to_string(),
        );
        manifest.add_source(
            "community".to_string(),
            "https://github.com/example-org/agpm-community.git".to_string(),
        );

        let temp_dir = TempDir::new().unwrap();
        let manager =
            SourceManager::from_manifest_with_cache(&manifest, temp_dir.path().to_path_buf());

        assert_eq!(manager.list().len(), 2);
        assert!(manager.get("official").is_some());
        assert!(manager.get("community").is_some());
    }

    #[test]
    fn test_source_manager_list() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        assert_eq!(manager.list().len(), 0);

        manager.add(Source::new("source1".to_string(), "url1".to_string())).unwrap();
        manager.add(Source::new("source2".to_string(), "url2".to_string())).unwrap();

        assert_eq!(manager.list().len(), 2);
    }

    #[test]
    fn test_source_manager_get_mut() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        manager.add(Source::new("test".to_string(), "url".to_string())).unwrap();

        if let Some(source) = manager.get_mut("test") {
            source.description = Some("Updated description".to_string());
        }

        assert_eq!(
            manager.get("test").unwrap().description,
            Some("Updated description".to_string())
        );
    }

    #[test]
    fn test_source_manager_enable_disable_errors() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        let result = manager.enable("nonexistent");
        assert!(result.is_err());

        let result = manager.disable("nonexistent");
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_source_manager_sync_disabled() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        let source =
            Source::new("test".to_string(), "https://github.com/user/repo.git".to_string());
        manager.add(source).unwrap();
        manager.disable("test").unwrap();

        let result = manager.sync("test").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_source_manager_sync_nonexistent() {
        let temp_dir = TempDir::new().unwrap();
        let mut manager = SourceManager::new_with_cache(temp_dir.path().to_path_buf());

        let result = manager.sync("nonexistent").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_source_manager_sync_local_repo() {
        use std::process::Command;

        // In coverage/CI environments, current dir might not exist, so set a safe one first

        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let repo_dir = temp_dir.path().join("repo");

        // Create a local git repo
        std::fs::create_dir(&repo_dir).unwrap();
        Command::new("git").args(["init"]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        std::fs::write(repo_dir.join("README.md"), "Test").unwrap();
        Command::new("git").args(["add", "."]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();

        let mut manager = SourceManager::new_with_cache(cache_dir.clone());
        let source = Source::new("test".to_string(), format!("file://{}", repo_dir.display()));
        manager.add(source).unwrap();

        // First sync (clone)
        let result = manager.sync("test").await;
        assert!(result.is_ok());
        let repo = result.unwrap();
        assert!(repo.is_git_repo());

        // Second sync (fetch + pull)
        let result = manager.sync("test").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_source_manager_sync_all() {
        use std::process::Command;

        // In coverage/CI environments, current dir might not exist, so set a safe one first

        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");

        // Create two local git repos
        let repo1_dir = temp_dir.path().join("repo1");
        let repo2_dir = temp_dir.path().join("repo2");

        for repo_dir in &[&repo1_dir, &repo2_dir] {
            std::fs::create_dir(repo_dir).unwrap();
            Command::new("git").args(["init"]).current_dir(repo_dir).output().unwrap();
            Command::new("git")
                .args(["config", "user.email", "test@example.com"])
                .current_dir(repo_dir)
                .output()
                .unwrap();
            Command::new("git")
                .args(["config", "user.name", "Test User"])
                .current_dir(repo_dir)
                .output()
                .unwrap();
            std::fs::write(repo_dir.join("README.md"), "Test").unwrap();
            Command::new("git").args(["add", "."]).current_dir(repo_dir).output().unwrap();
            Command::new("git")
                .args(["commit", "-m", "Initial commit"])
                .current_dir(repo_dir)
                .output()
                .unwrap();
        }

        let mut manager = SourceManager::new_with_cache(cache_dir.clone());

        manager
            .add(Source::new("repo1".to_string(), format!("file://{}", repo1_dir.display())))
            .unwrap();

        manager
            .add(Source::new("repo2".to_string(), format!("file://{}", repo2_dir.display())))
            .unwrap();

        // Sync all
        let result = manager.sync_all().await;
        assert!(result.is_ok());

        // Verify both repos were cloned
        let source1_cache = manager.get("repo1").unwrap().cache_dir(&cache_dir);
        let source2_cache = manager.get("repo2").unwrap().cache_dir(&cache_dir);
        assert!(source1_cache.exists());
        assert!(source2_cache.exists());
    }

    // Additional error path tests

    #[tokio::test]
    async fn test_sync_non_existent_local_path() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let mut manager = SourceManager::new_with_cache(cache_dir);

        let source = Source::new("test".to_string(), "/non/existent/path".to_string());
        manager.add(source).unwrap();

        let result = manager.sync("test").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("does not exist"));
    }

    #[tokio::test]
    async fn test_sync_non_git_directory() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let non_git_dir = temp_dir.path().join("not_git");
        std::fs::create_dir(&non_git_dir).unwrap();

        let mut manager = SourceManager::new_with_cache(cache_dir);
        let source = Source::new("test".to_string(), non_git_dir.to_str().unwrap().to_string());
        manager.add(source).unwrap();

        // Local paths are now treated as plain directories, so sync should succeed
        let result = manager.sync("test").await;
        if let Err(ref e) = result {
            eprintln!("Test failed with error: {e}");
            eprintln!("Path was: {non_git_dir:?}");
        }
        assert!(result.is_ok(), "Failed to sync: {result:?}");
        let repo = result.unwrap();
        // Should point to the canonicalized local directory
        assert_eq!(repo.path(), crate::utils::safe_canonicalize(&non_git_dir).unwrap());
    }

    #[tokio::test]
    async fn test_sync_invalid_cache_directory() {
        use std::process::Command;

        // Ensure stable test environment
        // In coverage/CI environments, current dir might not exist, so set a safe one first

        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let repo_dir = temp_dir.path().join("repo");

        // Create a valid git repo
        std::fs::create_dir(&repo_dir).unwrap();
        Command::new("git").args(["init"]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        std::fs::write(repo_dir.join("README.md"), "Test").unwrap();
        Command::new("git").args(["add", "."]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["commit", "-m", "Initial"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();

        let mut manager = SourceManager::new_with_cache(cache_dir.clone());
        let source = Source::new("test".to_string(), format!("file://{}", repo_dir.display()));
        manager.add(source).unwrap();

        // Create an invalid cache directory (not a git repo)
        let source_cache_dir = manager.get("test").unwrap().cache_dir(&cache_dir);
        std::fs::create_dir_all(&source_cache_dir).unwrap();
        std::fs::write(source_cache_dir.join("file.txt"), "not a git repo").unwrap();

        // Sync should detect invalid cache and re-clone
        let result = manager.sync("test").await;
        assert!(result.is_ok());
        assert!(crate::git::is_git_repository(&source_cache_dir));
    }

    #[tokio::test]
    async fn test_sync_by_url_invalid_url() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.sync_by_url("not-a-valid-url").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_sync_multiple_by_url_empty() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.sync_multiple_by_url(&[]).await;
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 0);
    }

    #[tokio::test]
    async fn test_sync_multiple_by_url_with_failures() {
        use std::process::Command;

        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let repo_dir = temp_dir.path().join("repo");

        // Create one valid repo
        std::fs::create_dir(&repo_dir).unwrap();
        Command::new("git").args(["init"]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        std::fs::write(repo_dir.join("README.md"), "Test").unwrap();
        Command::new("git").args(["add", "."]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["commit", "-m", "Initial"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();

        let manager = SourceManager::new_with_cache(cache_dir);

        let urls = vec![format!("file://{}", repo_dir.display()), "invalid-url".to_string()];

        // Should fail on invalid URL
        let result = manager.sync_multiple_by_url(&urls).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_get_cached_path_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.get_cached_path("https://unknown/url.git");
        assert!(result.is_err());
        // Just check that it returns an error - the message format may vary
    }

    #[tokio::test]
    async fn test_get_cached_path_by_name_not_found() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.get_cached_path_by_name("nonexistent");
        assert!(result.is_err());
        // Just check that it returns an error - the message format may vary
    }

    #[tokio::test]
    async fn test_verify_all_no_sources() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.verify_all().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_verify_all_with_disabled_sources() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let mut manager = SourceManager::new_with_cache(cache_dir);

        // Add but disable a source
        let source =
            Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
        manager.add(source).unwrap();
        manager.disable("test").unwrap();

        // Verify should skip disabled sources
        let result = manager.verify_all().await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_verify_source_file_url_not_exist() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.verify_source("file:///non/existent/path").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("does not exist"));
    }

    #[tokio::test]
    async fn test_verify_source_invalid_remote() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        let result = manager.verify_source("https://invalid-host-9999.test/repo.git").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not accessible"));
    }

    #[tokio::test]
    async fn test_remove_with_cache_cleanup() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let mut manager = SourceManager::new_with_cache(cache_dir.clone());

        let source =
            Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
        manager.add(source).unwrap();

        // Create cache directory
        let source_cache = cache_dir.join("sources").join("test");
        std::fs::create_dir_all(&source_cache).unwrap();
        std::fs::write(source_cache.join("file.txt"), "cached").unwrap();
        assert!(source_cache.exists());

        // Remove should clean up cache
        manager.remove("test").await.unwrap();
        assert!(!source_cache.exists());
    }

    #[tokio::test]
    async fn test_get_source_url() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let mut manager = SourceManager::new_with_cache(cache_dir);

        let source =
            Source::new("test".to_string(), "https://github.com/test/repo.git".to_string());
        manager.add(source).unwrap();

        let url = manager.get_source_url("test");
        assert_eq!(url, Some("https://github.com/test/repo.git".to_string()));

        let url = manager.get_source_url("nonexistent");
        assert_eq!(url, None);
    }

    #[test]
    fn test_source_with_description() {
        let source =
            Source::new("test".to_string(), "https://github.com/test/repo.git".to_string())
                .with_description("Test description".to_string());

        assert_eq!(source.description, Some("Test description".to_string()));
    }

    #[tokio::test]
    async fn test_sync_with_progress() {
        use std::process::Command;

        // Ensure stable test environment
        // In coverage/CI environments, current dir might not exist, so set a safe one first

        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let repo_dir = temp_dir.path().join("repo");

        // Create a git repo
        std::fs::create_dir(&repo_dir).unwrap();
        Command::new("git").args(["init"]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();
        std::fs::write(repo_dir.join("README.md"), "Test").unwrap();
        Command::new("git").args(["add", "."]).current_dir(&repo_dir).output().unwrap();
        Command::new("git")
            .args(["commit", "-m", "Initial"])
            .current_dir(&repo_dir)
            .output()
            .unwrap();

        let mut manager = SourceManager::new_with_cache(cache_dir);
        let source = Source::new("test".to_string(), format!("file://{}", repo_dir.display()));
        manager.add(source).unwrap();

        let result = manager.sync("test").await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_from_manifest_with_global() {
        let manifest = Manifest::new();
        let result = SourceManager::from_manifest_with_global(&manifest).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_new_source_manager() {
        let result = SourceManager::new();
        // May fail if cache dir can't be created, but should handle gracefully
        if let Ok(manager) = result {
            assert!(manager.sources.is_empty());
        }
    }

    #[tokio::test]
    async fn test_sync_local_path_directory() {
        // Test that local paths (not file:// URLs) are treated as plain directories
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let local_dir = temp_dir.path().join("local_deps");

        // Create a plain directory with some files (not a git repo)
        std::fs::create_dir(&local_dir).unwrap();
        std::fs::write(local_dir.join("agent.md"), "# Test Agent").unwrap();
        std::fs::write(local_dir.join("snippet.md"), "# Test Snippet").unwrap();

        let mut manager = SourceManager::new_with_cache(cache_dir.clone());

        // Add source with local path
        let source = Source::new("local".to_string(), local_dir.to_string_lossy().to_string());
        manager.add(source).unwrap();

        // Sync should work with plain directory (not require git)
        let result = manager.sync("local").await;
        assert!(result.is_ok());

        let repo = result.unwrap();
        // The returned GitRepo should point to the canonicalized local directory
        // On macOS, /var is a symlink to /private/var, so we need to compare canonical paths
        assert_eq!(repo.path(), crate::utils::safe_canonicalize(&local_dir).unwrap());
    }

    #[tokio::test]
    async fn test_sync_by_url_local_path() {
        // Test sync_by_url with local paths
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let local_dir = temp_dir.path().join("local_deps");

        // Create a plain directory with files
        std::fs::create_dir(&local_dir).unwrap();
        std::fs::write(local_dir.join("test.md"), "# Test Resource").unwrap();

        let manager = SourceManager::new_with_cache(cache_dir);

        // Test absolute path
        let result = manager.sync_by_url(&local_dir.to_string_lossy()).await;
        assert!(result.is_ok());
        let repo = result.unwrap();
        assert_eq!(repo.path(), crate::utils::safe_canonicalize(&local_dir).unwrap());

        // Test relative path
        {
            // In coverage/CI environments, current dir might not exist, so set a safe one first
            let result = manager.sync_by_url("./local_deps").await;
            assert!(result.is_ok());
            // Guard will restore directory when dropped
        }
    }

    #[tokio::test]
    async fn test_sync_local_path_not_exist() {
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let manager = SourceManager::new_with_cache(cache_dir);

        // Try to sync non-existent local path
        let result = manager.sync_by_url("/non/existent/path").await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("does not exist"));
    }

    #[tokio::test]
    async fn test_file_url_requires_git() {
        // Test that file:// URLs require valid git repositories
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let plain_dir = temp_dir.path().join("plain_dir");

        // Create a plain directory (not a git repo)
        std::fs::create_dir(&plain_dir).unwrap();
        std::fs::write(plain_dir.join("test.md"), "# Test").unwrap();

        let manager = SourceManager::new_with_cache(cache_dir);

        // file:// URL should fail for non-git directory
        let file_url = format!("file://{}", plain_dir.display());
        let result = manager.sync_by_url(&file_url).await;
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("not a git repository"));
    }

    #[tokio::test]
    async fn test_path_traversal_attack_prevention() {
        // Test that access to blacklisted system directories is prevented
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");

        let manager = SourceManager::new_with_cache(cache_dir.clone());

        // Test that blacklisted system paths are blocked
        let blacklisted_paths = vec!["/etc/passwd", "/System/Library", "/private/etc/hosts"];

        for malicious_path in blacklisted_paths {
            // Skip if path doesn't exist (e.g., /System on Linux)
            if !std::path::Path::new(malicious_path).exists() {
                continue;
            }

            let result = manager.sync_by_url(malicious_path).await;
            assert!(result.is_err(), "Blacklisted path not detected for: {malicious_path}");
            let err_msg = result.unwrap_err().to_string();
            assert!(
                err_msg.contains("Security error") || err_msg.contains("not allowed"),
                "Expected security error for blacklisted path: {malicious_path}, got: {err_msg}"
            );
        }

        // Test that normal paths in temp directories work fine
        let safe_dir = temp_dir.path().join("safe_dir");
        std::fs::create_dir(&safe_dir).unwrap();

        let result = manager.sync_by_url(&safe_dir.to_string_lossy()).await;
        assert!(result.is_ok(), "Safe path was incorrectly blocked: {result:?}");
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_symlink_attack_prevention() {
        // Test that symlink attacks are prevented
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");
        let project_dir = temp_dir.path().join("project");
        let deps_dir = project_dir.join("deps");
        let sensitive_dir = temp_dir.path().join("sensitive");

        // Create directories
        std::fs::create_dir(&project_dir).unwrap();
        std::fs::create_dir(&deps_dir).unwrap();
        std::fs::create_dir(&sensitive_dir).unwrap();
        std::fs::write(sensitive_dir.join("secret.txt"), "secret data").unwrap();

        // Create a symlink pointing to sensitive directory
        use std::os::unix::fs::symlink;
        let symlink_path = deps_dir.join("malicious_link");
        symlink(&sensitive_dir, &symlink_path).unwrap();

        let manager = SourceManager::new_with_cache(cache_dir);

        // Try to access the symlink directly as a local path
        let result = manager.sync_by_url(symlink_path.to_str().unwrap()).await;
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Symlinks are not allowed") || err_msg.contains("Security error"),
            "Expected symlink error, got: {err_msg}"
        );
    }

    #[tokio::test]
    async fn test_absolute_path_restriction() {
        // Test that blacklisted absolute paths are blocked
        let temp_dir = TempDir::new().unwrap();
        let cache_dir = temp_dir.path().join("cache");

        let manager = SourceManager::new_with_cache(cache_dir);

        // With blacklist approach, temp directories are allowed
        // So this test verifies that normal development paths work
        let safe_dir = temp_dir.path().join("project");
        std::fs::create_dir(&safe_dir).unwrap();
        std::fs::write(safe_dir.join("file.txt"), "content").unwrap();

        let result = manager.sync_by_url(&safe_dir.to_string_lossy()).await;

        // Temp directories should work fine with blacklist approach
        assert!(result.is_ok(), "Safe temp path was incorrectly blocked: {result:?}");
    }

    #[test]
    fn test_error_message_sanitization() {
        // Test that error messages don't leak sensitive path information
        // This is a compile-time test to ensure error messages are properly sanitized

        // Check that we're not including full paths in error messages
        let error_msg = "Local path is not accessible or does not exist";
        assert!(!error_msg.contains("/home"));
        assert!(!error_msg.contains("/Users"));
        assert!(!error_msg.contains("C:\\"));

        let security_msg =
            "Security error: Local path must be within the project directory or AGPM cache";
        assert!(!security_msg.contains("{:?}"));
        assert!(!security_msg.contains("{}"));
    }
}