agpm-cli 0.4.4

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
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
//! Manifest file parsing and validation for AGPM projects.
//!
//! This module handles the `agpm.toml` manifest file that defines project
//! dependencies and configuration. The manifest uses TOML format and follows
//! a structure similar to Cargo.toml, providing a lockfile-based dependency
//! management system for Claude Code resources.
//!
//! # Overview
//!
//! The manifest system enables:
//! - Declarative dependency management through `agpm.toml`
//! - Reproducible installations via lockfile generation
//! - Support for multiple Git-based source repositories
//! - Local and remote dependency resolution
//! - Version constraint specification and validation
//! - Transitive dependency resolution from resource metadata
//! - Cross-platform path handling and installation
//! - MCP (Model Context Protocol) server configuration management
//! - Atomic file operations for reliability
//!
//! # Complete TOML Format Specification
//!
//! ## Basic Structure
//!
//! A `agpm.toml` manifest file consists of four main sections:
//!
//! ```toml
//! # Named source repositories (optional)
//! [sources]
//! # Git repository URLs mapped to convenient names
//! official = "https://github.com/example-org/agpm-official.git"
//! community = "https://github.com/community/agpm-resources.git"
//! private = "git@github.com:company/private-resources.git"
//!
//! # Installation target directories (optional)
//! [target]
//! # Where agents should be installed (default: ".claude/agents")
//! agents = ".claude/agents"
//! # Where snippets should be installed (default: ".claude/agpm/snippets")
//! snippets = ".claude/agpm/snippets"
//! # Where commands should be installed (default: ".claude/commands")
//! commands = ".claude/commands"
//!
//! # Agent dependencies (optional)
//! [agents]
//! # Various dependency specification formats
//! simple-agent = "../local/agents/helper.md"                    # Local path
//! remote-agent = { source = "official", path = "agents/reviewer.md", version = "v1.0.0" }
//! latest-agent = { source = "community", path = "agents/utils.md", version = "latest" }
//! branch-agent = { source = "private", path = "agents/internal.md", git = "develop" }
//! commit-agent = { source = "official", path = "agents/stable.md", git = "abc123..." }
//! # Custom target installation directory (relative to .claude)
//! custom-agent = { source = "official", path = "agents/special.md", version = "v1.0.0", target = "integrations/ai" }
//!
//! # Snippet dependencies (optional)
//! [snippets]
//! # Same formats as agents
//! local-snippet = "../shared/snippets/common.md"
//! remote-snippet = { source = "community", path = "snippets/utils.md", version = "v2.1.0" }
//! # Custom target for special snippets
//! integration-snippet = { source = "community", path = "snippets/api.md", version = "v1.0.0", target = "tools/snippets" }
//!
//! # Command dependencies (optional)
//! [commands]
//! # Same formats as agents and snippets
//! local-command = "../shared/commands/helper.md"
//! remote-command = { source = "community", path = "commands/build.md", version = "v1.0.0" }
//! ```
//!
//! ## Sources Section
//!
//! The `[sources]` section maps convenient names to Git repository URLs:
//!
//! ```toml
//! [sources]
//! # HTTPS URLs (recommended for public repositories)
//! official = "https://github.com/owner/agpm-resources.git"
//! community = "https://gitlab.com/group/agpm-community.git"
//!
//! # SSH URLs (for private repositories with key authentication)
//! private = "git@github.com:company/private-resources.git"
//! internal = "git@gitlab.company.com:team/internal-resources.git"
//!
//! # Local Git repository URLs
//! local-repo = "file:///absolute/path/to/local/repo"
//!
//! # Environment variable expansion (useful for CI/CD)
//! dynamic = "https://github.com/${GITHUB_ORG}/resources.git"
//! home-repo = "file://${HOME}/git/resources"
//! ```
//!
//! ## Target Section
//!
//! The `[target]` section configures where resources are installed:
//!
//! ```toml
//! [target]
//! # Default values shown - these can be customized
//! agents = ".claude/agents"      # Where agent .md files are copied
//! snippets = ".claude/agpm/snippets"  # Where snippet .md files are copied
//! commands = ".claude/commands"  # Where command .md files are copied
//!
//! # Alternative configurations
//! agents = "resources/agents"
//! snippets = "resources/snippets"
//! commands = "resources/commands"
//!
//! # Absolute paths are supported
//! agents = "/opt/claude/agents"
//! snippets = "/opt/claude/snippets"
//! commands = "/opt/claude/commands"
//! ```
//!
//! ## Dependency Sections
//!
//! Both `[agents]` and `[snippets]` sections support multiple dependency formats:
//!
//! ### 1. Local Path Dependencies
//!
//! For resources in your local filesystem:
//!
//! ```toml
//! [agents]
//! # Relative paths from manifest directory
//! local-helper = "../shared/agents/helper.md"
//! nearby-agent = "./local-agents/custom.md"
//!
//! # Absolute paths (not recommended for portability)
//! system-agent = "/usr/local/share/claude/agents/system.md"
//! ```
//!
//! Local dependencies:
//! - Do not support version constraints
//! - Are copied directly from the filesystem
//! - Are not cached or managed through Git
//! - Must exist at install time
//!
//! ### 2. Remote Source Dependencies
//!
//! For resources from Git repositories:
//!
//! ```toml
//! [agents]
//! # Basic remote dependency with semantic version
//! code-reviewer = { source = "official", path = "agents/reviewer.md", version = "v1.0.0" }
//!
//! # Using latest version (not recommended for production)
//! utils = { source = "community", path = "agents/utils.md", version = "latest" }
//!
//! # Specific Git branch
//! bleeding-edge = { source = "official", path = "agents/experimental.md", git = "develop" }
//!
//! # Specific Git commit (maximum reproducibility)
//! stable = { source = "official", path = "agents/stable.md", git = "a1b2c3d4e5f6..." }
//!
//! # Git tag (alternative to version field)
//! tagged = { source = "community", path = "agents/tagged.md", git = "release-2.0" }
//! ```
//!
//! ### 3. Custom Target Installation
//!
//! Dependencies can specify a custom installation directory using the `target` field:
//!
//! ```toml
//! [agents]
//! # Install to .claude/integrations/ai/ instead of .claude/agents/
//! integration-agent = {
//!     source = "official",
//!     path = "agents/integration.md",
//!     version = "v1.0.0",
//!     target = "integrations/ai"
//! }
//!
//! # Organize tools in a custom structure
//! debug-tool = {
//!     source = "community",
//!     path = "agents/debugger.md",
//!     version = "v2.0.0",
//!     target = "development/tools"
//! }
//!
//! [snippets]
//! # Custom location for API snippets
//! api-helper = {
//!     source = "community",
//!     path = "snippets/api.md",
//!     version = "v1.0.0",
//!     target = "api/snippets"
//! }
//! ```
//!
//! Custom targets:
//! - Are always relative to the `.claude` directory
//! - Leading `.claude/` or `/` are automatically stripped
//! - Directories are created if they don't exist
//! - Help organize resources in complex projects
//!
//! ### 4. Custom Filenames
//!
//! Dependencies can specify a custom filename using the `filename` field:
//!
//! ```toml
//! [agents]
//! # Install as "ai-assistant.md" instead of "my-ai.md"
//! my-ai = {
//!     source = "official",
//!     path = "agents/complex-long-name-v2.md",
//!     version = "v1.0.0",
//!     filename = "ai-assistant.md"
//! }
//!
//! # Change both filename and extension
//! doc-helper = {
//!     source = "community",
//!     path = "agents/documentation.md",
//!     version = "v2.0.0",
//!     filename = "docs.txt"
//! }
//!
//! # Combine custom target and filename
//! special-tool = {
//!     source = "official",
//!     path = "agents/debug-analyzer-enhanced.md",
//!     version = "v1.0.0",
//!     target = "tools/debugging",
//!     filename = "analyzer.markdown"
//! }
//!
//! [scripts]
//! # Rename script during installation
//! data-processor = {
//!     source = "community",
//!     path = "scripts/data-processor-v3.py",
//!     version = "v1.0.0",
//!     filename = "process.py"
//! }
//! ```
//!
//! Custom filenames:
//! - Include the full filename with extension
//! - Override the default name (based on dependency key)
//! - Work with any resource type
//! - Can be combined with custom targets
//!
//! ## Version Constraint Syntax
//!
//! AGPM supports flexible version constraints:
//!
//! - `"v1.0.0"` - Exact semantic version
//! - `"1.0.0"` - Exact version (v prefix optional)
//! - `"latest"` - Always use the latest available version
//! - `"main"` - Use the main/master branch HEAD
//! - `"develop"` - Use a specific branch
//! - `"a1b2c3d4..."` - Use a specific commit SHA
//! - `"release-1.0"` - Use a specific Git tag
//!
//! ## Complete Examples
//!
//! ### Minimal Manifest
//!
//! ```toml
//! [agents]
//! helper = "../agents/helper.md"
//! ```
//!
//! ### Production Manifest
//!
//! ```toml
//! [sources]
//! official = "https://github.com/claude-org/official-resources.git"
//! community = "https://github.com/claude-community/resources.git"
//! company = "git@github.com:mycompany/claude-resources.git"
//!
//! [target]
//! agents = "resources/agents"
//! snippets = "resources/snippets"
//!
//! [agents]
//! # Production agents with pinned versions
//! code-reviewer = { source = "official", path = "agents/code-reviewer.md", version = "v2.1.0" }
//! documentation = { source = "community", path = "agents/doc-writer.md", version = "v1.5.2" }
//! internal-helper = { source = "company", path = "agents/helper.md", version = "v1.0.0" }
//!
//! # Local customizations
//! custom-agent = "./local/agents/custom.md"
//!
//! [snippets]
//! # Utility snippets
//! common-patterns = { source = "community", path = "snippets/patterns.md", version = "v1.2.0" }
//! company-templates = { source = "company", path = "snippets/templates.md", version = "latest" }
//! ```
//!
//! ## Security Considerations
//!
//! **CRITICAL**: Never include authentication credentials in `agpm.toml`:
//!
//! ```toml
//! # ❌ NEVER DO THIS - credentials will be committed to git
//! [sources]
//! private = "https://token:ghp_xxxx@github.com/company/repo.git"
//!
//! # ✅ Instead, use global configuration in ~/.agpm/config.toml
//! # Or use SSH keys with git@ URLs
//! [sources]
//! private = "git@github.com:company/repo.git"
//! ```
//!
//! Authentication should be configured globally in `~/.agpm/config.toml` or
//! through SSH keys for `git@` URLs. See [`crate::config`] for details.
//!
//! ## Relationship to Lockfile
//!
//! The manifest works together with the lockfile (`agpm.lock`):
//!
//! - **Manifest (`agpm.toml`)**: Declares dependencies and constraints
//! - **Lockfile (`agpm.lock`)**: Records exact resolved versions and checksums
//!
//! When you run `agpm install`:
//! 1. Reads dependencies from `agpm.toml`
//! 2. Resolves versions within constraints  
//! 3. Generates/updates `agpm.lock` with exact commits
//! 4. Installs resources to target directories
//!
//! See [`crate::lockfile`] for lockfile format details.
//!
//! ## Cross-Platform Compatibility
//!
//! AGPM handles platform differences automatically:
//! - Path separators (/ vs \\) are normalized
//! - Home directory expansion (~) is supported
//! - Environment variable expansion is available
//! - Git commands work on Windows, macOS, and Linux
//! - Long path support on Windows (>260 characters)
//! - Unicode filenames and paths are fully supported
//!
//! ## Best Practices
//!
//! 1. **Use semantic versions**: Prefer `v1.0.0` over `latest`
//! 2. **Pin production dependencies**: Use exact versions in production
//! 3. **Organize sources logically**: Group by organization or purpose
//! 4. **Document dependencies**: Add comments explaining why each is needed
//! 5. **Keep manifests simple**: Avoid overly complex dependency trees
//! 6. **Use SSH for private repos**: More secure than HTTPS tokens
//! 7. **Test across platforms**: Verify paths work on all target systems
//! 8. **Version control manifests**: Always commit `agpm.toml` to git
//! 9. **Validate regularly**: Run `agpm validate` before commits
//! 10. **Use lockfiles**: Commit `agpm.lock` for reproducible builds
//!
//! ## Transitive Dependencies
//!
//! Resources can declare their own dependencies within their files using structured
//! metadata. This enables automatic dependency resolution without manual manifest updates.
//!
//! ### Supported Formats
//!
//! #### Markdown Files (YAML Frontmatter)
//!
//! ```markdown
//! ---
//! dependencies:
//!   agents:
//!     - path: agents/helper.md
//!       version: v1.0.0
//!     - path: agents/reviewer.md
//!   snippets:
//!     - path: snippets/utils.md
//! ---
//!
//! # My Command Documentation
//! ...
//! ```
//!
//! #### JSON Files (Top-Level Field)
//!
//! ```json
//! {
//!   "events": ["UserPromptSubmit"],
//!   "type": "command",
//!   "command": ".claude/agpm/scripts/test.js",
//!   "dependencies": {
//!     "scripts": [
//!       { "path": "scripts/test-runner.sh", "version": "v1.0.0" },
//!       { "path": "scripts/validator.py" }
//!     ],
//!     "agents": [
//!       { "path": "agents/code-analyzer.md", "version": "~1.2.0" }
//!     ]
//!   }
//! }
//! ```
//!
//! ### Key Features
//!
//! - **Automatic Discovery**: Dependencies extracted during resolution
//! - **Version Inheritance**: If no version specified, parent's version is used
//! - **Same-Source Model**: Transitive deps inherit parent's source repository
//! - **Cycle Detection**: Circular dependency loops are detected and prevented
//! - **Topological Ordering**: Dependencies installed in correct order
//! - **Optional Resolution**: Can be disabled with `--no-transitive` flag
//!
//! ### Data Structures
//!
//! Transitive dependencies are represented by:
//! - [`DependencySpec`]: Individual dependency specification (path + optional version)
//! - [`DependencyMetadata`]: Collection of dependencies by resource type
//! - [`DetailedDependency::dependencies`]: Field storing extracted transitive deps
//!
//! ### Processing Flow
//!
//! 1. Manifest dependencies are resolved first
//! 2. Resource files are checked for metadata (YAML frontmatter or JSON fields)
//! 3. Discovered dependencies are added to dependency graph
//! 4. Graph is validated for cycles
//! 5. Dependencies are resolved in topological order
//! 6. All resources (direct + transitive) are installed
//!
//! See [`dependency_spec`] module for detailed specification formats.
//!
//! ## Error Handling
//!
//! The manifest module provides comprehensive error handling with:
//! - **Context-rich errors**: Detailed messages with actionable suggestions
//! - **Validation errors**: Clear explanations of manifest problems
//! - **I/O errors**: Helpful context for file system issues
//! - **TOML parsing errors**: Specific syntax error locations
//! - **Security validation**: Detection of potential security issues
//!
//! All errors implement [`std::error::Error`] and provide both user-friendly
//! messages and programmatic access to error details.
//!
//! ## Performance Characteristics
//!
//! - **Parsing**: O(n) where n is the manifest file size
//! - **Validation**: O(d) where d is the number of dependencies
//! - **Serialization**: O(n) where n is the total data size
//! - **Memory usage**: Proportional to manifest complexity
//! - **Thread safety**: All operations are thread-safe
//!
//! ## Integration with Other Modules
//!
//! The manifest module works closely with other AGPM modules:
//!
//! ### With [`crate::resolver`]
//!
//! ```rust,ignore
//! use agpm_cli::manifest::Manifest;
//! use agpm_cli::resolver::DependencyResolver;
//!
//! let manifest = Manifest::load(&project_path.join("agpm.toml"))?;
//! let resolver = DependencyResolver::new(&manifest);
//! let resolved = resolver.resolve_all().await?;
//! ```
//!
//! ### With [`crate::lockfile`]
//!
//! ```rust,ignore  
//! use agpm_cli::manifest::Manifest;
//! use agpm_cli::lockfile::LockFile;
//!
//! let manifest = Manifest::load(&project_path.join("agpm.toml"))?;
//! let lockfile = LockFile::generate_from_manifest(&manifest).await?;
//! lockfile.save(&project_path.join("agpm.lock"))?;
//! ```
//!
//! ### With [`crate::git`] for Source Management
//!
//! ```rust,ignore
//! use agpm_cli::manifest::Manifest;
//! use agpm_cli::git::GitManager;
//!
//! let manifest = Manifest::load(&project_path.join("agpm.toml"))?;
//! let git = GitManager::new(&cache_dir);
//!
//! for (name, url) in &manifest.sources {
//!     git.clone_or_update(name, url).await?;
//! }
//! ```

pub mod dependency_spec;

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

pub use dependency_spec::{DependencyMetadata, DependencySpec};

/// The main manifest file structure representing a complete `agpm.toml` file.
///
/// This struct encapsulates all configuration for a AGPM project, including
/// source repositories, installation targets, and resource dependencies.
/// It provides the foundation for declarative dependency management similar
/// to Cargo's `Cargo.toml`.
///
/// # Structure
///
/// - **Sources**: Named Git repositories that can be referenced by dependencies
/// - **Target**: Installation directories for different resource types
/// - **Agents**: AI agent dependencies (`.md` files with agent definitions)
/// - **Snippets**: Code snippet dependencies (`.md` files with reusable code)
/// - **Commands**: Claude Code command dependencies (`.md` files with slash commands)
///
/// # Serialization
///
/// The struct uses Serde for TOML serialization/deserialization with these behaviors:
/// - Empty collections are omitted from serialized output for cleaner files
/// - Default values are automatically applied for missing fields
/// - Field names match TOML section names exactly
///
/// # Thread Safety
///
/// This struct is thread-safe and can be shared across async tasks safely.
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::manifest::{Manifest, ResourceDependency};
///
/// // Create a new empty manifest
/// let mut manifest = Manifest::new();
///
/// // Add a source repository
/// manifest.add_source(
///     "community".to_string(),
///     "https://github.com/claude-community/resources.git".to_string()
/// );
///
/// // Add a dependency
/// manifest.add_dependency(
///     "helper".to_string(),
///     ResourceDependency::Simple("../local/helper.md".to_string()),
///     true  // is_agent = true
/// );
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Manifest {
    /// Named source repositories mapped to their Git URLs.
    ///
    /// Keys are short, convenient names used in dependency specifications.
    /// Values are Git repository URLs (HTTPS, SSH, or local file:// URLs).
    ///
    /// **Security Note**: Never include authentication tokens in these URLs.
    /// Use SSH keys or configure authentication in the global config file.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [sources]
    /// official = "https://github.com/claude-org/official.git"
    /// private = "git@github.com:company/private.git"
    /// local = "file:///home/user/local-repo"
    /// ```
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub sources: HashMap<String, String>,

    /// Installation target directory configuration.
    ///
    /// Specifies where different resource types should be installed relative
    /// to the project root. Uses sensible defaults if not specified.
    ///
    /// See [`TargetConfig`] for details on default values and customization.
    #[deprecated(since = "0.4.0", note = "Use tools configuration instead")]
    #[serde(default)]
    pub target: TargetConfig,

    /// Tool type configurations for multi-tool support.
    ///
    /// Maps tool type names (claude-code, opencode, agpm, custom) to their
    /// installation configurations. This replaces the old `target` field and
    /// enables support for multiple tools and custom tool types.
    ///
    /// See [`ToolsConfig`] for details on configuration format.
    #[serde(rename = "tools", skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolsConfig>,

    /// Agent dependencies mapping names to their specifications.
    ///
    /// Agents are typically AI model definitions, prompts, or behavioral
    /// specifications stored as Markdown files. Each dependency can be
    /// either local (filesystem path) or remote (from a Git source).
    ///
    /// See [`ResourceDependency`] for specification format details.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub agents: HashMap<String, ResourceDependency>,

    /// Snippet dependencies mapping names to their specifications.
    ///
    /// Snippets are typically reusable code templates, examples, or
    /// documentation stored as Markdown files. They follow the same
    /// dependency format as agents.
    ///
    /// See [`ResourceDependency`] for specification format details.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub snippets: HashMap<String, ResourceDependency>,

    /// Command dependencies mapping names to their specifications.
    ///
    /// Commands are Claude Code slash commands that provide custom functionality
    /// and automation within the Claude Code interface. They follow the same
    /// dependency format as agents and snippets.
    ///
    /// See [`ResourceDependency`] for specification format details.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub commands: HashMap<String, ResourceDependency>,

    /// MCP server configurations mapping names to their specifications.
    ///
    /// MCP servers provide integrations with external systems and services,
    /// allowing Claude Code to connect to databases, APIs, and other tools.
    /// MCP servers are JSON configuration files that get installed to
    /// `.claude/agpm/mcp-servers/` and configured in `.mcp.json`.
    ///
    /// See [`ResourceDependency`] for specification format details.
    #[serde(default, skip_serializing_if = "HashMap::is_empty", rename = "mcp-servers")]
    pub mcp_servers: HashMap<String, ResourceDependency>,

    /// Script dependencies mapping names to their specifications.
    ///
    /// Scripts are executable files (.sh, .js, .py, etc.) that can be run by hooks
    /// or independently. They are installed to `.claude/agpm/scripts/` and can be
    /// referenced by hook configurations.
    ///
    /// See [`ResourceDependency`] for specification format details.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub scripts: HashMap<String, ResourceDependency>,

    /// Hook dependencies mapping names to their specifications.
    ///
    /// Hooks are JSON configuration files that define event-based automation
    /// in Claude Code. They specify when to run scripts based on tool usage,
    /// prompts, and other events. Hook configurations are merged into
    /// `settings.local.json`.
    ///
    /// See [`ResourceDependency`] for specification format details.
    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    pub hooks: HashMap<String, ResourceDependency>,
}

/// Resource configuration within a tool.
///
/// Defines the installation path for a specific resource type within a tool.
/// The path can be omitted for resources that have special handling (e.g., MCP servers
/// that merge into configuration files instead of being installed as separate files).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ResourceConfig {
    /// Subdirectory path for this resource type relative to the tool's base directory.
    ///
    /// None means special handling (e.g., MCP servers that merge into config files)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
}

/// Tool configuration.
///
/// Defines how a specific tool (e.g., claude-code, opencode, agpm)
/// organizes its resources. Each tool has a base directory and
/// a map of resource types to their subdirectory configurations.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactTypeConfig {
    /// Base directory for this tool (e.g., ".claude", ".opencode", ".agpm")
    pub path: PathBuf,

    /// Map of resource type -> configuration
    pub resources: HashMap<String, ResourceConfig>,
}

/// Top-level tools configuration.
///
/// Maps tool type names to their configurations. This replaces the old
/// `[target]` section and enables multi-tool support.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolsConfig {
    /// Map of tool type name -> configuration
    #[serde(flatten)]
    pub types: HashMap<String, ArtifactTypeConfig>,
}

impl Default for ToolsConfig {
    fn default() -> Self {
        use crate::core::ResourceType;
        let mut types = HashMap::new();

        // Claude Code configuration
        let mut claude_resources = HashMap::new();
        claude_resources.insert(
            ResourceType::Agent.to_plural().to_string(),
            ResourceConfig {
                path: Some("agents".to_string()),
            },
        );
        claude_resources.insert(
            ResourceType::Snippet.to_plural().to_string(),
            ResourceConfig {
                path: Some("agpm/snippets".to_string()),
            },
        );
        claude_resources.insert(
            ResourceType::Command.to_plural().to_string(),
            ResourceConfig {
                path: Some("commands".to_string()),
            },
        );
        claude_resources.insert(
            ResourceType::Script.to_plural().to_string(),
            ResourceConfig {
                path: Some("agpm/scripts".to_string()),
            },
        );
        claude_resources.insert(
            ResourceType::Hook.to_plural().to_string(),
            ResourceConfig {
                path: Some("agpm/hooks".to_string()),
            },
        );
        claude_resources.insert(
            ResourceType::McpServer.to_plural().to_string(),
            ResourceConfig {
                path: Some("agpm/mcp-servers".to_string()),
            },
        );

        types.insert(
            "claude-code".to_string(),
            ArtifactTypeConfig {
                path: PathBuf::from(".claude"),
                resources: claude_resources,
            },
        );

        // OpenCode configuration
        let mut opencode_resources = HashMap::new();
        opencode_resources.insert(
            ResourceType::Agent.to_plural().to_string(),
            ResourceConfig {
                path: Some("agent".to_string()), // Singular
            },
        );
        opencode_resources.insert(
            ResourceType::Command.to_plural().to_string(),
            ResourceConfig {
                path: Some("command".to_string()), // Singular
            },
        );
        opencode_resources.insert(
            ResourceType::McpServer.to_plural().to_string(),
            ResourceConfig {
                path: Some("agpm/mcp-servers".to_string()), // Temporary staging area for merge
            },
        );

        types.insert(
            "opencode".to_string(),
            ArtifactTypeConfig {
                path: PathBuf::from(".opencode"),
                resources: opencode_resources,
            },
        );

        // AGPM configuration (snippets only)
        let mut agpm_resources = HashMap::new();
        agpm_resources.insert(
            ResourceType::Snippet.to_plural().to_string(),
            ResourceConfig {
                path: Some("snippets".to_string()),
            },
        );

        types.insert(
            "agpm".to_string(),
            ArtifactTypeConfig {
                path: PathBuf::from(".agpm"),
                resources: agpm_resources,
            },
        );

        Self {
            types,
        }
    }
}

/// Target directories configuration specifying where resources are installed.
///
/// This struct defines the installation destinations for different resource types
/// within a AGPM project. All paths are relative to the project root (where
/// `agpm.toml` is located) unless they are absolute paths.
///
/// # Default Values
///
/// - **Agents**: `.claude/agents` - Following Claude Code conventions
/// - **Snippets**: `.claude/agpm/snippets` - Following Claude Code conventions
/// - **Commands**: `.claude/commands` - Following Claude Code conventions
///
/// # Path Resolution
///
/// - Relative paths are resolved from the manifest directory
/// - Absolute paths are used as-is (not recommended for portability)
/// - Path separators are automatically normalized for the target platform
/// - Directories are created automatically during installation if they don't exist
///
/// # Examples
///
/// ```toml
/// # Default configuration (can be omitted)
/// [target]
/// agents = ".claude/agents"
/// snippets = ".claude/agpm/snippets"
/// commands = ".claude/commands"
///
/// # Custom configuration
/// [target]
/// agents = "resources/ai-agents"
/// snippets = "templates/code-snippets"
/// commands = "resources/commands"
///
/// # Absolute paths (use with caution)
/// [target]
/// agents = "/opt/claude/agents"
/// snippets = "/opt/claude/snippets"
/// commands = "/opt/claude/commands"
/// ```
///
/// # Cross-Platform Considerations
///
/// AGPM automatically handles platform differences:
/// - Forward slashes work on all platforms (Windows, macOS, Linux)
/// - Path separators are normalized during installation
/// - Long path support on Windows is handled automatically
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TargetConfig {
    /// Directory where agent `.md` files should be installed.
    ///
    /// Agents are AI model definitions, prompts, or behavioral specifications.
    /// This directory will contain copies of agent files from dependencies.
    ///
    /// **Default**: `.claude/agents` (following Claude Code conventions)
    #[serde(default = "default_agents_dir")]
    pub agents: String,

    /// Directory where snippet `.md` files should be installed.
    ///
    /// Snippets are reusable code templates, examples, or documentation.
    /// This directory will contain copies of snippet files from dependencies.
    ///
    /// **Default**: `.claude/agpm/snippets` (following Claude Code conventions)
    #[serde(default = "default_snippets_dir")]
    pub snippets: String,

    /// Directory where command `.md` files should be installed.
    ///
    /// Commands are Claude Code slash commands that provide custom functionality.
    /// This directory will contain copies of command files from dependencies.
    ///
    /// **Default**: `.claude/commands` (following Claude Code conventions)
    #[serde(default = "default_commands_dir")]
    pub commands: String,

    /// Directory where MCP server configurations should be tracked.
    ///
    /// Note: MCP servers are configured in `.mcp.json` at the project root,
    /// not installed to this directory. This directory is used for tracking
    /// metadata about installed servers.
    ///
    /// **Default**: `.claude/agpm/mcp-servers` (following Claude Code conventions)
    #[serde(default = "default_mcp_servers_dir", rename = "mcp-servers")]
    pub mcp_servers: String,

    /// Directory where script files should be installed.
    ///
    /// Scripts are executable files (.sh, .js, .py, etc.) that can be referenced
    /// by hooks or run independently.
    ///
    /// **Default**: `.claude/agpm/scripts` (following Claude Code conventions)
    #[serde(default = "default_scripts_dir")]
    pub scripts: String,

    /// Directory where hook configuration files should be installed.
    ///
    /// Hooks are JSON configuration files that define event-based automation
    /// in Claude Code.
    ///
    /// **Default**: `.claude/agpm/hooks` (following Claude Code conventions)
    #[serde(default = "default_hooks_dir")]
    pub hooks: String,

    /// Whether to automatically add installed files to `.gitignore`.
    ///
    /// When enabled (default), AGPM will create or update `.gitignore`
    /// to exclude all installed files from version control. This prevents
    /// installed dependencies from being committed to your repository.
    ///
    /// Set to `false` if you want to commit installed resources to version control.
    ///
    /// **Default**: `true`
    #[serde(default = "default_gitignore")]
    pub gitignore: bool,
}

impl Default for TargetConfig {
    fn default() -> Self {
        Self {
            agents: default_agents_dir(),
            snippets: default_snippets_dir(),
            commands: default_commands_dir(),
            mcp_servers: default_mcp_servers_dir(),
            scripts: default_scripts_dir(),
            hooks: default_hooks_dir(),
            gitignore: default_gitignore(),
        }
    }
}

fn default_agents_dir() -> String {
    ".claude/agents".to_string()
}

fn default_snippets_dir() -> String {
    ".claude/agpm/snippets".to_string()
}

fn default_commands_dir() -> String {
    ".claude/commands".to_string()
}

fn default_mcp_servers_dir() -> String {
    ".claude/agpm/mcp-servers".to_string()
}

fn default_scripts_dir() -> String {
    ".claude/agpm/scripts".to_string()
}

fn default_hooks_dir() -> String {
    ".claude/agpm/hooks".to_string()
}

const fn default_gitignore() -> bool {
    true
}

/// A resource dependency specification supporting multiple formats.
///
/// Dependencies can be specified in two main formats to balance simplicity
/// with flexibility. The enum uses Serde's `untagged` attribute to automatically
/// deserialize the correct variant based on the TOML structure.
///
/// # Variants
///
/// ## Simple Dependencies
///
/// For local file dependencies, just specify the path directly:
///
/// ```toml
/// [agents]
/// local-helper = "../shared/agents/helper.md"
/// nearby-agent = "./local/custom-agent.md"
/// ```
///
/// ## Detailed Dependencies
///
/// For remote dependencies or when you need more control:
///
/// ```toml
/// [agents]
/// # Remote dependency with version
/// code-reviewer = { source = "official", path = "agents/reviewer.md", version = "v1.0.0" }
///
/// # Remote dependency with git reference
/// experimental = { source = "community", path = "agents/new.md", git = "develop" }
///
/// # Local dependency with explicit path (equivalent to simple form)
/// local-tool = { path = "../tools/agent.md" }
/// ```
///
/// # Validation Rules
///
/// - **Local dependencies** (no source): Cannot have version constraints
/// - **Remote dependencies** (with source): Must have either `version` or `git` field
/// - **Path field**: Required and cannot be empty
/// - **Source field**: Must reference an existing source in the `[sources]` section
///
/// # Type Safety
///
/// The enum ensures type safety at compile time while providing runtime
/// validation through the [`Manifest::validate`] method.
///
/// # Serialization Behavior
///
/// - Simple paths serialize directly as strings
/// - Detailed specs serialize as TOML inline tables
/// - Empty optional fields are omitted for cleaner output
/// - Deserialization is automatic based on TOML structure
///
/// # Memory Layout
///
/// This enum uses `#[serde(untagged)]` for automatic variant detection,
/// which means deserialization tries the `Detailed` variant first, then
/// falls back to `Simple`. This is efficient for the expected usage patterns
/// where detailed dependencies are more common in larger projects.
///
/// # Memory Layout
///
/// The `Detailed` variant is boxed to reduce the size of the enum from 264 bytes
/// to 24 bytes, improving memory efficiency when many dependencies are stored.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ResourceDependency {
    /// Simple path-only dependency, typically for local files.
    ///
    /// This variant represents the simplest dependency format where only
    /// a file path is specified. It's primarily used for local dependencies
    /// that exist in the filesystem relative to the project.
    ///
    /// # Format
    ///
    /// ```toml
    /// dependency-name = "path/to/file.md"
    /// ```
    ///
    /// # Examples
    ///
    /// ```toml
    /// [agents]
    /// # Relative paths from manifest directory
    /// helper = "../shared/helper.md"
    /// custom = "./local/custom.md"
    ///
    /// # Absolute paths (not recommended)
    /// system = "/usr/local/share/agent.md"
    /// ```
    ///
    /// # Limitations
    ///
    /// - Cannot specify version constraints
    /// - Cannot reference remote Git sources
    /// - Must be a valid filesystem path
    /// - Path must exist at installation time
    Simple(String),

    /// Detailed dependency specification with full control.
    ///
    /// This variant provides complete control over dependency specification,
    /// supporting both local and remote dependencies with version constraints,
    /// Git references, and explicit source mapping.
    ///
    /// See [`DetailedDependency`] for field-level documentation.
    ///
    /// Note: This variant is boxed to reduce the overall size of the enum.
    Detailed(Box<DetailedDependency>),
}

/// Detailed dependency specification with full control over source resolution.
///
/// This struct provides fine-grained control over dependency specification,
/// supporting both local filesystem paths and remote Git repository resources
/// with flexible version constraints and Git reference handling.
///
/// # Field Relationships
///
/// The fields work together with specific validation rules:
/// - If `source` is specified: Must have either `version` or `git`
/// - If `source` is omitted: Dependency is local, `version` and `git` are ignored
/// - `path` is always required and cannot be empty
///
/// # Examples
///
/// ## Remote Dependencies
///
/// ```toml
/// [agents]
/// # Semantic version constraint
/// stable = { source = "official", path = "agents/stable.md", version = "v1.0.0" }
///
/// # Latest version (not recommended for production)
/// latest = { source = "community", path = "agents/utils.md", version = "latest" }
///
/// # Specific Git branch
/// cutting-edge = { source = "official", path = "agents/new.md", git = "develop" }
///
/// # Specific commit SHA (maximum reproducibility)
/// pinned = { source = "community", path = "agents/tool.md", git = "a1b2c3d4e5f6..." }
///
/// # Git tag
/// release = { source = "official", path = "agents/release.md", git = "v2.0-release" }
/// ```
///
/// ## Local Dependencies
///
/// ```toml
/// [agents]
/// # Local file (version/git fields ignored if present)
/// local-helper = { path = "../shared/helper.md" }
/// custom = { path = "./local/custom.md" }
/// ```
///
/// # Version Resolution Priority
///
/// When both `version` and `git` are specified, `git` takes precedence:
///
/// ```toml
/// # This will use the "develop" branch, not "v1.0.0"
/// conflicted = { source = "repo", path = "file.md", version = "v1.0.0", git = "develop" }
/// ```
///
/// # Path Format
///
/// Paths are interpreted differently based on context:
/// - **Remote dependencies**: Path within the Git repository
/// - **Local dependencies**: Filesystem path relative to manifest directory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DetailedDependency {
    /// Source repository name referencing the `[sources]` section.
    ///
    /// When specified, this dependency will be resolved from a Git repository.
    /// The name must exactly match a key in the manifest's `[sources]` table.
    ///
    /// **Omit this field** to create a local filesystem dependency.
    ///
    /// # Examples
    ///
    /// ```toml
    /// # References this source definition:
    /// [sources]
    /// official = "https://github.com/org/repo.git"
    ///
    /// [agents]
    /// remote-agent = { source = "official", path = "agents/tool.md", version = "v1.0.0" }
    /// local-agent = { path = "../local/tool.md" }  # No source = local dependency
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,

    /// Path to the resource file or glob pattern for multiple resources.
    ///
    /// For **remote dependencies**: Path within the Git repository\
    /// For **local dependencies**: Filesystem path relative to manifest directory\
    /// For **pattern dependencies**: Glob pattern to match multiple resources
    ///
    /// This field supports both individual file paths and glob patterns:
    /// - Individual file: `"agents/helper.md"`
    /// - Pattern matching: `"agents/*.md"`, `"**/*.md"`, `"agents/[a-z]*.md"`
    ///
    /// Pattern dependencies are detected by the presence of glob characters
    /// (`*`, `?`, `[`) in the path. When a pattern is detected, AGPM will
    /// expand it to match all resources in the source repository.
    ///
    /// # Examples
    ///
    /// ```toml
    /// # Remote: single file in git repo
    /// remote = { source = "repo", path = "agents/helper.md", version = "v1.0.0" }
    ///
    /// # Local: filesystem path
    /// local = { path = "../shared/helper.md" }
    ///
    /// # Pattern: all agents in AI folder
    /// ai_agents = { source = "repo", path = "agents/ai/*.md", version = "v1.0.0" }
    ///
    /// # Pattern: all agents recursively
    /// all_agents = { source = "repo", path = "agents/**/*.md", version = "v1.0.0" }
    /// ```
    pub path: String,

    /// Version constraint for Git tag resolution.
    ///
    /// Specifies which version of the resource to use when resolving from
    /// a Git repository. This field is ignored for local dependencies.
    ///
    /// **Note**: If both `version` and `git` are specified, `git` takes precedence.
    ///
    /// # Supported Formats
    ///
    /// - `"v1.0.0"` - Exact semantic version tag
    /// - `"1.0.0"` - Exact version (v prefix optional)
    /// - `"^1.0.0"` - Semantic version constraint (highest compatible 1.x.x)
    /// - `"latest"` - Git tag or branch named "latest" (not special - just a name)
    /// - `"main"` - Use main/master branch HEAD
    ///
    /// # Examples
    ///
    /// ```toml
    /// [agents]
    /// stable = { source = "repo", path = "agent.md", version = "v1.0.0" }
    /// flexible = { source = "repo", path = "agent.md", version = "^1.0.0" }
    /// latest-tag = { source = "repo", path = "agent.md", version = "latest" }  # If repo has a "latest" tag
    /// main = { source = "repo", path = "agent.md", version = "main" }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Git branch to track.
    ///
    /// Specifies a Git branch to use when resolving the dependency.
    /// Branch references are mutable and will update to the latest commit on each update.
    /// This field is ignored for local dependencies.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [agents]
    /// # Track the main branch
    /// dev = { source = "repo", path = "agent.md", branch = "main" }
    ///
    /// # Track a feature branch
    /// experimental = { source = "repo", path = "agent.md", branch = "feature/new-capability" }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,

    /// Git commit hash (revision).
    ///
    /// Specifies an exact Git commit to use when resolving the dependency.
    /// Provides maximum reproducibility as commits are immutable.
    /// This field is ignored for local dependencies.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [agents]
    /// # Pin to exact commit (full hash)
    /// pinned = { source = "repo", path = "agent.md", rev = "a1b2c3d4e5f67890abcdef1234567890abcdef12" }
    ///
    /// # Pin to exact commit (abbreviated)
    /// stable = { source = "repo", path = "agent.md", rev = "abc123def" }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rev: Option<String>,

    /// Command to execute for MCP servers.
    ///
    /// This field is specific to MCP server dependencies and specifies
    /// the command that will be executed to run the MCP server.
    /// Only used for entries in the `[mcp-servers]` section.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [mcp-servers]
    /// github = { source = "repo", path = "mcp/github.toml", version = "v1.0.0", command = "npx" }
    /// sqlite = { path = "./local/sqlite.toml", command = "uvx" }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<String>,

    /// Arguments to pass to the MCP server command.
    ///
    /// This field is specific to MCP server dependencies and provides
    /// the arguments that will be passed to the command when starting
    /// the MCP server. Only used for entries in the `[mcp-servers]` section.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [mcp-servers]
    /// github = {
    ///     source = "repo",
    ///     path = "mcp/github.toml",
    ///     version = "v1.0.0",
    ///     command = "npx",
    ///     args = ["-y", "@modelcontextprotocol/server-github"]
    /// }
    /// sqlite = {
    ///     path = "./local/sqlite.toml",
    ///     command = "uvx",
    ///     args = ["mcp-server-sqlite", "--db", "./data/local.db"]
    /// }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub args: Option<Vec<String>>,
    /// Custom target directory for this dependency.
    ///
    /// Overrides the default installation directory for this specific dependency.
    /// The path is relative to the `.claude` directory for consistency and security.
    /// If not specified, the dependency will be installed to the default location
    /// based on its resource type.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [agents]
    /// # Install to .claude/custom/tools/ instead of default .claude/agents/
    /// special-agent = {
    ///     source = "repo",
    ///     path = "agent.md",
    ///     version = "v1.0.0",
    ///     target = "custom/tools"
    /// }
    ///
    /// # Install to .claude/integrations/ai/
    /// integration = {
    ///     source = "repo",
    ///     path = "integration.md",
    ///     version = "v2.0.0",
    ///     target = "integrations/ai"
    /// }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,

    /// Custom filename for this dependency.
    ///
    /// Overrides the default filename (which is based on the dependency key).
    /// The filename should include the desired file extension. If not specified,
    /// the dependency will be installed using the key name with an automatically
    /// determined extension based on the resource type.
    ///
    /// # Examples
    ///
    /// ```toml
    /// [agents]
    /// # Install as "ai-assistant.md" instead of "my-ai.md"
    /// my-ai = {
    ///     source = "repo",
    ///     path = "agent.md",
    ///     version = "v1.0.0",
    ///     filename = "ai-assistant.md"
    /// }
    ///
    /// # Install with a different extension
    /// doc-agent = {
    ///     source = "repo",
    ///     path = "documentation.md",
    ///     version = "v2.0.0",
    ///     filename = "docs-helper.txt"
    /// }
    ///
    /// [scripts]
    /// # Rename a script during installation
    /// analyzer = {
    ///     source = "repo",
    ///     path = "scripts/data-analyzer-v3.py",
    ///     version = "v1.0.0",
    ///     filename = "analyze.py"
    /// }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub filename: Option<String>,

    /// Transitive dependencies on other resources.
    ///
    /// This field is populated from metadata extracted from the resource file itself
    /// (YAML frontmatter in .md files or JSON fields in .json files).
    /// Maps resource type to list of dependency specifications.
    ///
    /// Example:
    /// ```toml
    /// # This would be extracted from the file's frontmatter/JSON, not specified in agpm.toml
    /// # { "agents": [{"path": "agents/helper.md", "version": "v1.0.0"}] }
    /// ```
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dependencies: Option<HashMap<String, Vec<DependencySpec>>>,

    /// Tool type (claude-code, opencode, agpm, or custom).
    ///
    /// Specifies which target AI coding assistant tool this resource is for. This determines
    /// where the resource is installed and how it's configured.
    ///
    /// **Defaults to "claude-code"** for backward compatibility with existing manifests.
    ///
    /// Omitted from TOML serialization when the value is "claude-code" (default).
    #[serde(default = "default_tool", skip_serializing_if = "is_default_tool")]
    pub tool: String,
}

fn default_tool() -> String {
    "claude-code".to_string()
}

fn is_default_tool(tool: &str) -> bool {
    tool == "claude-code"
}

impl Manifest {
    /// Create a new empty manifest with default configuration.
    ///
    /// The new manifest will have:
    /// - No sources defined
    /// - Default target directories (`.claude/agents` and `.claude/agpm/snippets`)
    /// - No dependencies
    ///
    /// This is typically used when programmatically building a manifest or
    /// as a starting point for adding dependencies.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::Manifest;
    ///
    /// let manifest = Manifest::new();
    /// assert!(manifest.sources.is_empty());
    /// assert!(manifest.agents.is_empty());
    /// assert!(manifest.snippets.is_empty());
    /// assert!(manifest.commands.is_empty());
    /// assert!(manifest.mcp_servers.is_empty());
    /// assert_eq!(manifest.target.agents, ".claude/agents");
    /// ```
    #[must_use]
    #[allow(deprecated)]
    pub fn new() -> Self {
        Self {
            sources: HashMap::new(),
            target: TargetConfig::default(),
            tools: None,
            agents: HashMap::new(),
            snippets: HashMap::new(),
            commands: HashMap::new(),
            mcp_servers: HashMap::new(),
            scripts: HashMap::new(),
            hooks: HashMap::new(),
        }
    }

    /// Load and parse a manifest from a TOML file.
    ///
    /// This method reads the specified file, parses it as TOML, deserializes
    /// it into a [`Manifest`] struct, and validates the result. The entire
    /// operation is atomic - either the manifest loads successfully or an
    /// error is returned.
    ///
    /// # Validation
    ///
    /// After parsing, the manifest is automatically validated to ensure:
    /// - All dependency sources reference valid entries in the `[sources]` section
    /// - Required fields are present and non-empty
    /// - Version constraints are properly specified for remote dependencies
    /// - Source URLs use supported protocols
    /// - No version conflicts exist between dependencies
    ///
    /// # Error Handling
    ///
    /// Returns detailed errors for common problems:
    /// - **File I/O errors**: File not found, permission denied, etc.
    /// - **TOML syntax errors**: Invalid TOML format with helpful suggestions
    /// - **Validation errors**: Logical inconsistencies in the manifest
    /// - **Security errors**: Unsafe URL patterns or credential leakage
    ///
    /// All errors include contextual information and actionable suggestions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run,ignore
    /// use agpm_cli::manifest::Manifest;
    /// use std::path::Path;
    ///
    /// // Load a manifest file
    /// let manifest = Manifest::load(Path::new("agpm.toml"))?;
    ///
    /// // Access parsed data
    /// println!("Found {} sources", manifest.sources.len());
    /// println!("Found {} agents", manifest.agents.len());
    /// println!("Found {} snippets", manifest.snippets.len());
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # File Format
    ///
    /// Expects a valid TOML file following the AGPM manifest format.
    /// See the module-level documentation for complete format specification.
    pub fn load(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path).with_context(|| {
            format!(
                "Cannot read manifest file: {}\n\n\
                    Possible causes:\n\
                    - File doesn't exist or has been moved\n\
                    - Permission denied (check file ownership)\n\
                    - File is locked by another process",
                path.display()
            )
        })?;

        let mut manifest: Self = toml::from_str(&content)
            .map_err(|e| crate::core::AgpmError::ManifestParseError {
                file: path.display().to_string(),
                reason: e.to_string(),
            })
            .with_context(|| {
                format!(
                    "Invalid TOML syntax in manifest file: {}\n\n\
                    Common TOML syntax errors:\n\
                    - Missing quotes around strings\n\
                    - Unmatched brackets [ ] or braces {{ }}\n\
                    - Invalid characters in keys or values\n\
                    - Incorrect indentation or structure",
                    path.display()
                )
            })?;

        // Apply resource-type-specific defaults for tool
        // Snippets default to "agpm" (shared infrastructure) instead of "claude-code"
        manifest.apply_tool_defaults();

        manifest.validate()?;

        Ok(manifest)
    }

    /// Apply resource-type-specific defaults for tool.
    ///
    /// This method adjusts the tool field based on the resource type to provide
    /// more sensible defaults:
    /// - **Snippets**: Default to "agpm" (shared infrastructure) instead of "claude-code"
    /// - **All other resources**: Keep "claude-code" as the default
    ///
    /// This is called automatically after deserialization in `load()`.
    ///
    /// # Rationale
    ///
    /// Snippets are designed to be shared content across multiple tools (Claude Code,
    /// OpenCode, etc.). The `.agpm/snippets/` location provides a shared infrastructure
    /// that can be referenced by resources from different tools. Therefore, snippets
    /// should default to the "agpm" tool type.
    ///
    /// Users can still explicitly set `tool = "claude-code"` for a snippet if they want
    /// it installed to `.claude/agpm/snippets/` instead.
    fn apply_tool_defaults(&mut self) {
        // Apply snippet-specific default: "agpm" instead of "claude-code"
        for dependency in self.snippets.values_mut() {
            if let ResourceDependency::Detailed(details) = dependency {
                // Only change if it's still the serde default ("claude-code")
                // This means: no explicit type was specified in the manifest
                if details.tool == "claude-code" {
                    details.tool = "agpm".to_string();
                }
            }
        }
    }

    /// Save the manifest to a TOML file with pretty formatting.
    ///
    /// This method serializes the manifest to TOML format and writes it to the
    /// specified file path. The output is pretty-printed for human readability
    /// and follows TOML best practices.
    ///
    /// # Formatting
    ///
    /// The generated TOML file will:
    /// - Use consistent indentation and spacing
    /// - Omit empty sections for cleaner output
    /// - Order sections logically (sources, target, agents, snippets)
    /// - Include inline tables for detailed dependencies
    ///
    /// # Atomic Operation
    ///
    /// The save operation is atomic - the file is either completely written
    /// or left unchanged. This prevents corruption if the operation fails
    /// partway through.
    ///
    /// # Error Handling
    ///
    /// Returns detailed errors for common problems:
    /// - **Permission denied**: Insufficient write permissions
    /// - **Directory doesn't exist**: Parent directory missing  
    /// - **Disk full**: Insufficient storage space
    /// - **File locked**: Another process has the file open
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::Manifest;
    /// use std::path::Path;
    ///
    /// let mut manifest = Manifest::new();
    /// manifest.add_source(
    ///     "official".to_string(),
    ///     "https://github.com/claude-org/resources.git".to_string()
    /// );
    ///
    /// // Save to file
    /// # use tempfile::tempdir;
    /// # let temp_dir = tempdir()?;
    /// # let manifest_path = temp_dir.path().join("agpm.toml");
    /// manifest.save(&manifest_path)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Output Format
    ///
    /// The generated file will follow this structure:
    ///
    /// ```toml
    /// [sources]
    /// official = "https://github.com/claude-org/resources.git"
    ///
    /// [target]
    /// agents = ".claude/agents"
    /// snippets = ".claude/agpm/snippets"
    ///
    /// [agents]
    /// helper = { source = "official", path = "agents/helper.md", version = "v1.0.0" }
    ///
    /// [snippets]
    /// utils = { source = "official", path = "snippets/utils.md", version = "v1.0.0" }
    /// ```
    pub fn save(&self, path: &Path) -> Result<()> {
        let content = toml::to_string_pretty(self)
            .with_context(|| "Failed to serialize manifest data to TOML format")?;

        std::fs::write(path, content).with_context(|| {
            format!(
                "Cannot write manifest file: {}\n\n\
                    Possible causes:\n\
                    - Permission denied (try running with elevated permissions)\n\
                    - Directory doesn't exist\n\
                    - Disk is full or read-only\n\
                    - File is locked by another process",
                path.display()
            )
        })?;

        Ok(())
    }

    /// Validate the manifest structure and enforce business rules.
    ///
    /// This method performs comprehensive validation of the manifest to ensure
    /// logical consistency, security best practices, and correct dependency
    /// relationships. It's automatically called during [`Self::load`] but can
    /// also be used independently to validate programmatically constructed manifests.
    ///
    /// # Validation Rules
    ///
    /// ## Source Validation
    /// - All source URLs must use supported protocols (HTTPS, SSH, git://, file://)
    /// - No plain directory paths allowed as sources (must use file:// URLs)
    /// - No authentication tokens embedded in URLs (security check)
    /// - Environment variable expansion is validated for syntax
    ///
    /// ## Dependency Validation  
    /// - All dependency paths must be non-empty
    /// - Remote dependencies must reference existing sources
    /// - Remote dependencies must specify version constraints
    /// - Local dependencies cannot have version constraints
    /// - No version conflicts between dependencies with the same name
    ///
    /// ## Path Validation
    /// - Local dependency paths are checked for proper format
    /// - Remote dependency paths are validated as repository-relative
    /// - Path traversal attempts are detected and rejected
    ///
    /// # Error Types
    ///
    /// Returns specific error types for different validation failures:
    /// - [`crate::core::AgpmError::SourceNotFound`]: Referenced source doesn't exist
    /// - [`crate::core::AgpmError::ManifestValidationError`]: General validation failures
    /// - Context errors for specific issues with actionable suggestions
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{Manifest, ResourceDependency, DetailedDependency};
    ///
    /// let mut manifest = Manifest::new();
    ///
    /// // This will pass validation (local dependency)
    /// manifest.add_dependency(
    ///     "local".to_string(),
    ///     ResourceDependency::Simple("../local/helper.md".to_string()),
    ///     true
    /// );
    /// assert!(manifest.validate().is_ok());
    ///
    /// // This will fail validation (missing source)
    /// manifest.add_dependency(
    ///     "remote".to_string(),
    ///     ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///         source: Some("missing".to_string()),
    ///         path: "agent.md".to_string(),
    ///         version: Some("v1.0.0".to_string()),
    ///         branch: None,
    ///         rev: None,
    ///         command: None,
    ///         args: None,
    ///         target: None,
    ///         filename: None,
    ///         dependencies: None,
    ///         tool: "claude-code".to_string(),
    ///     })),
    ///     true
    /// );
    /// assert!(manifest.validate().is_err());
    /// ```
    ///
    /// # Security Considerations
    ///
    /// This method enforces critical security rules:
    /// - Prevents credential leakage in version-controlled files
    /// - Blocks path traversal attacks in local dependencies
    /// - Validates URL schemes to prevent protocol confusion
    /// - Checks for malicious patterns in dependency specifications
    ///
    /// # Performance
    ///
    /// Validation is designed to be fast and is safe to call frequently.
    /// Complex validations (like network connectivity) are not performed
    /// here - those are handled during dependency resolution.
    pub fn validate(&self) -> Result<()> {
        // Validate artifact type names
        for artifact_type in self.get_tools_config().types.keys() {
            if artifact_type.contains('/') || artifact_type.contains('\\') {
                return Err(crate::core::AgpmError::ManifestValidationError {
                    reason: format!(
                        "Artifact type name '{artifact_type}' cannot contain path separators ('/' or '\\\\'). \n\
                        Artifact type names must be simple identifiers without special characters."
                    ),
                }
                .into());
            }

            // Also check for other potentially problematic characters
            if artifact_type.contains("..") {
                return Err(crate::core::AgpmError::ManifestValidationError {
                    reason: format!(
                        "Artifact type name '{artifact_type}' cannot contain '..' (path traversal). \n\
                        Artifact type names must be simple identifiers."
                    ),
                }
                .into());
            }
        }

        // Check that all referenced sources exist and dependencies have required fields
        for (name, dep) in self.all_dependencies() {
            // Check for empty path
            if dep.get_path().is_empty() {
                return Err(crate::core::AgpmError::ManifestValidationError {
                    reason: format!("Missing required field 'path' for dependency '{name}'"),
                }
                .into());
            }

            // Validate pattern safety if it's a pattern dependency
            if dep.is_pattern() {
                crate::pattern::validate_pattern_safety(dep.get_path()).map_err(|e| {
                    crate::core::AgpmError::ManifestValidationError {
                        reason: format!("Invalid pattern in dependency '{name}': {e}"),
                    }
                })?;
            }

            // Check for version when source is specified (non-local dependencies)
            if let Some(source) = dep.get_source() {
                if !self.sources.contains_key(source) {
                    return Err(crate::core::AgpmError::SourceNotFound {
                        name: source.to_string(),
                    }
                    .into());
                }

                // Check if the source URL is a local path
                let source_url = self.sources.get(source).unwrap();
                let _is_local_source = source_url.starts_with('/')
                    || source_url.starts_with("./")
                    || source_url.starts_with("../");

                // Git dependencies can optionally have a version (defaults to 'main' if not specified)
                // Local path sources don't need versions
                // We no longer require versions for Git dependencies - they'll default to 'main'
            } else {
                // For local path dependencies (no source), version is not allowed
                // Skip directory check for pattern dependencies
                if !dep.is_pattern() {
                    let path = dep.get_path();
                    let is_plain_dir =
                        path.starts_with('/') || path.starts_with("./") || path.starts_with("../");

                    if is_plain_dir && dep.get_version().is_some() {
                        return Err(crate::core::AgpmError::ManifestValidationError {
                            reason: format!(
                                "Version specified for plain directory dependency '{name}' with path '{path}'. \n\
                                Plain directory dependencies do not support versions. \n\
                            Remove the 'version' field or use a git source instead."
                            ),
                        }
                        .into());
                    }
                }
            }
        }

        // Check for version conflicts (same dependency name with different versions)
        let mut seen_deps: std::collections::HashMap<String, String> =
            std::collections::HashMap::new();
        for (name, dep) in self.all_dependencies() {
            if let Some(version) = dep.get_version() {
                if let Some(existing_version) = seen_deps.get(name) {
                    if existing_version != version {
                        return Err(crate::core::AgpmError::ManifestValidationError {
                            reason: format!(
                                "Version conflict for dependency '{name}': found versions '{existing_version}' and '{version}'"
                            ),
                        }
                        .into());
                    }
                } else {
                    seen_deps.insert(name.to_string(), version.to_string());
                }
            }
        }

        // Validate URLs in sources
        for (name, url) in &self.sources {
            // Expand environment variables and home directory in URL
            let expanded_url = expand_url(url)?;

            if !expanded_url.starts_with("http://")
                && !expanded_url.starts_with("https://")
                && !expanded_url.starts_with("git@")
                && !expanded_url.starts_with("file://")
            // Plain directory paths not allowed as sources
            && !expanded_url.starts_with('/')
            && !expanded_url.starts_with("./")
            && !expanded_url.starts_with("../")
            {
                return Err(crate::core::AgpmError::ManifestValidationError {
                    reason: format!("Source '{name}' has invalid URL: '{url}'. Must be HTTP(S), SSH (git@...), or file:// URL"),
                }
                .into());
            }

            // Check if plain directory path is used as a source
            if expanded_url.starts_with('/')
                || expanded_url.starts_with("./")
                || expanded_url.starts_with("../")
            {
                return Err(crate::core::AgpmError::ManifestValidationError {
                    reason: format!(
                        "Plain directory path '{url}' cannot be used as source '{name}'. \n\
                        Sources must be git repositories. Use one of:\n\
                        - Remote URL: https://github.com/owner/repo.git\n\
                        - Local git repo: file:///absolute/path/to/repo\n\
                        - Or use direct path dependencies without a source"
                    ),
                }
                .into());
            }
        }

        // Check for case-insensitive conflicts on all platforms
        // This ensures manifests are portable across different filesystems
        // Even though Linux supports case-sensitive files, we reject conflicts
        // to ensure the manifest works on Windows and macOS too
        let mut normalized_names: std::collections::HashSet<String> =
            std::collections::HashSet::new();

        for (name, _) in self.all_dependencies() {
            let normalized = name.to_lowercase();
            if !normalized_names.insert(normalized.clone()) {
                // Find the original conflicting name
                for (other_name, _) in self.all_dependencies() {
                    if other_name != name && other_name.to_lowercase() == normalized {
                        return Err(crate::core::AgpmError::ManifestValidationError {
                            reason: format!(
                                "Case conflict: '{name}' and '{other_name}' would map to the same file on case-insensitive filesystems. To ensure portability across platforms, resource names must be case-insensitively unique."
                            ),
                        }
                        .into());
                    }
                }
            }
        }

        // Validate artifact types and resource type support
        for resource_type in crate::core::ResourceType::all() {
            if let Some(deps) = self.get_dependencies(*resource_type) {
                for (name, dep) in deps {
                    // Get tool from dependency (defaults to "claude-code")
                    let tool = match dep {
                        ResourceDependency::Detailed(d) => &d.tool,
                        ResourceDependency::Simple(_) => "claude-code", // Default for simple deps
                    };

                    // Check if tool is configured
                    if self.get_tool_config(tool).is_none() {
                        return Err(crate::core::AgpmError::ManifestValidationError {
                            reason: format!(
                                "Unknown tool '{tool}' for dependency '{name}'.\n\
                                Available types: {}\n\
                                Configure custom types in [tools] section or use a standard type.",
                                self.get_tools_config()
                                    .types
                                    .keys()
                                    .map(|s| format!("'{s}'"))
                                    .collect::<Vec<_>>()
                                    .join(", ")
                            ),
                        }
                        .into());
                    }

                    // Check if resource type is supported by this tool
                    if !self.is_resource_supported(tool, *resource_type) {
                        let artifact_config = self.get_tool_config(tool).unwrap();
                        let supported_types: Vec<String> =
                            artifact_config.resources.keys().map(|s| s.to_string()).collect();

                        // Build resource-type-specific suggestions
                        let mut suggestions = Vec::new();

                        match resource_type {
                            crate::core::ResourceType::Snippet => {
                                suggestions.push("Snippets work best with the 'agpm' tool (shared infrastructure)".to_string());
                                suggestions.push(
                                    "Add tool='agpm' to this dependency to use shared snippets"
                                        .to_string(),
                                );
                            }
                            _ => {
                                // Find which tool types DO support this resource type
                                let default_config = ToolsConfig::default();
                                let tools_config = self.tools.as_ref().unwrap_or(&default_config);
                                let resource_plural = resource_type.to_plural();
                                let supporting_types: Vec<String> = tools_config
                                    .types
                                    .iter()
                                    .filter(|(_, config)| {
                                        config.resources.contains_key(resource_plural)
                                    })
                                    .map(|(type_name, _)| format!("'{}'", type_name))
                                    .collect();

                                if !supporting_types.is_empty() {
                                    suggestions.push(format!(
                                        "This resource type is supported by tools: {}",
                                        supporting_types.join(", ")
                                    ));
                                }
                            }
                        }

                        let mut reason = format!(
                            "Resource type '{}' is not supported by tool '{}' for dependency '{}'.\n\n",
                            resource_type.to_plural(),
                            tool,
                            name
                        );

                        reason.push_str(&format!(
                            "Tool '{}' supports: {}\n\n",
                            tool,
                            supported_types.join(", ")
                        ));

                        if !suggestions.is_empty() {
                            reason.push_str("💡 Suggestions:\n");
                            for suggestion in &suggestions {
                                reason.push_str(&format!("{}\n", suggestion));
                            }
                            reason.push('\n');
                        }

                        reason.push_str(
                            "You can fix this by:\n\
                            1. Changing the 'tool' field to a supported tool\n\
                            2. Using a different resource type\n\
                            3. Removing this dependency from your manifest",
                        );

                        return Err(crate::core::AgpmError::ManifestValidationError {
                            reason,
                        }
                        .into());
                    }
                }
            }
        }

        Ok(())
    }

    /// Get all dependencies from both agents and snippets sections.
    ///
    /// Returns a vector of tuples containing dependency names and their
    /// specifications. This is useful for iteration over all dependencies
    /// without needing to handle agents and snippets separately.
    ///
    /// # Return Value
    ///
    /// Each tuple contains:
    /// - `&str`: The dependency name (key from TOML)
    /// - `&ResourceDependency`: The dependency specification
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::Manifest;
    ///
    /// let manifest = Manifest::new();
    /// // ... add some dependencies
    ///
    /// for (name, dep) in manifest.all_dependencies() {
    ///     println!("Dependency: {} -> {}", name, dep.get_path());
    ///     if let Some(source) = dep.get_source() {
    ///         println!("  Source: {}", source);
    ///     }
    /// }
    /// ```
    ///
    /// # Order
    ///
    /// Dependencies are returned in the order they appear in the underlying
    /// `HashMaps` (agents first, then snippets, then commands), which means the order is not
    /// guaranteed to be stable across runs.
    /// Get dependencies for a specific resource type
    ///
    /// Returns the `HashMap` of dependencies for the specified resource type.
    /// Note: MCP servers return None as they use a different dependency type.
    pub const fn get_dependencies(
        &self,
        resource_type: crate::core::ResourceType,
    ) -> Option<&HashMap<String, ResourceDependency>> {
        use crate::core::ResourceType;
        match resource_type {
            ResourceType::Agent => Some(&self.agents),
            ResourceType::Snippet => Some(&self.snippets),
            ResourceType::Command => Some(&self.commands),
            ResourceType::Script => Some(&self.scripts),
            ResourceType::Hook => Some(&self.hooks),
            ResourceType::McpServer => Some(&self.mcp_servers),
        }
    }

    /// Get the target directory for a specific resource type
    #[allow(deprecated)]
    pub fn get_target_dir(&self, resource_type: crate::core::ResourceType) -> &str {
        use crate::core::ResourceType;
        match resource_type {
            ResourceType::Agent => &self.target.agents,
            ResourceType::Snippet => &self.target.snippets,
            ResourceType::Command => &self.target.commands,
            ResourceType::Script => &self.target.scripts,
            ResourceType::Hook => &self.target.hooks,
            ResourceType::McpServer => &self.target.mcp_servers,
        }
    }

    /// Get the tools configuration, returning default if not specified.
    ///
    /// This method provides access to the tool configurations which define
    /// where resources are installed for different tools (claude-code, opencode, agpm).
    ///
    /// Returns the configured tools or the default configuration if not specified.
    pub fn get_tools_config(&self) -> &ToolsConfig {
        self.tools.as_ref().unwrap_or_else(|| {
            // Return a static default - this is safe because ToolsConfig::default() is deterministic
            static DEFAULT: std::sync::OnceLock<ToolsConfig> = std::sync::OnceLock::new();
            DEFAULT.get_or_init(ToolsConfig::default)
        })
    }

    /// Get configuration for a specific tool type.
    ///
    /// Returns None if the tool is not configured.
    pub fn get_tool_config(&self, tool: &str) -> Option<&ArtifactTypeConfig> {
        self.get_tools_config().types.get(tool)
    }

    /// Get the installation path for a resource within a tool.
    ///
    /// Returns the full installation directory path by combining:
    /// - Tool's base directory (e.g., ".claude", ".opencode")
    /// - Resource type's subdirectory (e.g., "agents", "command")
    ///
    /// Returns None if:
    /// - The tool is not configured
    /// - The resource type is not supported by this tool
    /// - The resource has no configured path (special handling like MCP merge)
    pub fn get_artifact_resource_path(
        &self,
        tool: &str,
        resource_type: crate::core::ResourceType,
    ) -> Option<std::path::PathBuf> {
        let artifact_config = self.get_tool_config(tool)?;
        let resource_config = artifact_config.resources.get(resource_type.to_plural())?;

        resource_config.path.as_ref().map(|subdir| artifact_config.path.join(subdir))
    }

    /// Check if a resource type is supported by a tool.
    ///
    /// Returns true if the tool has configuration for the given resource type.
    pub fn is_resource_supported(
        &self,
        tool: &str,
        resource_type: crate::core::ResourceType,
    ) -> bool {
        self.get_tool_config(tool)
            .and_then(|config| config.resources.get(resource_type.to_plural()))
            .is_some()
    }

    /// Returns all dependencies from all resource types.
    ///
    /// This method collects dependencies from agents, snippets, commands,
    /// scripts, hooks, and MCP servers into a single vector. It's commonly used for:
    /// - Manifest validation across all dependency types
    /// - Dependency resolution operations
    /// - Generating reports of all configured dependencies
    /// - Bulk operations on all dependencies
    ///
    /// # Returns
    ///
    /// A vector of tuples containing the dependency name and its configuration.
    /// Each tuple is `(name, dependency)` where:
    /// - `name`: The dependency name as specified in the manifest
    /// - `dependency`: Reference to the [`ResourceDependency`] configuration
    ///
    /// The order follows the resource type order defined in [`crate::core::ResourceType::all()`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use agpm_cli::manifest::Manifest;
    /// # let manifest = Manifest::new();
    /// for (name, dep) in manifest.all_dependencies() {
    ///     println!("Dependency: {} -> {}", name, dep.get_path());
    ///     if let Some(source) = dep.get_source() {
    ///         println!("  Source: {}", source);
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn all_dependencies(&self) -> Vec<(&str, &ResourceDependency)> {
        let mut deps = Vec::new();

        // Use ResourceType::all() to iterate through all resource types
        for resource_type in crate::core::ResourceType::all() {
            if let Some(type_deps) = self.get_dependencies(*resource_type) {
                for (name, dep) in type_deps {
                    deps.push((name.as_str(), dep));
                }
            }
        }

        deps
    }

    /// Get all dependencies including MCP servers.
    ///
    /// All resource types now use standard `ResourceDependency`, so no conversion needed.
    #[must_use]
    pub fn all_dependencies_with_mcp(
        &self,
    ) -> Vec<(&str, std::borrow::Cow<'_, ResourceDependency>)> {
        let mut deps = Vec::new();

        // Use ResourceType::all() to iterate through all resource types
        for resource_type in crate::core::ResourceType::all() {
            if let Some(type_deps) = self.get_dependencies(*resource_type) {
                for (name, dep) in type_deps {
                    deps.push((name.as_str(), std::borrow::Cow::Borrowed(dep)));
                }
            }
        }

        deps
    }

    /// Check if a dependency with the given name exists in any section.
    ///
    /// Searches the `[agents]`, `[snippets]`, and `[commands]` sections for a dependency
    /// with the specified name. This is useful for avoiding duplicate names
    /// across different resource types.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{Manifest, ResourceDependency};
    ///
    /// let mut manifest = Manifest::new();
    /// manifest.add_dependency(
    ///     "helper".to_string(),
    ///     ResourceDependency::Simple("../helper.md".to_string()),
    ///     true  // is_agent
    /// );
    ///
    /// assert!(manifest.has_dependency("helper"));
    /// assert!(!manifest.has_dependency("nonexistent"));
    /// ```
    ///
    /// # Performance
    ///
    /// This method performs two `HashMap` lookups, so it's O(1) on average.
    #[must_use]
    pub fn has_dependency(&self, name: &str) -> bool {
        self.agents.contains_key(name)
            || self.snippets.contains_key(name)
            || self.commands.contains_key(name)
    }

    /// Get a dependency by name from any section.
    ///
    /// Searches both the `[agents]` and `[snippets]` sections for a dependency
    /// with the specified name, returning the first match found. Agents are
    /// searched before snippets.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{Manifest, ResourceDependency};
    ///
    /// let mut manifest = Manifest::new();
    /// manifest.add_dependency(
    ///     "helper".to_string(),
    ///     ResourceDependency::Simple("../helper.md".to_string()),
    ///     true  // is_agent
    /// );
    ///
    /// if let Some(dep) = manifest.get_dependency("helper") {
    ///     println!("Found dependency: {}", dep.get_path());
    /// }
    /// ```
    ///
    /// # Search Order
    ///
    /// Dependencies are searched in this order:
    /// 1. `[agents]` section
    /// 2. `[snippets]` section
    /// 3. `[commands]` section
    ///
    /// If the same name exists in multiple sections, the first match is returned.
    #[must_use]
    pub fn get_dependency(&self, name: &str) -> Option<&ResourceDependency> {
        self.agents
            .get(name)
            .or_else(|| self.snippets.get(name))
            .or_else(|| self.commands.get(name))
    }

    /// Find a dependency by name from any section (alias for `get_dependency`).
    ///
    /// Searches the `[agents]`, `[snippets]`, and `[commands]` sections for a dependency
    /// with the specified name, returning the first match found.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{Manifest, ResourceDependency};
    ///
    /// let mut manifest = Manifest::new();
    /// manifest.add_dependency(
    ///     "helper".to_string(),
    ///     ResourceDependency::Simple("../helper.md".to_string()),
    ///     true  // is_agent
    /// );
    ///
    /// if let Some(dep) = manifest.find_dependency("helper") {
    ///     println!("Found dependency: {}", dep.get_path());
    /// }
    /// ```
    pub fn find_dependency(&self, name: &str) -> Option<&ResourceDependency> {
        self.get_dependency(name)
    }

    /// Add or update a source repository in the `[sources]` section.
    ///
    /// Sources map convenient names to Git repository URLs. These names can
    /// then be referenced in dependency specifications to avoid repeating
    /// long URLs throughout the manifest.
    ///
    /// # Parameters
    ///
    /// - `name`: Short, convenient name for the source (e.g., "official", "community")
    /// - `url`: Git repository URL (HTTPS, SSH, or file:// protocol)
    ///
    /// # URL Validation
    ///
    /// The URL is not validated when added - validation occurs during
    /// [`Self::validate`]. Supported URL formats:
    /// - `https://github.com/owner/repo.git`
    /// - `git@github.com:owner/repo.git`
    /// - `file:///absolute/path/to/repo`
    /// - `file:///path/to/local/repo`
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::Manifest;
    ///
    /// let mut manifest = Manifest::new();
    ///
    /// // Add public repository
    /// manifest.add_source(
    ///     "community".to_string(),
    ///     "https://github.com/claude-community/resources.git".to_string()
    /// );
    ///
    /// // Add private repository (SSH)
    /// manifest.add_source(
    ///     "private".to_string(),
    ///     "git@github.com:company/private-resources.git".to_string()
    /// );
    ///
    /// // Add local repository
    /// manifest.add_source(
    ///     "local".to_string(),
    ///     "file:///home/user/my-resources".to_string()
    /// );
    /// ```
    ///
    /// # Security Note
    ///
    /// Never include authentication tokens in the URL. Use SSH keys or
    /// configure authentication globally in `~/.agpm/config.toml`.
    pub fn add_source(&mut self, name: String, url: String) {
        self.sources.insert(name, url);
    }

    /// Add or update a dependency in the appropriate section.
    ///
    /// Adds the dependency to either the `[agents]`, `[snippets]`, or `[commands]` section
    /// based on the `is_agent` parameter. If a dependency with the same name
    /// already exists in the target section, it will be replaced.
    ///
    /// **Note**: This method is deprecated in favor of [`Self::add_typed_dependency`]
    /// which provides explicit control over resource types.
    ///
    /// # Parameters
    ///
    /// - `name`: Unique name for the dependency within its section
    /// - `dep`: The dependency specification (Simple or Detailed)
    /// - `is_agent`: If true, adds to `[agents]`; if false, adds to `[snippets]`
    ///   (Note: Use [`Self::add_typed_dependency`] for commands and other resource types)
    ///
    /// # Validation
    ///
    /// The dependency is not validated when added - validation occurs during
    /// [`Self::validate`]. This allows for building manifests incrementally
    /// before all sources are defined.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{Manifest, ResourceDependency, DetailedDependency};
    ///
    /// let mut manifest = Manifest::new();
    ///
    /// // Add local agent dependency
    /// manifest.add_dependency(
    ///     "helper".to_string(),
    ///     ResourceDependency::Simple("../local/helper.md".to_string()),
    ///     true  // is_agent = true
    /// );
    ///
    /// // Add remote snippet dependency
    /// manifest.add_dependency(
    ///     "utils".to_string(),
    ///     ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///         source: Some("community".to_string()),
    ///         path: "snippets/utils.md".to_string(),
    ///         version: Some("v1.0.0".to_string()),
    ///         branch: None,
    ///         rev: None,
    ///         command: None,
    ///         args: None,
    ///         target: None,
    ///         filename: None,
    ///         dependencies: None,
    ///         tool: "claude-code".to_string(),
    ///     })),
    ///     false  // is_agent = false (snippet)
    /// );
    /// ```
    ///
    /// # Name Conflicts
    ///
    /// This method allows the same dependency name to exist in both the
    /// `[agents]` and `[snippets]` sections. However, some operations like
    /// [`Self::get_dependency`] will prefer agents over snippets when
    /// searching by name.
    pub fn add_dependency(&mut self, name: String, dep: ResourceDependency, is_agent: bool) {
        if is_agent {
            self.agents.insert(name, dep);
        } else {
            self.snippets.insert(name, dep);
        }
    }

    /// Add or update a dependency with specific resource type.
    ///
    /// This is the preferred method for adding dependencies as it explicitly
    /// specifies the resource type using the `ResourceType` enum.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{Manifest, ResourceDependency};
    /// use agpm_cli::core::ResourceType;
    ///
    /// let mut manifest = Manifest::new();
    ///
    /// // Add command dependency
    /// manifest.add_typed_dependency(
    ///     "build".to_string(),
    ///     ResourceDependency::Simple("../commands/build.md".to_string()),
    ///     ResourceType::Command
    /// );
    /// ```
    pub fn add_typed_dependency(
        &mut self,
        name: String,
        dep: ResourceDependency,
        resource_type: crate::core::ResourceType,
    ) {
        match resource_type {
            crate::core::ResourceType::Agent => {
                self.agents.insert(name, dep);
            }
            crate::core::ResourceType::Snippet => {
                self.snippets.insert(name, dep);
            }
            crate::core::ResourceType::Command => {
                self.commands.insert(name, dep);
            }
            crate::core::ResourceType::McpServer => {
                // MCP servers don't use ResourceDependency, they have their own type
                // This method shouldn't be called for MCP servers
                panic!("Use add_mcp_server() for MCP server dependencies");
            }
            crate::core::ResourceType::Script => {
                self.scripts.insert(name, dep);
            }
            crate::core::ResourceType::Hook => {
                self.hooks.insert(name, dep);
            }
        }
    }

    /// Add or update an MCP server configuration.
    ///
    /// MCP servers now use standard `ResourceDependency` format,
    /// pointing to JSON configuration files in source repositories.
    ///
    /// # Examples
    ///
    /// ```rust,no_run,ignore
    /// use agpm_cli::manifest::{Manifest, ResourceDependency};
    ///
    /// let mut manifest = Manifest::new();
    ///
    /// // Add MCP server from source repository
    /// manifest.add_mcp_server(
    ///     "filesystem".to_string(),
    ///     ResourceDependency::Simple("../local/mcp-servers/filesystem.json".to_string())
    /// );
    /// ```
    pub fn add_mcp_server(&mut self, name: String, dependency: ResourceDependency) {
        self.mcp_servers.insert(name, dependency);
    }
}

impl ResourceDependency {
    /// Get the source repository name if this is a remote dependency.
    ///
    /// Returns the source name for remote dependencies (those that reference
    /// a Git repository), or `None` for local dependencies (those that reference
    /// local filesystem paths).
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Local dependency - no source
    /// let local = ResourceDependency::Simple("../local/file.md".to_string());
    /// assert!(local.get_source().is_none());
    ///
    /// // Remote dependency - has source
    /// let remote = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("official".to_string()),
    ///     path: "agents/tool.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert_eq!(remote.get_source(), Some("official"));
    /// ```
    ///
    /// # Use Cases
    ///
    /// This method is commonly used to:
    /// - Determine if dependency resolution should use Git vs filesystem
    /// - Validate that referenced sources exist in the manifest
    /// - Filter dependencies by type (local vs remote)
    /// - Generate dependency graphs and reports
    #[must_use]
    pub fn get_source(&self) -> Option<&str> {
        match self {
            Self::Simple(_) => None,
            Self::Detailed(d) => d.source.as_deref(),
        }
    }

    /// Get the custom target directory for this dependency.
    ///
    /// Returns the custom target directory if specified, or `None` if the
    /// dependency should use the default installation location for its resource type.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Dependency with custom target
    /// let custom = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("official".to_string()),
    ///     path: "agents/tool.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     target: Some("custom/tools".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert_eq!(custom.get_target(), Some("custom/tools"));
    ///
    /// // Dependency without custom target
    /// let default = ResourceDependency::Simple("../local/file.md".to_string());
    /// assert!(default.get_target().is_none());
    /// ```
    #[must_use]
    pub fn get_target(&self) -> Option<&str> {
        match self {
            Self::Simple(_) => None,
            Self::Detailed(d) => d.target.as_deref(),
        }
    }

    /// Get the custom filename for this dependency.
    ///
    /// Returns the custom filename if specified, or `None` if the
    /// dependency should use the default filename based on the dependency key.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Dependency with custom filename
    /// let custom = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("official".to_string()),
    ///     path: "agents/tool.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     filename: Some("ai-assistant.md".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert_eq!(custom.get_filename(), Some("ai-assistant.md"));
    ///
    /// // Dependency without custom filename
    /// let default = ResourceDependency::Simple("../local/file.md".to_string());
    /// assert!(default.get_filename().is_none());
    /// ```
    #[must_use]
    pub fn get_filename(&self) -> Option<&str> {
        match self {
            Self::Simple(_) => None,
            Self::Detailed(d) => d.filename.as_deref(),
        }
    }

    /// Get the path to the resource file.
    ///
    /// Returns the path component of the dependency, which is interpreted
    /// differently based on whether this is a local or remote dependency:
    ///
    /// - **Local dependencies**: Filesystem path relative to the manifest directory
    /// - **Remote dependencies**: Path within the Git repository
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Local dependency - filesystem path
    /// let local = ResourceDependency::Simple("../shared/helper.md".to_string());
    /// assert_eq!(local.get_path(), "../shared/helper.md");
    ///
    /// // Remote dependency - repository path
    /// let remote = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("official".to_string()),
    ///     path: "agents/code-reviewer.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert_eq!(remote.get_path(), "agents/code-reviewer.md");
    /// ```
    ///
    /// # Path Resolution
    ///
    /// The returned path should be processed appropriately based on the dependency type:
    /// - Local paths may need resolution against the manifest directory
    /// - Remote paths are used directly within the cloned repository
    /// - All paths should use forward slashes (/) for cross-platform compatibility
    #[must_use]
    pub fn get_path(&self) -> &str {
        match self {
            Self::Simple(path) => path,
            Self::Detailed(d) => &d.path,
        }
    }

    /// Check if this is a pattern-based dependency.
    ///
    /// Returns `true` if this dependency uses a glob pattern to match
    /// multiple resources, `false` if it specifies a single resource path.
    ///
    /// Patterns are detected by the presence of glob characters (`*`, `?`, `[`)
    /// in the path field.
    #[must_use]
    pub fn is_pattern(&self) -> bool {
        let path = self.get_path();
        path.contains('*') || path.contains('?') || path.contains('[')
    }

    /// Get the version constraint for dependency resolution.
    ///
    /// Returns the version constraint that should be used when resolving this
    /// dependency from a Git repository. For local dependencies, always returns `None`.
    ///
    /// # Priority Rules
    ///
    /// If both `version` and `git` fields are present in a detailed dependency,
    /// the `git` field takes precedence:
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("repo".to_string()),
    ///     path: "file.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),  // This is ignored
    ///     branch: Some("develop".to_string()),   // This takes precedence over version
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    ///
    /// assert_eq!(dep.get_version(), Some("develop"));
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Local dependency - no version
    /// let local = ResourceDependency::Simple("../local/file.md".to_string());
    /// assert!(local.get_version().is_none());
    ///
    /// // Remote dependency with version
    /// let versioned = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("repo".to_string()),
    ///     path: "file.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert_eq!(versioned.get_version(), Some("v1.0.0"));
    ///
    /// // Remote dependency with branch reference
    /// let branch_ref = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("repo".to_string()),
    ///     path: "file.md".to_string(),
    ///     version: None,
    ///     branch: Some("main".to_string()),
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert_eq!(branch_ref.get_version(), Some("main"));
    /// ```
    ///
    /// # Version Formats
    ///
    /// Supported version constraint formats include:
    /// - Semantic versions: `"v1.0.0"`, `"1.2.3"`
    /// - Semantic version ranges: `"^1.0.0"`, `"~2.1.0"`
    /// - Branch names: `"main"`, `"develop"`, `"latest"`, `"feature/new"`
    /// - Git tags: `"release-2023"`, `"stable"`
    /// - Commit SHAs: `"a1b2c3d4e5f6..."`
    #[must_use]
    pub fn get_version(&self) -> Option<&str> {
        match self {
            Self::Simple(_) => None,
            Self::Detailed(d) => {
                // Precedence: rev > branch > version
                d.rev.as_deref().or(d.branch.as_deref()).or(d.version.as_deref())
            }
        }
    }

    /// Check if this is a local filesystem dependency.
    ///
    /// Returns `true` if this dependency refers to a local file (no Git source),
    /// or `false` if it's a remote dependency that will be resolved from a
    /// Git repository.
    ///
    /// This is a convenience method equivalent to `self.get_source().is_none()`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Local dependency
    /// let local = ResourceDependency::Simple("../local/file.md".to_string());
    /// assert!(local.is_local());
    ///
    /// // Remote dependency
    /// let remote = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("official".to_string()),
    ///     path: "agents/tool.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert!(!remote.is_local());
    ///
    /// // Local detailed dependency (no source specified)
    /// let local_detailed = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: None,
    ///     path: "../shared/tool.md".to_string(),
    ///     version: None,
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "claude-code".to_string(),
    /// }));
    /// assert!(local_detailed.is_local());
    /// ```
    ///
    /// # Use Cases
    ///
    /// This method is useful for:
    /// - Choosing between filesystem and Git resolution strategies
    /// - Validation logic (local deps can't have versions)
    /// - Installation planning (local deps don't need caching)
    /// - Progress reporting (different steps for local vs remote)
    #[must_use]
    pub fn is_local(&self) -> bool {
        self.get_source().is_none()
    }

    /// Get the tool type for this dependency.
    ///
    /// Returns the target AI coding assistant tool for this resource. This determines where
    /// the resource will be installed (e.g., `.claude`, `.opencode`, `.agpm`).
    ///
    /// For simple dependencies, defaults to "claude-code".
    /// For detailed dependencies, returns the configured tool type.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use agpm_cli::manifest::{ResourceDependency, DetailedDependency};
    ///
    /// // Simple dependency - defaults to "claude-code"
    /// let simple = ResourceDependency::Simple("../local/file.md".to_string());
    /// assert_eq!(simple.get_tool(), "claude-code");
    ///
    /// // Detailed dependency with explicit tool
    /// let detailed = ResourceDependency::Detailed(Box::new(DetailedDependency {
    ///     source: Some("official".to_string()),
    ///     path: "agents/tool.md".to_string(),
    ///     version: Some("v1.0.0".to_string()),
    ///     branch: None,
    ///     rev: None,
    ///     command: None,
    ///     args: None,
    ///     target: None,
    ///     filename: None,
    ///     dependencies: None,
    ///     tool: "opencode".to_string(),
    /// }));
    /// assert_eq!(detailed.get_tool(), "opencode");
    /// ```
    #[must_use]
    pub fn get_tool(&self) -> &str {
        match self {
            Self::Simple(_) => "claude-code", // Default for simple deps
            Self::Detailed(d) => &d.tool,
        }
    }
}

impl Default for Manifest {
    fn default() -> Self {
        Self::new()
    }
}

/// Expand environment variables and home directory in URLs.
///
/// This function handles URL expansion for source repository specifications,
/// supporting environment variable substitution and home directory expansion
/// while preserving standard Git URL formats.
///
/// # Processing Rules
///
/// 1. **Standard Git URLs** are returned unchanged:
///    - `http://` and `https://` URLs
///    - SSH URLs starting with `git@`
///    - File URLs starting with `file://`
///
/// 2. **Local paths** with expansion markers are processed:
///    - Environment variables: `${VAR_NAME}` or `$VAR_NAME`
///    - Home directory: `~` at the start of the path
///    - Relative paths: `./` or `../`
///    - Absolute paths: starting with `/`
///
/// 3. **Converted to file:// URLs**: Local paths are converted to file:// URLs
///    for consistent handling throughout the system.
///
/// # Examples
///
/// ```rust,no_run,ignore
/// # use agpm_cli::manifest::expand_url;
/// # fn example() -> anyhow::Result<()> {
/// // Standard URLs remain unchanged
/// assert_eq!(expand_url("https://github.com/user/repo.git")?,
///            "https://github.com/user/repo.git");
/// assert_eq!(expand_url("git@github.com:user/repo.git")?,
///            "git@github.com:user/repo.git");
///
/// // Environment variable expansion (if HOME=/home/user)
/// std::env::set_var("REPOS_DIR", "/home/user/repositories");
/// assert_eq!(expand_url("${REPOS_DIR}/my-repo")?,
///            "file:///home/user/repositories/my-repo");
///
/// // Home directory expansion  
/// assert_eq!(expand_url("~/git/my-repo")?,
///            "file:///home/user/git/my-repo");
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling
///
/// - Returns the original URL if expansion fails
/// - Never panics, even with malformed input
/// - Allows validation to catch invalid URLs with proper error messages
///
/// # Security Considerations
///
/// - Environment variable expansion is limited to safe patterns
/// - Path traversal attempts in expanded paths are detected later in validation
/// - No execution of shell commands or arbitrary code
///
/// # Use Cases
///
/// This function enables flexible source specifications in manifests:
/// - CI/CD systems can inject repository URLs via environment variables
/// - Users can reference repositories relative to their home directory  
/// - Docker containers can use mounted paths with consistent URLs
/// - Development teams can share manifests without hardcoded paths
/// - Multi-platform projects can use consistent path references
///
/// # Thread Safety
///
/// This function is thread-safe and does not modify global state.
/// Environment variable access is read-only and atomic.
fn expand_url(url: &str) -> Result<String> {
    // If it looks like a standard protocol URL (http, https, git@, file://), don't expand
    if url.starts_with("http://")
        || url.starts_with("https://")
        || url.starts_with("git@")
        || url.starts_with("file://")
    {
        return Ok(url.to_string());
    }

    // Only try to expand if it looks like a local path (contains path separators, starts with ~, or contains env vars)
    if url.contains('/') || url.contains('\\') || url.starts_with('~') || url.contains('$') {
        // For cases that look like local paths, try to expand as a local path and convert to file:// URL
        match crate::utils::platform::resolve_path(url) {
            Ok(expanded_path) => {
                // Convert to file:// URL
                let path_str = expanded_path.to_string_lossy();
                if expanded_path.is_absolute() {
                    Ok(format!("file://{path_str}"))
                } else {
                    Ok(format!(
                        "file://{}",
                        std::env::current_dir()?.join(expanded_path).to_string_lossy()
                    ))
                }
            }
            Err(_) => {
                // If path expansion fails, return the original URL
                // This allows the validation to catch the error with a proper message
                Ok(url.to_string())
            }
        }
    } else {
        // For strings that don't look like paths, return as-is to let validation catch the error
        Ok(url.to_string())
    }
}

/// Find the manifest file by searching up the directory tree from the current directory.
///
/// This function implements the standard AGPM behavior of searching for a `agpm.toml`
/// file starting from the current working directory and walking up the directory
/// tree until one is found or the filesystem root is reached.
///
/// This behavior mirrors tools like Cargo, Git, and NPM that search for project
/// configuration files in parent directories.
///
/// # Search Algorithm
///
/// 1. Start from the current working directory
/// 2. Look for `agpm.toml` in the current directory
/// 3. If not found, move to the parent directory
/// 4. Repeat until found or reach the filesystem root
/// 5. Return error if no manifest is found
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::manifest::find_manifest;
///
/// // Find manifest from current directory
/// match find_manifest() {
///     Ok(path) => println!("Found manifest at: {}", path.display()),
///     Err(e) => println!("No manifest found: {}", e),
/// }
/// ```
///
/// # Directory Structure Example
///
/// ```text
/// /home/user/project/
/// ├── agpm.toml          ← Found here
/// └── subdir/
///     └── deep/
///         └── nested/     ← Search started here, walks up
/// ```
///
/// If called from `/home/user/project/subdir/deep/nested/`, this function
/// will find and return `/home/user/project/agpm.toml`.
///
/// # Error Conditions
///
/// - **No manifest found**: Searched to filesystem root without finding `agpm.toml`
/// - **Permission denied**: Cannot read current directory or traverse up
/// - **Filesystem corruption**: Cannot determine current working directory
///
/// # Use Cases
///
/// This function is typically called by CLI commands that need to locate the
/// project configuration, allowing users to run AGPM commands from any
/// subdirectory within their project.
pub fn find_manifest() -> Result<PathBuf> {
    let current = std::env::current_dir()
        .context("Cannot determine current working directory. This may indicate a permission issue or corrupted filesystem")?;
    find_manifest_from(current)
}

/// Find the manifest file, using an explicit path if provided.
///
/// This function provides a consistent way to locate the manifest file,
/// either using an explicitly provided path or by searching from the
/// current directory.
///
/// # Arguments
///
/// * `explicit_path` - Optional path to a manifest file. If provided and the file exists,
///   this path is returned. If provided but the file doesn't exist, an error is returned.
///
/// # Returns
///
/// The path to the manifest file.
///
/// # Errors
///
/// Returns an error if:
/// - An explicit path is provided but the file doesn't exist
/// - No explicit path is provided and no manifest is found via search
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::manifest::find_manifest_with_optional;
/// use std::path::PathBuf;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// // Use explicit path
/// let explicit = Some(PathBuf::from("/path/to/agpm.toml"));
/// let manifest = find_manifest_with_optional(explicit)?;
///
/// // Search from current directory
/// let manifest = find_manifest_with_optional(None)?;
/// # Ok(())
/// # }
/// ```
pub fn find_manifest_with_optional(explicit_path: Option<PathBuf>) -> Result<PathBuf> {
    match explicit_path {
        Some(path) => {
            if path.exists() {
                Ok(path)
            } else {
                Err(crate::core::AgpmError::ManifestNotFound.into())
            }
        }
        None => find_manifest(),
    }
}

/// Find the manifest file by searching up from a specific starting directory.
///
/// This is the core manifest discovery function that implements the directory
/// traversal logic. It's used internally by [`find_manifest`] and can also
/// be used when you need to search from a specific directory rather than
/// the current working directory.
///
/// # Algorithm
///
/// 1. Check if `agpm.toml` exists in the starting directory
/// 2. If found, return the full path to the manifest
/// 3. If not found, move to the parent directory
/// 4. Repeat until manifest is found or filesystem root is reached
/// 5. Return [`crate::core::AgpmError::ManifestNotFound`] if no manifest is found
///
/// # Parameters
///
/// - `current`: The starting directory for the search (consumed by the function)
///
/// # Examples
///
/// ```rust,no_run
/// use agpm_cli::manifest::find_manifest_from;
/// use std::path::PathBuf;
///
/// // Search from a specific directory
/// let start_dir = PathBuf::from("/home/user/project/subdir");
/// match find_manifest_from(start_dir) {
///     Ok(manifest_path) => {
///         println!("Found manifest: {}", manifest_path.display());
///     }
///     Err(e) => {
///         println!("No manifest found: {}", e);
///     }
/// }
/// ```
///
/// # Performance Considerations
///
/// - Each directory check involves a filesystem stat operation
/// - Search depth is limited by filesystem hierarchy (typically < 20 levels)
/// - Function returns immediately upon finding the first manifest
/// - No filesystem locks are held during the search
///
/// # Cross-Platform Behavior
///
/// - Works correctly on Windows, macOS, and Linux
/// - Handles filesystem roots appropriately (`/` on Unix, `C:\` on Windows)
/// - Respects platform-specific path separators and conventions
/// - Works with network filesystems and mounted volumes
///
/// # Error Handling
///
/// Returns [`crate::core::AgpmError::ManifestNotFound`] wrapped in an [`anyhow::Error`]
/// if no manifest file is found after searching to the filesystem root.
pub fn find_manifest_from(mut current: PathBuf) -> Result<PathBuf> {
    loop {
        let manifest_path = current.join("agpm.toml");
        if manifest_path.exists() {
            return Ok(manifest_path);
        }

        if !current.pop() {
            return Err(crate::core::AgpmError::ManifestNotFound.into());
        }
    }
}

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

    #[test]
    fn test_manifest_new() {
        let manifest = Manifest::new();
        assert!(manifest.sources.is_empty());
        assert!(manifest.agents.is_empty());
        assert!(manifest.snippets.is_empty());
        assert!(manifest.commands.is_empty());
        assert!(manifest.mcp_servers.is_empty());
    }

    #[test]
    fn test_manifest_load_save() {
        let temp = tempdir().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        let mut manifest = Manifest::new();
        manifest.add_source(
            "official".to_string(),
            "https://github.com/example-org/agpm-official.git".to_string(),
        );
        manifest.add_dependency(
            "test-agent".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("official".to_string()),
                path: "agents/test.md".to_string(),
                version: Some("v1.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
            true,
        );

        manifest.save(&manifest_path).unwrap();

        let loaded = Manifest::load(&manifest_path).unwrap();
        assert_eq!(loaded.sources.len(), 1);
        assert_eq!(loaded.agents.len(), 1);
        assert!(loaded.has_dependency("test-agent"));
    }

    #[test]
    fn test_manifest_validation() {
        let mut manifest = Manifest::new();

        // Add dependency without source - should be valid (local dependency)
        manifest.add_dependency(
            "local-agent".to_string(),
            ResourceDependency::Simple("../local/agent.md".to_string()),
            true,
        );
        assert!(manifest.validate().is_ok());

        // Add dependency with undefined source - should fail validation
        manifest.add_dependency(
            "remote-agent".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("undefined".to_string()),
                path: "agent.md".to_string(),
                version: Some("v1.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
            true,
        );
        assert!(manifest.validate().is_err());

        // Add the source - should now be valid
        manifest
            .add_source("undefined".to_string(), "https://github.com/test/repo.git".to_string());
        assert!(manifest.validate().is_ok());
    }

    #[test]
    fn test_dependency_helpers() {
        let simple_dep = ResourceDependency::Simple("path/to/file.md".to_string());
        assert_eq!(simple_dep.get_path(), "path/to/file.md");
        assert!(simple_dep.get_source().is_none());
        assert!(simple_dep.get_version().is_none());
        assert!(simple_dep.is_local());

        let detailed_dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/test.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: "claude-code".to_string(),
        }));
        assert_eq!(detailed_dep.get_path(), "agents/test.md");
        assert_eq!(detailed_dep.get_source(), Some("official"));
        assert_eq!(detailed_dep.get_version(), Some("v1.0.0"));
        assert!(!detailed_dep.is_local());
    }

    #[test]
    fn test_all_dependencies() {
        let mut manifest = Manifest::new();

        manifest.add_dependency(
            "agent1".to_string(),
            ResourceDependency::Simple("a1.md".to_string()),
            true,
        );
        manifest.add_dependency(
            "snippet1".to_string(),
            ResourceDependency::Simple("s1.md".to_string()),
            false,
        );

        let all_deps = manifest.all_dependencies();
        assert_eq!(all_deps.len(), 2);
    }

    #[test]
    fn test_source_url_validation() {
        let mut manifest = Manifest::new();

        // Valid URLs
        manifest.add_source("http".to_string(), "http://github.com/test/repo.git".to_string());
        manifest.add_source("https".to_string(), "https://github.com/test/repo.git".to_string());
        manifest.add_source("ssh".to_string(), "git@github.com:test/repo.git".to_string());
        assert!(manifest.validate().is_ok());

        // Invalid URL
        manifest.add_source("invalid".to_string(), "not-a-url".to_string());
        let result = manifest.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("invalid URL"));
    }

    #[test]
    fn test_manifest_commands() {
        let mut manifest = Manifest::new();

        // Add a command dependency
        manifest.add_typed_dependency(
            "build-command".to_string(),
            ResourceDependency::Simple("commands/build.md".to_string()),
            crate::core::ResourceType::Command,
        );

        assert!(manifest.commands.contains_key("build-command"));
        assert_eq!(manifest.commands.len(), 1);
        assert!(manifest.has_dependency("build-command"));

        // Test get_dependency returns command
        let dep = manifest.get_dependency("build-command");
        assert!(dep.is_some());
        assert_eq!(dep.unwrap().get_path(), "commands/build.md");
    }

    #[test]
    fn test_manifest_all_dependencies_with_commands() {
        let mut manifest = Manifest::new();

        manifest.add_typed_dependency(
            "agent1".to_string(),
            ResourceDependency::Simple("a1.md".to_string()),
            crate::core::ResourceType::Agent,
        );
        manifest.add_typed_dependency(
            "snippet1".to_string(),
            ResourceDependency::Simple("s1.md".to_string()),
            crate::core::ResourceType::Snippet,
        );
        manifest.add_typed_dependency(
            "command1".to_string(),
            ResourceDependency::Simple("c1.md".to_string()),
            crate::core::ResourceType::Command,
        );

        let all_deps = manifest.all_dependencies();
        assert_eq!(all_deps.len(), 3);

        // Verify all three types are present
        assert!(manifest.agents.contains_key("agent1"));
        assert!(manifest.snippets.contains_key("snippet1"));
        assert!(manifest.commands.contains_key("command1"));
    }

    #[test]
    fn test_manifest_save_load_commands() {
        let temp = tempdir().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        let mut manifest = Manifest::new();
        manifest.add_source(
            "community".to_string(),
            "https://github.com/example/community.git".to_string(),
        );
        manifest.add_typed_dependency(
            "deploy".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("community".to_string()),
                path: "commands/deploy.md".to_string(),
                version: Some("v2.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
            crate::core::ResourceType::Command,
        );

        // Save and reload
        manifest.save(&manifest_path).unwrap();
        let loaded = Manifest::load(&manifest_path).unwrap();

        assert_eq!(loaded.commands.len(), 1);
        assert!(loaded.commands.contains_key("deploy"));
        assert!(loaded.has_dependency("deploy"));

        let dep = loaded.get_dependency("deploy").unwrap();
        assert_eq!(dep.get_path(), "commands/deploy.md");
        assert_eq!(dep.get_version(), Some("v2.0.0"));
    }

    #[test]
    #[allow(deprecated)]
    fn test_target_config_commands_dir() {
        let config = TargetConfig::default();
        assert_eq!(config.commands, ".claude/commands");

        // Test custom config
        let mut manifest = Manifest::new();
        manifest.target.commands = "custom/commands".to_string();
        assert_eq!(manifest.target.commands, "custom/commands");
    }

    #[test]
    fn test_mcp_servers() {
        let mut manifest = Manifest::new();

        // Add an MCP server (now using standard ResourceDependency)
        manifest.add_mcp_server(
            "test-server".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("npm".to_string()),
                path: "mcp-servers/test-server.json".to_string(),
                version: Some("latest".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
        );

        assert_eq!(manifest.mcp_servers.len(), 1);
        assert!(manifest.mcp_servers.contains_key("test-server"));

        let server = &manifest.mcp_servers["test-server"];
        assert_eq!(server.get_source(), Some("npm"));
        assert_eq!(server.get_path(), "mcp-servers/test-server.json");
        assert_eq!(server.get_version(), Some("latest"));
    }

    #[test]
    fn test_manifest_save_load_mcp_servers() {
        let temp = tempdir().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        let mut manifest = Manifest::new();
        manifest.add_source("npm".to_string(), "https://registry.npmjs.org".to_string());
        manifest.add_mcp_server(
            "postgres".to_string(),
            ResourceDependency::Simple("../local/mcp-servers/postgres.json".to_string()),
        );

        // Save and reload
        manifest.save(&manifest_path).unwrap();
        let loaded = Manifest::load(&manifest_path).unwrap();

        assert_eq!(loaded.mcp_servers.len(), 1);
        assert!(loaded.mcp_servers.contains_key("postgres"));

        let server = &loaded.mcp_servers["postgres"];
        assert_eq!(server.get_path(), "../local/mcp-servers/postgres.json");
    }

    #[test]
    #[allow(deprecated)]
    fn test_target_config_mcp_servers_dir() {
        let config = TargetConfig::default();
        assert_eq!(config.mcp_servers, ".claude/agpm/mcp-servers");

        // Test custom config
        let mut manifest = Manifest::new();
        manifest.target.mcp_servers = "custom/mcp".to_string();
        assert_eq!(manifest.target.mcp_servers, "custom/mcp");
    }

    #[test]
    fn test_dependency_with_custom_target() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/tool.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: Some("custom/tools".to_string()),
            filename: None,
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        assert_eq!(dep.get_target(), Some("custom/tools"));
        assert_eq!(dep.get_source(), Some("official"));
        assert_eq!(dep.get_path(), "agents/tool.md");
    }

    #[test]
    fn test_dependency_without_custom_target() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/tool.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        assert!(dep.get_target().is_none());
    }

    #[test]
    fn test_simple_dependency_no_custom_target() {
        let dep = ResourceDependency::Simple("../local/file.md".to_string());
        assert!(dep.get_target().is_none());
    }

    #[test]
    fn test_save_load_dependency_with_custom_target() {
        let temp = tempdir().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        let mut manifest = Manifest::new();
        manifest.add_source(
            "official".to_string(),
            "https://github.com/example/official.git".to_string(),
        );

        // Add dependency with custom target
        manifest.add_typed_dependency(
            "special-agent".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("official".to_string()),
                path: "agents/special.md".to_string(),
                version: Some("v1.0.0".to_string()),
                target: Some("integrations/ai".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
            crate::core::ResourceType::Agent,
        );

        // Save and reload
        manifest.save(&manifest_path).unwrap();
        let loaded = Manifest::load(&manifest_path).unwrap();

        assert_eq!(loaded.agents.len(), 1);
        assert!(loaded.agents.contains_key("special-agent"));

        let dep = loaded.get_dependency("special-agent").unwrap();
        assert_eq!(dep.get_target(), Some("integrations/ai"));
        assert_eq!(dep.get_path(), "agents/special.md");
    }

    #[test]
    fn test_dependency_with_custom_filename() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/tool.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: Some("ai-assistant.md".to_string()),
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        assert_eq!(dep.get_filename(), Some("ai-assistant.md"));
        assert_eq!(dep.get_source(), Some("official"));
        assert_eq!(dep.get_path(), "agents/tool.md");
    }

    #[test]
    fn test_dependency_without_custom_filename() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/tool.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        assert!(dep.get_filename().is_none());
    }

    #[test]
    fn test_simple_dependency_no_custom_filename() {
        let dep = ResourceDependency::Simple("../local/file.md".to_string());
        assert!(dep.get_filename().is_none());
    }

    #[test]
    fn test_save_load_dependency_with_custom_filename() {
        let temp = tempdir().unwrap();
        let manifest_path = temp.path().join("agpm.toml");

        let mut manifest = Manifest::new();
        manifest.add_source(
            "official".to_string(),
            "https://github.com/example/official.git".to_string(),
        );

        // Add dependency with custom filename
        manifest.add_typed_dependency(
            "my-agent".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("official".to_string()),
                path: "agents/complex-name.md".to_string(),
                version: Some("v1.0.0".to_string()),
                target: None,
                filename: Some("simple-name.txt".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
            crate::core::ResourceType::Agent,
        );

        // Save and reload
        manifest.save(&manifest_path).unwrap();
        let loaded = Manifest::load(&manifest_path).unwrap();

        assert_eq!(loaded.agents.len(), 1);
        assert!(loaded.agents.contains_key("my-agent"));

        let dep = loaded.get_dependency("my-agent").unwrap();
        assert_eq!(dep.get_filename(), Some("simple-name.txt"));
        assert_eq!(dep.get_path(), "agents/complex-name.md");
    }

    #[test]
    fn test_pattern_dependency() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("repo".to_string()),
            path: "agents/**/*.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: None,
            filename: None,
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        assert!(dep.is_pattern());
        assert_eq!(dep.get_path(), "agents/**/*.md");
        assert!(!dep.is_local());
    }

    #[test]
    fn test_pattern_dependency_validation() {
        let mut manifest = Manifest::new();
        manifest
            .sources
            .insert("repo".to_string(), "https://github.com/example/repo.git".to_string());

        // Valid pattern dependency (uses glob characters in path)
        manifest.agents.insert(
            "ai-agents".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("repo".to_string()),
                path: "agents/ai/*.md".to_string(),
                version: Some("v1.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
        );

        assert!(manifest.validate().is_ok());

        // Valid: regular dependency (no glob characters)
        manifest.agents.insert(
            "regular".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("repo".to_string()),
                path: "agents/test.md".to_string(),
                version: Some("v1.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
        );

        let result = manifest.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_pattern_dependency_with_path_traversal() {
        let mut manifest = Manifest::new();
        manifest
            .sources
            .insert("repo".to_string(), "https://github.com/example/repo.git".to_string());

        // Pattern with path traversal (using path field now)
        manifest.agents.insert(
            "unsafe".to_string(),
            ResourceDependency::Detailed(Box::new(DetailedDependency {
                source: Some("repo".to_string()),
                path: "../../../etc/*.conf".to_string(),
                version: Some("v1.0.0".to_string()),
                branch: None,
                rev: None,
                command: None,
                args: None,
                target: None,
                filename: None,
                dependencies: None,
                tool: "claude-code".to_string(),
            })),
        );

        let result = manifest.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("Invalid pattern"));
    }

    #[test]
    fn test_dependency_with_both_target_and_filename() {
        let dep = ResourceDependency::Detailed(Box::new(DetailedDependency {
            source: Some("official".to_string()),
            path: "agents/tool.md".to_string(),
            version: Some("v1.0.0".to_string()),
            branch: None,
            rev: None,
            command: None,
            args: None,
            target: Some("tools/ai".to_string()),
            filename: Some("assistant.markdown".to_string()),
            dependencies: None,
            tool: "claude-code".to_string(),
        }));

        assert_eq!(dep.get_target(), Some("tools/ai"));
        assert_eq!(dep.get_filename(), Some("assistant.markdown"));
    }
}

#[cfg(test)]
mod tool_tests {
    use super::*;

    #[test]
    fn test_detailed_dependency_tool_parsing() {
        let toml_str = r#"
[agents]
opencode-helper = { source = "test_repo", path = "agents/helper.md", version = "v1.0.0", tool = "opencode" }
"#;

        let manifest: Manifest = toml::from_str(toml_str).unwrap();

        let helper = manifest.agents.get("opencode-helper").unwrap();

        match helper {
            ResourceDependency::Detailed(d) => {
                assert_eq!(d.tool, "opencode", "tool should be 'opencode'");
            }
            _ => panic!("Expected Detailed dependency"),
        }
    }

    #[test]
    fn test_tool_name_validation() {
        // Test that artifact type names with path separators are rejected
        let toml_with_slash = r#"
[sources]
test = "https://example.com/repo.git"

[tools."bad/name"]
path = ".claude"

[tools."bad/name".resources.agents]
path = "agents"

[agents]
test = { source = "test", path = "agents/test.md", type = "bad/name" }
"#;

        let manifest: Result<Manifest, _> = toml::from_str(toml_with_slash);
        assert!(manifest.is_ok(), "Manifest should parse (validation happens in validate())");
        let manifest = manifest.unwrap();
        let result = manifest.validate();
        assert!(result.is_err(), "Validation should fail for artifact type with forward slash");
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("cannot contain path separators"),
            "Error should mention path separators, got: {}",
            err
        );

        // Test backslash
        let toml_with_backslash = r#"
[sources]
test = "https://example.com/repo.git"

[tools."bad\\name"]
path = ".claude"

[tools."bad\\name".resources.agents]
path = "agents"

[agents]
test = { source = "test", path = "agents/test.md", type = "bad\\name" }
"#;

        let manifest: Result<Manifest, _> = toml::from_str(toml_with_backslash);
        assert!(manifest.is_ok(), "Manifest should parse (validation happens in validate())");
        let manifest = manifest.unwrap();
        let result = manifest.validate();
        assert!(result.is_err(), "Validation should fail for artifact type with backslash");

        // Test path traversal (..)
        let toml_with_dotdot = r#"
[sources]
test = "https://example.com/repo.git"

[tools."bad..name"]
path = ".claude"

[tools."bad..name".resources.agents]
path = "agents"

[agents]
test = { source = "test", path = "agents/test.md", type = "bad..name" }
"#;

        let manifest: Result<Manifest, _> = toml::from_str(toml_with_dotdot);
        assert!(manifest.is_ok(), "Manifest should parse (validation happens in validate())");
        let manifest = manifest.unwrap();
        let result = manifest.validate();
        assert!(result.is_err(), "Validation should fail for artifact type with ..");
        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("cannot contain '..'"),
            "Error should mention path traversal, got: {}",
            err
        );

        // Test valid tool type names work
        let toml_valid = r#"
[sources]
test = "https://example.com/repo.git"

[tools."my-custom-type"]
path = ".custom"

[tools."my-custom-type".resources.agents]
path = "agents"

[agents]
test = { source = "test", path = "agents/test.md", version = "v1.0.0", tool = "my-custom-type" }
"#;

        let manifest: Result<Manifest, _> = toml::from_str(toml_valid);
        assert!(manifest.is_ok(), "Valid manifest should parse");
        let manifest = manifest.unwrap();
        let result = manifest.validate();
        assert!(result.is_ok(), "Valid artifact type name should pass validation");
    }
}