mind-cli 0.11.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
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
//! Scanning melded sources for installable items.
//!
//! By convention (mirrors the `agents` repo layout):
//! - `skills/<name>/SKILL.md`  -> skill `<name>`
//! - `agents/<name>.md`        -> agent `<name>`
//! - `rules/<name>.md`         -> rule  `<name>`
//!
//! A source may instead ship a `mind.toml` (see [`crate::mindfile`]) declaring
//! its inventory explicitly via `[[items]]` or `[discover]` globs; that takes
//! over discovery for the source. Either way, an item's `description` is read
//! from its frontmatter unless overridden.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

use crate::error::{ItemKind, MindError, Result};
use crate::frontmatter;
use crate::mindfile::{Discover, HookEvent, ItemDecl, KindGlobs, MindToml, ResolvedHook};
use crate::namespace;
use crate::paths::Paths;
use crate::plugin_manifest;
use crate::source::{Registry, Source};

/// One installable item discovered in a source.
///
/// The catalog is source truth: `name` is the item's *bare* name exactly as it
/// appears in the repo. The namespace prefix and `{{ns:}}` token expansion are
/// install-time transforms, applied by `install.rs`, not baked in here. The
/// stable identity of an item is therefore `(source, kind, name)`, which is what
/// `upgrade` matches on across a prefix change.
#[derive(Debug, Clone)]
pub struct CatalogItem {
    pub kind: ItemKind,
    /// Bare name as it appears in the source.
    pub name: String,
    /// The source `name` it belongs to.
    pub source: String,
    /// The source's effective namespace prefix, if any (applied at install).
    pub prefix: Option<String>,
    /// Path to the item root on disk (a dir for skills, a file for agents/rules).
    pub path: PathBuf,
    /// One-line description, from frontmatter or a `mind.toml` override.
    pub description: Option<String>,
    /// Optional link target relative to `~/.claude` (from `mind.toml`); `None`
    /// means use the default location for the kind.
    pub link_rel: Option<String>,
    /// A tool's entrypoint, relative to the item dir (from `TOOL.md` frontmatter
    /// or a `mind.toml` override). What `{{tools:name}}` resolves to. Tools only.
    pub bin: Option<String>,
    /// A per-item build command run in staging at install (from `TOOL.md`
    /// frontmatter or a `mind.toml` override). `None` means no build step.
    pub build: Option<String>,
    /// An item install hook (HOOK-80): a host side-effect command run as the
    /// final install step (from a `mind.toml` `[[items]].install` on any kind,
    /// or a tool's `TOOL.md` `install:` frontmatter). `None` means none.
    pub install: Option<String>,
    /// An item uninstall hook (HOOK-80): a host cleanup command run when the item
    /// is removed (from a `mind.toml` `[[items]].uninstall` on any kind, or a
    /// tool's `TOOL.md` `uninstall:` frontmatter). `None` means none.
    pub uninstall: Option<String>,
    /// Explicit intra-source dependency refs declared in the item's frontmatter
    /// `requires:` key (DEP-4). Whitespace-split raw strings as written, e.g.
    /// `["skill:x", "agent:y"]`. Empty when absent.
    pub requires: Vec<String>,
    /// The item's full resolved lifecycle hooks (HOOK-86), in execution order:
    /// the scalar `install`/`uninstall` shorthand folded in ahead of any
    /// `[[items.hooks]]` array entries. The scalar fields above stay populated
    /// alongside this list (HOOK-85 disclosure reads them); this list is what the
    /// install/uninstall execution iterates. A `TOOL.md`-frontmatter item has
    /// only its scalars folded in (DSC-21: the array form requires `mind.toml`).
    pub hooks: Vec<ResolvedHook>,
}

impl CatalogItem {
    /// The name this item installs under: bare, or `<prefix>:<bare>` if namespaced.
    pub fn effective_name(&self) -> String {
        namespace::apply(&self.name, &self.prefix)
    }

    /// The harness-visible name for an agent: the frontmatter `name:` field when
    /// it is non-empty and a safe single path component, else the bare catalog
    /// name (`self.name`). Returns `None` for non-agent kinds.
    ///
    /// The Claude harness keys an agent by its frontmatter `name`, not its
    /// filename, so this is the name mind links the agent under in each agent
    /// home (NS-40).
    pub fn agent_harness_name(&self) -> Option<String> {
        // spec: NS-40
        if self.kind != ItemKind::Agent {
            return None;
        }
        if let Some(fm_name) = frontmatter::file_field(&self.path, "name") {
            let trimmed = fm_name.trim().to_string();
            if !trimmed.is_empty() && is_safe_item_name(&trimmed) {
                return Some(trimmed);
            }
        }
        // Fall back to the bare catalog name (file stem).
        Some(self.name.clone())
    }

    /// A tool's entrypoint relative to its dir, for `{{tools:name}}`: the
    /// declared `bin`, else the convention default `<name>` (a file named after
    /// the tool at the dir root) when that file is present in the source. `None`
    /// for non-tools or a tool with no resolvable entrypoint.
    pub fn resolved_bin(&self) -> Option<String> {
        if self.kind != ItemKind::Tool {
            return None;
        }
        if let Some(bin) = &self.bin {
            return Some(bin.clone());
        }
        self.path
            .join(&self.name)
            .is_file()
            .then(|| self.name.clone())
    }

    /// This item's resolved install hooks (HOOK-86), in execution order.
    pub fn install_hooks(&self) -> Vec<&ResolvedHook> {
        self.hooks
            .iter()
            .filter(|h| h.event == HookEvent::Install)
            .collect()
    }

    /// This item's resolved uninstall hooks (HOOK-86), in execution order.
    pub fn uninstall_hooks(&self) -> Vec<&ResolvedHook> {
        self.hooks
            .iter()
            .filter(|h| h.event == HookEvent::Uninstall)
            .collect()
    }

    /// User-facing key, using the effective (possibly prefixed) name.
    pub fn key(&self) -> String {
        format!("{}:{}", self.kind.as_str(), self.effective_name())
    }

    /// This item as a path-token resolution sibling (namespace.rs), carrying its
    /// kind, bare name, and resolved `bin`. `PathSibling` exists so `namespace`
    /// need not depend on `catalog`; this is the one place the mapping lives.
    pub fn as_path_sibling(&self) -> namespace::PathSibling {
        namespace::PathSibling {
            kind: self.kind,
            name: self.name.clone(),
            bin: self.resolved_bin(),
        }
    }
}

/// True when `query` matches the item by effective name or description,
/// case-insensitively. An empty query matches everything. (spec: CLI-85)
pub(crate) fn matches_query(item: &CatalogItem, query: &str) -> bool {
    if query.is_empty() {
        return true;
    }
    let q = query.to_lowercase();
    if item.effective_name().to_lowercase().contains(&q) {
        return true;
    }
    item.description
        .as_deref()
        .is_some_and(|d| d.to_lowercase().contains(&q))
}

/// Scan every melded source for installable items.
pub fn scan(paths: &Paths, registry: &Registry) -> Result<Vec<CatalogItem>> {
    let mut items = Vec::new();
    for source in &registry.sources {
        scan_source(paths, source, &mut items)?;
    }
    Ok(items)
}

pub(crate) fn scan_source(
    paths: &Paths,
    source: &Source,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    let clone_root = source.clone_dir(paths);
    scan_source_at(clone_root, source, out)
}

/// Scan a source whose clone root is known directly (e.g. for `review`, where
/// the directory may not live under the standard sources tree).
pub(crate) fn scan_source_at(
    clone_root: impl AsRef<std::path::Path>,
    source: &Source,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    let clone_root = clone_root.as_ref();
    let mindfile = MindToml::load(clone_root)?;

    // Reject a source that requires a newer `mind` than the one running, rather
    // than scanning it against a format this version may predate (DSC-40).
    if let Some(required) = mindfile
        .as_ref()
        .and_then(|m| m.source.min_mind_version.as_deref())
        && !crate::mindfile::version_at_least(env!("CARGO_PKG_VERSION"), required)
    {
        return Err(MindError::IncompatibleVersion {
            source_name: source.name.clone(),
            required: required.to_string(),
            running: env!("CARGO_PKG_VERSION").to_string(),
        });
    }

    // Effective prefix: consumer alias wins over the repo's own declaration. An
    // empty alias (`--as ''`, or the meld prompt's "no prefix" choice) is the
    // explicit "no prefix" override and suppresses a declared `[source].prefix`.
    // No NS-25 guard is needed here: both inputs are validated upstream where they
    // are set (the `--as` alias in commands.rs, the `[source].prefix` at mindfile
    // load), so a reserved-kind-word prefix can never reach this resolution.
    let prefix = source
        .alias
        .clone()
        .or_else(|| mindfile.as_ref().and_then(|m| m.source.prefix.clone()))
        .filter(|p| !p.is_empty());

    match mindfile {
        Some(mt) if mt.is_authoritative() => {
            // spec: DSC-52 — authoritative mind.toml ignores scan roots entirely;
            // its paths are always repo-root-relative.
            // spec: DSC-53 — (kind, bare_name) uniqueness applies to [[items]]
            // declarations: two entries with the same kind+name are a DuplicateItem.
            let mut seen: std::collections::HashSet<(crate::error::ItemKind, String)> =
                std::collections::HashSet::new();
            for decl in &mt.items {
                let item = from_decl(clone_root, source, &prefix, decl)?;
                let key = (item.kind, item.name.clone());
                if !seen.insert(key.clone()) {
                    return Err(MindError::DuplicateItem {
                        source_name: source.name.clone(),
                        kind: key.0,
                        name: key.1,
                    });
                }
                out.push(item);
            }
            if let Some(discover) = &mt.discover {
                scan_globs(clone_root, source, &prefix, discover, out)?;
            }
            Ok(())
        }
        ref mt => {
            // MKT-1/MKT-2: Single-plugin discovery layer.
            //
            // Check for `.claude-plugin/plugin.json` at the clone root BEFORE
            // falling back to convention discovery. When present, the plugin manifest
            // is the authoritative item source and convention discovery is skipped
            // (MKT-2). A `.claude-plugin/marketplace.json` (catalog super-source) is
            // handled by commands.rs at meld time (shard 4) for external entries;
            // in-repo entries are scanned directly here (MKT-14).
            //
            // This branch is only reached when mind.toml is absent or `[source]`-only
            // (non-authoritative). An authoritative mind.toml suppresses the plugin
            // manifest -- that is handled in the `Some(mt) if mt.is_authoritative()`
            // arm above. The "found and ignored" NOTE for that case is
            // commands.rs's responsibility (shard 4); catalog stays quiet (MKT-2).
            if let Some(plugin_path) = plugin_manifest::find_plugin_manifest(clone_root) {
                // Load the plugin manifest; a parse error propagates as MindToml (MKT-9).
                let manifest = plugin_manifest::load_plugin_manifest(&plugin_path)?;

                // Effective prefix (MKT-5): alias > mind.toml [source].prefix > plugin name.
                // The `prefix` variable above already resolved alias and mindfile prefix.
                // If it is still `None` AND no explicit override was declared, use the
                // plugin name as the default prefix. An explicitly-empty alias or mindfile
                // prefix suppresses the plugin-name fallback (user intentionally cleared it).
                let plugin_prefix = if source.alias.is_some()
                    || mt.as_ref().and_then(|m| m.source.prefix.as_ref()).is_some()
                {
                    // A prefix was explicitly set (possibly to "" = cleared). Respect it.
                    prefix.clone()
                } else {
                    // No explicit prefix; try the plugin name as the default (MKT-5).
                    let plugin_name = manifest.name.trim().to_string();
                    // Resilience (NS-25): if the plugin name is a reserved kind word
                    // (e.g. "skill", "agent"), do NOT use it as a prefix. Prefer
                    // silently falling through to no prefix over making the whole source
                    // un-meldable -- a plugin you don't control should not block install.
                    match namespace::validate_prefix(&plugin_name) {
                        Ok(()) if !plugin_name.is_empty() => Some(plugin_name),
                        _ => None,
                    }
                };

                // MKT-3: map skills/<n>/SKILL.md -> Skill, agents/<n>.md -> Agent.
                // Flat-skills and [source].roots knobs do NOT apply to a plugin.
                scan_plugin_components(clone_root, source, &plugin_prefix, out)?;

                // MKT-6/DSC-32: The plugin-level `description` describes the source
                // (not each item); recording it on the Source is commands.rs's job
                // (shard 4). Per-item descriptions continue to come from frontmatter.

                return Ok(());
            }

            // MKT-14: Check for a marketplace.json AFTER plugin.json (plugin.json wins
            // if both are present) and BEFORE the convention fallback. In-repo entries
            // are scanned as roots within this repo; external entries are skipped here
            // (they are sub-melded by commands.rs). The marketplace is authoritative:
            // when found, convention discovery is skipped.
            if let Some(marketplace_path) = plugin_manifest::find_marketplace_manifest(clone_root) {
                let manifest = plugin_manifest::load_marketplace_manifest(&marketplace_path)?;
                // Detect whether the consumer set an explicit prefix override (even ""
                // to clear it). Used to distinguish "no override → use entry name as
                // the default prefix" from "override set → respect it".
                let has_explicit_prefix = source.alias.is_some()
                    || mt.as_ref().and_then(|m| m.source.prefix.as_ref()).is_some();
                scan_marketplace_in_repo_plugins(
                    clone_root,
                    source,
                    manifest,
                    &prefix,
                    has_explicit_prefix,
                    out,
                )?;
                return Ok(()); // marketplace is authoritative (MKT-2 / MKT-14)
            }

            // No plugin manifest found; fall through to the existing convention scan.

            // spec: DSC-50 / DSC-51 — resolve the effective scan roots:
            //   source.roots (--root override) wins; else mindfile [source].roots;
            //   else implicit single root of the repo root.
            let effective_roots: Vec<String> = source
                .roots
                .clone()
                .or_else(|| mt.as_ref().and_then(|m| m.source.roots.clone()))
                .unwrap_or_else(|| vec![".".to_string()]);

            // Validate each root: must exist as a directory inside the clone and
            // must not be absolute or escape the clone via `..`.
            for r in &effective_roots {
                if std::path::Path::new(r).is_absolute() {
                    return Err(MindError::InvalidRoot {
                        source_name: source.name.clone(),
                        root: r.clone(),
                    });
                }
                let full = clone_root.join(r);
                // Reject paths that try to escape via `..`.
                if !full
                    .canonicalize()
                    .unwrap_or_else(|_| full.clone())
                    .starts_with(
                        clone_root
                            .canonicalize()
                            .unwrap_or_else(|_| clone_root.to_path_buf()),
                    )
                {
                    return Err(MindError::InvalidRoot {
                        source_name: source.name.clone(),
                        root: r.clone(),
                    });
                }
                if !full.is_dir() {
                    return Err(MindError::InvalidRoot {
                        source_name: source.name.clone(),
                        root: r.clone(),
                    });
                }
            }

            // spec: DSC-74 — resolve the effective flat-skills setting: the
            // consumer `--flat-skills` override (STO-44) wins; else the source's
            // own `[source].flat-skills`; else false (the DSC-10 container layout).
            let flat_skills =
                source.flat_skills || mt.as_ref().map(|m| m.source.flat_skills).unwrap_or(false);

            // spec: DSC-53 — scan each root and union the results. Detect a
            // (kind, bare_name) collision within this source.
            let pre_scan_len = out.len();
            for r in &effective_roots {
                let scan_root = clone_root.join(r);
                scan_convention(&scan_root, source, &prefix, flat_skills, out)?;
            }
            // Check for duplicates among items contributed by this source.
            let new_items = &out[pre_scan_len..];
            let mut seen: std::collections::HashSet<(crate::error::ItemKind, String)> =
                std::collections::HashSet::new();
            for item in new_items {
                let key = (item.kind, item.name.clone());
                if !seen.insert(key.clone()) {
                    return Err(MindError::DuplicateItem {
                        source_name: source.name.clone(),
                        kind: key.0,
                        name: key.1,
                    });
                }
            }
            Ok(())
        }
    }
}

/// Build a catalog item from an explicit `[[items]]` declaration.
fn from_decl(
    root: &Path,
    source: &Source,
    prefix: &Option<String>,
    decl: &ItemDecl,
) -> Result<CatalogItem> {
    let kind = ItemKind::parse(&decl.kind).ok_or_else(|| MindError::MindToml {
        path: root.join("mind.toml"),
        msg: format!("unknown item kind '{}' for '{}'", decl.kind, decl.name),
    })?;
    // DSC-71/DSC-72: a melded source's `name` and `link` flow into filesystem
    // paths (the store key and the per-home symlink), so reject any value that
    // could escape its kind directory or the agent home before it is used.
    if !is_safe_item_name(&decl.name) {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "item name '{}' is unsafe: it must be a single path component (no '/', '\\', \
                 '.', '..', or NUL)",
                decl.name
            ),
        });
    }
    if let Some(link) = &decl.link
        && !is_safe_link_rel(link)
    {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "item '{}' has an unsafe link '{}': it must be a relative path inside the agent \
                 home (no leading '/' or '~', no '..' component, no NUL)",
                decl.name, link
            ),
        });
    }
    // `bin` and `build` describe tooling, so they are valid only on a tool item.
    if kind != ItemKind::Tool && (decl.bin.is_some() || decl.build.is_some()) {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "`bin`/`build` are only valid on a tool item, not '{}' ('{}')",
                decl.kind, decl.name
            ),
        });
    }
    // spec: DSC-73 — a [[items]] `path` must be a safe repo-root-relative path.
    // Reuse `is_safe_link_rel` (the same rule: relative, no `..`, no absolute or
    // `~`-rooted value, no NUL). Without this guard, `root.join` with an absolute
    // operand silently discards `root`, and a `..`-bearing path escapes the clone.
    if !is_safe_link_rel(&decl.path) {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "item '{}' has an unsafe path '{}': must be a relative path inside the clone \
                 (no leading '/' or '~', no '..' component, no NUL)",
                decl.name, decl.path
            ),
        });
    }
    let path = root.join(&decl.path);
    let meta = meta_file(kind, &path);
    // HOOK-86: resolve the item's full lifecycle hook list (scalar shorthand
    // folded ahead of the `[[items.hooks]]` array, validated). This is the
    // authoritative list for the `mind.toml` path; the scalar fields below stay
    // populated for the HOOK-85 disclosure.
    let hooks = decl.resolved_item_hooks(&root.join("mind.toml"))?;
    Ok(build_item(
        source,
        prefix,
        kind,
        decl.name.clone(),
        path,
        &meta,
        ItemOverrides {
            description: decl.description.clone(),
            link: decl.link.clone(),
            bin: decl.bin.clone(),
            build: decl.build.clone(),
            install: decl.install.clone(),
            uninstall: decl.uninstall.clone(),
            hooks: Some(hooks),
        },
    ))
}

/// True when `name` is a single safe path component (DSC-71): non-empty, not `.`
/// or `..`, and free of a path separator or NUL. The name keys the store and the
/// per-home symlink, so anything else could steer those paths out of the kind
/// directory.
fn is_safe_item_name(name: &str) -> bool {
    if name.is_empty() || name == "." || name == ".." {
        return false;
    }
    if name.contains('/') || name.contains('\\') || name.contains('\0') {
        return false;
    }
    // Belt and suspenders: exactly one normal component, nothing else.
    let mut comps = Path::new(name).components();
    matches!(comps.next(), Some(std::path::Component::Normal(_))) && comps.next().is_none()
}

/// True when `rel` is a safe link target relative to an agent home (DSC-72):
/// non-empty, not absolute, not `~`-rooted, and with no parent (`..`)/root/prefix
/// component or NUL. `rel` may contain `/` for subdirectories; it just may not
/// escape the home.
fn is_safe_link_rel(rel: &str) -> bool {
    if rel.is_empty() || rel.contains('\0') || rel.starts_with('~') {
        return false;
    }
    let p = Path::new(rel);
    if p.is_absolute() {
        return false;
    }
    use std::path::Component;
    p.components()
        .all(|c| matches!(c, Component::Normal(_) | Component::CurDir))
}

/// Read a lifecycle hook (`install`/`uninstall`, HOOK-80) from an item's meta
/// file frontmatter, but only for a tool (a `TOOL.md`). Other kinds declare
/// these only via `mind.toml` `[[items]]`, so frontmatter is not consulted.
/// An empty or whitespace-only value is treated as absent (HOOK-3).
fn lifecycle_frontmatter(kind: ItemKind, meta: &Path, key: &str) -> Option<String> {
    if kind != ItemKind::Tool {
        return None;
    }
    nonempty(frontmatter::file_field(meta, key))
}

/// Trim a value and treat an empty/whitespace-only string as absent (HOOK-3).
fn nonempty(v: Option<String>) -> Option<String> {
    v.map(|s| s.trim().to_string()).filter(|s| !s.is_empty())
}

/// Resolve a tool's `bin`/`build`: an explicit `mind.toml` value wins, else the
/// `TOOL.md` frontmatter value. Always `None` for a non-tool kind.
fn tool_field(kind: ItemKind, explicit: Option<String>, meta: &Path, key: &str) -> Option<String> {
    if kind != ItemKind::Tool {
        return None;
    }
    explicit.or_else(|| frontmatter::file_field(meta, key))
}

/// Field overrides from a `[[items]]` declaration. Every field is empty for
/// convention discovery (`make_item`); a `mind.toml` item supplies the ones it
/// declares (`from_decl`). Each takes precedence over the frontmatter fallback.
#[derive(Default)]
struct ItemOverrides {
    description: Option<String>,
    link: Option<String>,
    bin: Option<String>,
    build: Option<String>,
    install: Option<String>,
    uninstall: Option<String>,
    /// The item's fully resolved lifecycle hooks (HOOK-86) in execution order:
    /// the scalar install/uninstall shorthand folded in ahead of any
    /// `[[items.hooks]]` array entries. `None` lets `build_item` derive the list
    /// from the resolved scalar fields alone (the convention/TOOL.md path, where
    /// there is no array form, DSC-21).
    hooks: Option<Vec<ResolvedHook>>,
}

/// The single `CatalogItem` constructor: it applies the override-then-frontmatter
/// fallback policy once, so convention discovery and `[[items]]` declarations
/// share one definition of how each field is resolved.
fn build_item(
    source: &Source,
    prefix: &Option<String>,
    kind: ItemKind,
    name: String,
    path: PathBuf,
    meta: &Path,
    ov: ItemOverrides,
) -> CatalogItem {
    // HOOK-80: a `mind.toml` install/uninstall is valid on any kind; a tool's
    // TOOL.md may also carry one in frontmatter. An empty value is absent. These
    // scalar fields stay populated for the HOOK-85 disclosure, alongside `hooks`.
    let install = nonempty(ov.install).or_else(|| lifecycle_frontmatter(kind, meta, "install"));
    let uninstall =
        nonempty(ov.uninstall).or_else(|| lifecycle_frontmatter(kind, meta, "uninstall"));
    // HOOK-86: the full resolved hook list in execution order. On the `mind.toml`
    // path the caller supplies it via `ItemDecl::resolved_item_hooks` (scalar
    // shorthand folded ahead of the `[[items.hooks]]` array). On the
    // convention/TOOL.md path there is no array (DSC-21), so derive it from the
    // resolved scalar install/uninstall (which may come from TOOL.md frontmatter),
    // each as one required hook of its event.
    let hooks = ov.hooks.unwrap_or_else(|| {
        let mut out: Vec<ResolvedHook> = Vec::new();
        for (cmd, event) in [
            (&install, HookEvent::Install),
            (&uninstall, HookEvent::Uninstall),
        ] {
            if let Some(c) = cmd {
                out.push(ResolvedHook {
                    run: c.clone(),
                    name: None,
                    optional: false,
                    event,
                });
            }
        }
        out
    });
    // DEP-4: read the `requires:` frontmatter scalar and split on whitespace.
    // This is always read from `meta` regardless of kind; absent or empty -> empty Vec.
    let requires: Vec<String> = frontmatter::file_field(meta, "requires")
        .map(|s| s.split_whitespace().map(str::to_owned).collect())
        .unwrap_or_default();
    CatalogItem {
        kind,
        name,
        source: source.name.clone(),
        prefix: prefix.clone(),
        path,
        description: ov.description.or_else(|| frontmatter::description(meta)),
        link_rel: ov.link,
        bin: tool_field(kind, ov.bin, meta, "bin"),
        build: tool_field(kind, ov.build, meta, "build"),
        install,
        uninstall,
        requires,
        hooks,
    }
}

/// Discover items by glob, relative to the repo root. Nested `sources` are
/// handled at meld time, not here.
fn scan_globs(
    root: &Path,
    source: &Source,
    prefix: &Option<String>,
    discover: &Discover,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    for skill_md in resolve_globs(root, &discover.skills)? {
        // The glob points at the SKILL.md; the item is its parent dir.
        if let Some(dir) = skill_md.parent() {
            out.push(make_item(
                source,
                prefix,
                ItemKind::Skill,
                dir.to_path_buf(),
                &skill_md,
            ));
        }
    }
    for (kind, globs) in [
        (ItemKind::Agent, &discover.agents),
        (ItemKind::Rule, &discover.rules),
    ] {
        for md in resolve_globs(root, globs)? {
            out.push(make_item(source, prefix, kind, md.clone(), &md));
        }
    }
    // Tool globs match the tool directory itself; its `TOOL.md` (if any) is the
    // metadata source.
    for dir in resolve_globs(root, &discover.tools)? {
        let meta = dir.join("TOOL.md");
        out.push(make_item(source, prefix, ItemKind::Tool, dir, &meta));
    }
    Ok(())
}

/// Expand a kind's include globs, then drop anything its exclude globs match.
fn resolve_globs(root: &Path, globs: &KindGlobs) -> Result<Vec<PathBuf>> {
    let mut included = BTreeSet::new();
    for pattern in &globs.include {
        included.extend(glob_paths(root, pattern)?);
    }
    let mut excluded = BTreeSet::new();
    for pattern in &globs.exclude {
        excluded.extend(glob_paths(root, pattern)?);
    }
    Ok(included.difference(&excluded).cloned().collect())
}

/// Convention scan: fixed `skills/`, `agents/`, `rules/` directories.
///
/// When `flat_skills` is true (DSC-74), skills are instead found as bare-name
/// directories with a direct `SKILL.md` immediately under `root` (no `skills/`
/// container); agent, rule, and tool discovery are unchanged either way.
fn scan_convention(
    root: &Path,
    source: &Source,
    prefix: &Option<String>,
    flat_skills: bool,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    // spec: DSC-74 — flat layout: each immediate child directory of `root` that
    // contains a direct `SKILL.md` is a skill, taking the directory name as its
    // bare name. The scan is shallow (only `root`'s immediate children), and the
    // `SKILL.md` anchor disambiguates a skill dir from `agents/`, `rules/`, etc.
    // Otherwise (DSC-10) skills live under the `skills/` container.
    let skills_dir = if flat_skills {
        root.to_path_buf()
    } else {
        root.join(ItemKind::Skill.dir())
    };
    for entry in read_dir_opt(&skills_dir)? {
        let skill_md = entry.join("SKILL.md");
        if entry.is_dir() && skill_md.is_file() {
            out.push(make_item(source, prefix, ItemKind::Skill, entry, &skill_md));
        }
    }

    for kind in [ItemKind::Agent, ItemKind::Rule] {
        let kind_dir = root.join(kind.dir());
        for entry in read_dir_opt(&kind_dir)? {
            if entry.is_file() && entry.extension().is_some_and(|e| e == "md") {
                out.push(make_item(source, prefix, kind, entry.clone(), &entry));
            }
        }
    }

    // Tools: every immediate subdirectory of `tools/` is a tool. Unlike a skill,
    // a tool needs no anchor file; its directory contents are the tool. An
    // optional `TOOL.md` carries `description`/`bin`/`build` (read in make_item).
    let tools_dir = root.join(ItemKind::Tool.dir());
    for entry in read_dir_opt(&tools_dir)? {
        if entry.is_dir() {
            let meta = entry.join("TOOL.md");
            out.push(make_item(source, prefix, ItemKind::Tool, entry, &meta));
        }
    }
    Ok(())
}

/// Build a [`CatalogItem`], deriving its bare name from the path and its
/// description from `meta_file`'s frontmatter, then applying the prefix.
fn make_item(
    source: &Source,
    prefix: &Option<String>,
    kind: ItemKind,
    path: PathBuf,
    meta: &Path,
) -> CatalogItem {
    let bare = match kind {
        // Directory-shaped items take the directory name; file items the stem.
        ItemKind::Skill | ItemKind::Tool => file_name(&path),
        ItemKind::Agent | ItemKind::Rule => path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default(),
    };
    // Convention discovery carries no overrides: every field falls back to the
    // item's frontmatter (HOOK-80: install/uninstall only from a tool's TOOL.md).
    build_item(
        source,
        prefix,
        kind,
        bare,
        path,
        meta,
        ItemOverrides::default(),
    )
}

#[cfg(test)]
mod lifecycle_tests {
    use super::*;
    use std::sync::atomic::{AtomicU32, Ordering};

    static N: AtomicU32 = AtomicU32::new(0);

    fn tmp() -> PathBuf {
        let n = N.fetch_add(1, Ordering::SeqCst);
        let p = std::env::temp_dir().join(format!("mind-lifecycle-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&p);
        std::fs::create_dir_all(&p).unwrap();
        p
    }

    fn write(path: &Path, contents: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    }

    fn source_for(clone: &Path) -> Source {
        use crate::source::Pin;
        Source {
            name: "local/test/repo".to_string(),
            url: clone.to_string_lossy().into_owned(),
            host: "local".to_string(),
            owner: "test".to_string(),
            repo: "repo".to_string(),
            commit: None,
            description: None,
            alias: None,
            pin: Pin::default(),
            roots: None,
            flat_skills: false,
            origin: None,
            plugin_version: None,
            install_hooks: Vec::new(),
            install_hook: None,
            install_hook_commit: None,
        }
    }

    #[test]
    fn item_install_uninstall_hooks_from_mind_toml_on_any_kind() {
        // spec: HOOK-80
        // A `mind.toml` [[items]].install/.uninstall is valid on a non-tool kind
        // (here a rule), unlike `bin`/`build` which are tool-only.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"guidelines/style.md\"\n",
                "install = \"echo set-up\"\n",
                "uninstall = \"echo tear-down\"\n",
            ),
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let rule = items.iter().find(|i| i.name == "style").unwrap();
        assert_eq!(rule.install.as_deref(), Some("echo set-up"));
        assert_eq!(rule.uninstall.as_deref(), Some("echo tear-down"));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn item_hooks_from_tool_md_frontmatter() {
        // spec: HOOK-80
        // A tool's TOOL.md may carry install:/uninstall: in frontmatter.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("tools/helper/TOOL.md"),
            "---\ndescription: helper\ninstall: make setup\nuninstall: make cleanup\n---\n# helper\n",
        );
        write(&clone.join("tools/helper/helper"), "#!/bin/sh\n");
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let tool = items.iter().find(|i| i.name == "helper").unwrap();
        assert_eq!(tool.install.as_deref(), Some("make setup"));
        assert_eq!(tool.uninstall.as_deref(), Some("make cleanup"));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn empty_item_hook_is_treated_as_absent() {
        // spec: HOOK-80
        // An empty/whitespace install or uninstall is absent (HOOK-3).
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"guidelines/style.md\"\n",
                "install = \"   \"\n",
            ),
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let rule = items.iter().find(|i| i.name == "style").unwrap();
        assert_eq!(rule.install, None, "whitespace install must be absent");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn scalar_item_hooks_populate_both_the_scalar_fields_and_the_list() {
        // spec: HOOK-86
        // COORDINATION: the scalar install/uninstall fields stay populated (the
        // HOOK-85 disclosure reads them) AND the resolved hook list is populated.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"guidelines/style.md\"\n",
                "install = \"echo set-up\"\n",
                "uninstall = \"echo tear-down\"\n",
            ),
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let rule = items.iter().find(|i| i.name == "style").unwrap();
        // Scalar fields still populated.
        assert_eq!(rule.install.as_deref(), Some("echo set-up"));
        assert_eq!(rule.uninstall.as_deref(), Some("echo tear-down"));
        // The resolved list mirrors them: one required install, one required
        // uninstall, in fold-in order.
        assert_eq!(rule.hooks.len(), 2);
        let ih = rule.install_hooks();
        assert_eq!(ih.len(), 1);
        assert_eq!(ih[0].run, "echo set-up");
        let uh = rule.uninstall_hooks();
        assert_eq!(uh.len(), 1);
        assert_eq!(uh[0].run, "echo tear-down");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn array_item_hooks_resolve_in_order_with_scalar_folded_ahead() {
        // spec: HOOK-86
        // A `[[items.hooks]]` array plus a scalar install: the scalar folds in as
        // the first install hook, then the array entries in declaration order.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(&clone.join("tools/helper/helper"), "#!/bin/sh\n");
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"tool\"\n",
                "name = \"helper\"\n",
                "path = \"tools/helper\"\n",
                "install = \"scalar-install\"\n",
                "\n",
                "[[items.hooks]]\n",
                "run = \"array-install\"\n",
                "name = \"Second step\"\n",
                "\n",
                "[[items.hooks]]\n",
                "run = \"array-uninstall\"\n",
                "event = \"uninstall\"\n",
            ),
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let tool = items.iter().find(|i| i.name == "helper").unwrap();
        // Scalar field still set.
        assert_eq!(tool.install.as_deref(), Some("scalar-install"));
        // Full list: scalar install, then the two array entries.
        assert_eq!(tool.hooks.len(), 3);
        let ih = tool.install_hooks();
        assert_eq!(ih.len(), 2);
        assert_eq!(ih[0].run, "scalar-install");
        assert_eq!(ih[1].run, "array-install");
        assert_eq!(ih[1].name.as_deref(), Some("Second step"));
        let uh = tool.uninstall_hooks();
        assert_eq!(uh.len(), 1);
        assert_eq!(uh[0].run, "array-uninstall");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn tool_md_scalar_hooks_fold_into_the_list() {
        // spec: HOOK-86
        // For a convention-discovered tool, the TOOL.md install:/uninstall:
        // frontmatter scalars (DSC-21: the only form there) fold into the hook
        // list AND populate the scalar fields.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("tools/helper/TOOL.md"),
            "---\ndescription: helper\ninstall: make setup\nuninstall: make cleanup\n---\n# helper\n",
        );
        write(&clone.join("tools/helper/helper"), "#!/bin/sh\n");
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let tool = items.iter().find(|i| i.name == "helper").unwrap();
        assert_eq!(tool.install.as_deref(), Some("make setup"));
        assert_eq!(tool.uninstall.as_deref(), Some("make cleanup"));
        // Folded into the list as one required hook each.
        assert_eq!(tool.hooks.len(), 2);
        assert_eq!(tool.install_hooks()[0].run, "make setup");
        assert!(!tool.install_hooks()[0].optional);
        assert_eq!(tool.uninstall_hooks()[0].run, "make cleanup");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn item_array_hooks_unknown_event_is_a_scan_error() {
        // spec: HOOK-86
        // An unknown event in a `[[items.hooks]]` entry surfaces as a mind.toml
        // schema error from the scan (via from_decl).
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(&clone.join("tools/helper/helper"), "#!/bin/sh\n");
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"tool\"\n",
                "name = \"helper\"\n",
                "path = \"tools/helper\"\n",
                "\n",
                "[[items.hooks]]\n",
                "run = \"do-it\"\n",
                "event = \"build\"\n",
            ),
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        let err = scan_source(&paths, &source_for(&clone), &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "unknown item hook event must be a schema error: {err}"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn requires_populated_on_authoritative_mind_toml_item() {
        // spec: DEP-4
        // An authoritative `[[items]]` declaration routes through `from_decl` ->
        // `build_item`, the same constructor as convention discovery. So an item
        // declared in mind.toml whose META FILE frontmatter carries `requires:`
        // must still have that field populated (it is read from the meta file, not
        // from the `[[items]]` table). Pins the otherwise-untested mind.toml route.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\nrequires: agent:linter\n---\n# style\n",
        );
        write(
            &clone.join("agents/linter.md"),
            "---\ndescription: linter\n---\n# linter\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"guidelines/style.md\"\n",
                "[[items]]\n",
                "kind = \"agent\"\n",
                "name = \"linter\"\n",
                "path = \"agents/linter.md\"\n",
            ),
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let rule = items.iter().find(|i| i.name == "style").unwrap();
        assert_eq!(
            rule.requires,
            vec!["agent:linter".to_string()],
            "requires from the meta-file frontmatter must populate on the authoritative mind.toml path"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn requires_splits_on_arbitrary_whitespace() {
        // spec: DEP-4
        // The `requires:` scalar is split on whitespace, not a YAML sequence:
        // multiple internal spaces and leading/trailing whitespace collapse to a
        // clean list of entries (DEP-4: "a single string split on whitespace").
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/review/SKILL.md"),
            "---\ndescription: review\nrequires:   agent:a    rule:b  \n---\n# review\n",
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let skill = items.iter().find(|i| i.name == "review").unwrap();
        assert_eq!(
            skill.requires,
            vec!["agent:a".to_string(), "rule:b".to_string()],
            "extra/leading/trailing whitespace must split into exactly two entries"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn empty_requires_scalar_yields_no_entries() {
        // spec: DEP-4
        // An empty (or whitespace-only) `requires:` value yields an empty entry
        // list and no error: `"".split_whitespace()` produces zero items. Pins
        // that an author writing `requires:` with no value is a benign no-op, not
        // a spurious edge or a bad-reference at scan time.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/review/SKILL.md"),
            "---\ndescription: review\nrequires:    \n---\n# review\n",
        );
        let paths = Paths {
            mind_home: base.clone(),
            claude_home: base.join("claude"),
        };
        let mut items = Vec::new();
        scan_source(&paths, &source_for(&clone), &mut items).unwrap();
        let skill = items.iter().find(|i| i.name == "review").unwrap();
        assert!(
            skill.requires.is_empty(),
            "a whitespace-only requires value must yield no entries: {:?}",
            skill.requires
        );
        let _ = std::fs::remove_dir_all(&base);
    }
}

/// Scan a plugin root for skills and agents only (MKT-3).
///
/// A plugin's component layout matches `mind`'s convention layout (DSC-10, DSC-11):
/// `skills/<name>/SKILL.md` -> Skill, `agents/<name>.md` -> Agent. Rules and tools
/// have no plugin equivalent and are not emitted. The flat-skills knob and
/// `[source].roots` do not apply to a plugin.
fn scan_plugin_components(
    plugin_root: &Path,
    source: &Source,
    prefix: &Option<String>,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    // Skills: skills/<name>/SKILL.md at the plugin root (DSC-10, MKT-3).
    let skills_dir = plugin_root.join(ItemKind::Skill.dir());
    for entry in read_dir_opt(&skills_dir)? {
        let skill_md = entry.join("SKILL.md");
        if entry.is_dir() && skill_md.is_file() {
            out.push(make_item(source, prefix, ItemKind::Skill, entry, &skill_md));
        }
    }
    // Agents: agents/<name>.md at the plugin root (DSC-11, MKT-3).
    // NS-40: agent_harness_name reads frontmatter `name:` just as convention does.
    let agents_dir = plugin_root.join(ItemKind::Agent.dir());
    for entry in read_dir_opt(&agents_dir)? {
        if entry.is_file() && entry.extension().is_some_and(|e| e == "md") {
            out.push(make_item(
                source,
                prefix,
                ItemKind::Agent,
                entry.clone(),
                &entry,
            ));
        }
    }
    Ok(())
}

/// Scan in-repo plugins declared in a marketplace manifest (MKT-14).
///
/// Each entry with [`plugin_manifest::PluginSource::InRepo`] is treated as a scan
/// root within the catalog repo. When an entry's `skills` array is non-empty, only
/// the listed leaf skill directories are scanned; otherwise `plugin_root/skills/` is
/// scanned conventionally. Agents are always scanned conventionally from
/// `plugin_root/agents/`. External entries are skipped — those are sub-melded by
/// `commands.rs`.
///
/// `outer_prefix`: the already-resolved effective prefix for the source (alias or
/// mindfile prefix, filtered to `None` when empty). `has_explicit_prefix`: true when
/// the consumer set an explicit override (even `""` to clear), used to decide whether
/// to fall back to the entry name as the default namespace prefix.
// spec: MKT-14
fn scan_marketplace_in_repo_plugins(
    clone_root: &Path,
    source: &Source,
    manifest: plugin_manifest::MarketplaceManifest,
    outer_prefix: &Option<String>,
    has_explicit_prefix: bool,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    // Pre-compute canonicalized clone root once for the path-traversal guard (H4).
    let canon_clone = clone_root
        .canonicalize()
        .unwrap_or_else(|_| clone_root.to_path_buf());

    for entry in manifest.into_entries() {
        // Only process in-repo entries; external ones are sub-melded by commands.rs.
        let inrepo_path = match &entry.source {
            plugin_manifest::PluginSource::InRepo { path } => path.clone(),
            plugin_manifest::PluginSource::External { .. } => continue,
        };

        // 1. Compute the plugin root.
        //    clone_root.join("./") normalizes to clone_root on all platforms.
        let plugin_root = clone_root.join(&inrepo_path);

        // H4 (MKT-14, MKT-9): path-traversal guard -- skip entries whose resolved
        // plugin_root escapes the clone root, including paths traversed via symlinks.
        // Same "skip silently" tolerance as the scan-root guard uses "skip silently" for
        // an unresolvable path; here we also skip rather than error to keep resilience.
        let Ok(canon_plugin) = plugin_root.canonicalize() else {
            continue; // non-existent or unresolvable -- skip silently
        };
        if !canon_plugin.starts_with(&canon_clone) {
            continue; // plugin_root escapes the clone -- skip silently
        }

        // 2. Compute the effective prefix (MKT-5 / MKT-8 / MKT-13).
        //    M5a (MKT-14): strip ANSI from the entry name before using as a prefix
        //    to prevent terminal injection from catalog-controlled content.
        let entry_name = strip_ansi(entry.name.trim());

        let plugin_prefix = if has_explicit_prefix {
            // Consumer set an explicit namespace override (MKT-13).  Per-plugin
            // namespacing (MKT-8) still applies regardless; outer_prefix layers on
            // top when present.
            match outer_prefix {
                Some(p) if !entry_name.is_empty() => {
                    // outer_prefix:entry_name combined; items end up outer:entry:name.
                    Some(format!("{p}:{entry_name}"))
                }
                Some(p) => {
                    // entry_name was empty/ANSI-only after sanitization; use outer alone.
                    Some(p.clone())
                }
                None => {
                    // Outer prefix explicitly cleared (namespace=""); per-plugin prefix
                    // (entry name) is still intact per MKT-13.
                    // Resilience (NS-25): fall back to no prefix when entry name is
                    // reserved or empty rather than making the entry un-installable.
                    match namespace::validate_prefix(&entry_name) {
                        Ok(()) if !entry_name.is_empty() => Some(entry_name.clone()),
                        _ => None,
                    }
                }
            }
        } else {
            // No override; use entry name as default namespace prefix (MKT-8).
            // Resilience (NS-25): fall back to no prefix when entry name is reserved
            // or empty rather than making the entry un-installable.
            match namespace::validate_prefix(&entry_name) {
                Ok(()) if !entry_name.is_empty() => Some(entry_name.clone()),
                _ => None,
            }
        };

        // 3. Scan skills.
        if !entry.skills.is_empty() {
            // Explicit skill paths: each is a leaf dir (relative to plugin_root)
            // that contains a SKILL.md. Missing dirs or absent SKILL.md are skipped
            // silently (same tolerance as scan_plugin_components).
            for skill_path in &entry.skills {
                let skill_dir = plugin_root.join(skill_path);
                let skill_md = skill_dir.join("SKILL.md");
                if skill_dir.is_dir() && skill_md.is_file() {
                    out.push(make_item(
                        source,
                        &plugin_prefix,
                        ItemKind::Skill,
                        skill_dir,
                        &skill_md,
                    ));
                }
            }
        } else {
            // No explicit skills array: scan plugin_root/skills/ conventionally.
            let skills_dir = plugin_root.join(ItemKind::Skill.dir());
            for entry_path in read_dir_opt(&skills_dir)? {
                let skill_md = entry_path.join("SKILL.md");
                if entry_path.is_dir() && skill_md.is_file() {
                    out.push(make_item(
                        source,
                        &plugin_prefix,
                        ItemKind::Skill,
                        entry_path,
                        &skill_md,
                    ));
                }
            }
        }

        // 4. Scan agents (always): agents/<name>.md at the plugin root (DSC-11, MKT-3).
        let agents_dir = plugin_root.join(ItemKind::Agent.dir());
        for agent_path in read_dir_opt(&agents_dir)? {
            if agent_path.is_file() && agent_path.extension().is_some_and(|e| e == "md") {
                out.push(make_item(
                    source,
                    &plugin_prefix,
                    ItemKind::Agent,
                    agent_path.clone(),
                    &agent_path,
                ));
            }
        }
    }
    Ok(())
}

/// Count unsupported Claude plugin components present at a plugin root (MKT-4).
///
/// Checks for directory-based components: `commands/` and `hooks/` (which have no
/// `mind` equivalent), and a `.mcp.json` file (mcpServers). Manifest-declared keys
/// beyond these (lsp servers, monitors, themes, output styles) are not counted here
/// because they leave no directory marker — they would require re-parsing the
/// manifest. This is a dir-based heuristic; commands.rs (shard 4) calls this at
/// meld time and prints the summary via `SkippedComponents::summary`.
pub fn plugin_skipped_components(plugin_root: &Path) -> plugin_manifest::SkippedComponents {
    let mut sc = plugin_manifest::SkippedComponents::default();
    if plugin_root.join("commands").is_dir() {
        sc.commands = 1;
    }
    if plugin_root.join("hooks").is_dir() {
        sc.hooks = 1;
    }
    if plugin_root.join(".mcp.json").is_file() {
        sc.mcp_servers = 1;
    }
    sc
}

/// The file whose frontmatter describes an item (SKILL.md for a skill, TOOL.md
/// for a tool, the item file itself for an agent/rule). The file may be absent
/// for a tool (it is optional), in which case frontmatter reads yield `None`.
fn meta_file(kind: ItemKind, path: &Path) -> PathBuf {
    match kind {
        ItemKind::Skill => path.join("SKILL.md"),
        ItemKind::Tool => path.join("TOOL.md"),
        ItemKind::Agent | ItemKind::Rule => path.to_path_buf(),
    }
}

/// Strip ANSI escape sequences and certain unsafe Unicode code points from `s`.
///
/// Used to sanitize names and descriptions read from plugin/marketplace manifests
/// (MKT-9) before using them as namespace prefixes or display strings, preventing
/// terminal injection from catalog-controlled content (DSC-69 rule).
///
/// Mirrors `commands::strip_ansi`; duplicated here to avoid a cross-module
/// private dependency.
fn strip_ansi(s: &str) -> String {
    let bytes = strip_ansi_escapes::strip(s);
    // Input is valid UTF-8, so output is too; lossy is a no-op in practice.
    String::from_utf8_lossy(&bytes)
        .chars()
        .filter(|&c| {
            (('\x20'..='\x7e').contains(&c) || c > '\u{009f}')
                && !matches!(
                    c,
                    // Bidi-override code points: phishing/spoofing vectors.
                    '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
                    // Line separator and paragraph separator.
                    | '\u{2028}' | '\u{2029}'
                )
        })
        .collect()
}

/// Expand a glob pattern rooted at `root`, returning sorted matches.
fn glob_paths(root: &Path, pattern: &str) -> Result<Vec<PathBuf>> {
    let joined = root.join(pattern);
    let full = joined.to_string_lossy();
    let paths = glob::glob(&full).map_err(|e| MindError::MindToml {
        path: root.join("mind.toml"),
        msg: format!("bad discover glob '{pattern}': {e}"),
    })?;
    let mut out = Vec::new();
    for entry in paths {
        match entry {
            Ok(p) => out.push(p),
            Err(e) => {
                let path = e.path().to_path_buf();
                return Err(MindError::io(path, e.into_error()));
            }
        }
    }
    out.sort();
    Ok(out)
}

/// Read a directory's entries, treating "not found" as empty.
fn read_dir_opt(dir: &Path) -> Result<Vec<PathBuf>> {
    match std::fs::read_dir(dir) {
        Ok(rd) => {
            let mut paths = Vec::new();
            for entry in rd {
                let entry = entry.map_err(|e| MindError::io(dir, e))?;
                paths.push(entry.path());
            }
            paths.sort();
            Ok(paths)
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
        Err(e) => Err(MindError::io(dir, e)),
    }
}

fn file_name(p: &Path) -> String {
    p.file_name()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ItemKind;
    use crate::paths::Paths;
    use crate::source::{Pin, Source};
    use std::path::PathBuf;

    // ---- scan roots unit tests (DSC-50, DSC-51, DSC-52, DSC-53) -------

    use std::sync::atomic::{AtomicU32, Ordering};
    static UNIT_COUNTER: AtomicU32 = AtomicU32::new(0);

    /// Allocate a unique temp dir for a unit test and return a guard that
    /// removes it on drop (via a wrapper struct).
    struct TmpDir(PathBuf);
    impl TmpDir {
        fn new() -> Self {
            let n = UNIT_COUNTER.fetch_add(1, Ordering::SeqCst);
            let p =
                std::env::temp_dir().join(format!("mind-catalog-unit-{}-{n}", std::process::id()));
            let _ = std::fs::remove_dir_all(&p);
            std::fs::create_dir_all(&p).unwrap();
            TmpDir(p)
        }
        fn path(&self) -> &std::path::Path {
            &self.0
        }
    }
    impl Drop for TmpDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// Create a minimal `Source` for a local path fixture.
    fn make_source_for(clone: &std::path::Path) -> Source {
        Source {
            name: "local/test/repo".to_string(),
            url: clone.to_string_lossy().into_owned(),
            host: "local".to_string(),
            owner: "test".to_string(),
            repo: "repo".to_string(),
            commit: None,
            description: None,
            alias: None,
            pin: Pin::default(),
            roots: None,
            flat_skills: false,
            origin: None,
            plugin_version: None,
            install_hooks: Vec::new(),
            install_hook: None,
            install_hook_commit: None,
        }
    }

    /// Create a `Paths` whose sources dir is `base/sources`, so that
    /// the clone of `local/test/repo` lives at `base/sources/local/test/repo`.
    fn paths_for(base: &std::path::Path) -> Paths {
        Paths {
            mind_home: base.to_path_buf(),
            claude_home: base.join("claude"),
        }
    }

    fn write_file(path: &std::path::Path, contents: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    }

    #[test]
    fn convention_discovery_under_single_explicit_root() {
        // spec: DSC-50 DSC-53
        // When [source].roots = ["tools"], items in tools/skills/ etc. are found.
        let tmp = TmpDir::new();
        let base = tmp.path();

        // The clone lands at base/sources/local/test/repo.
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("tools/skills/meld/SKILL.md"),
            "---\ndescription: meld skill\n---\n# meld\n",
        );
        write_file(
            &clone.join("tools/agents/do.md"),
            "---\ndescription: do agent\n---\n# do\n",
        );
        // Write a mind.toml with roots = ["tools"].
        write_file(&clone.join("mind.toml"), "[source]\nroots = [\"tools\"]\n");

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(names.contains(&"meld"), "expected 'meld': {names:?}");
        assert!(names.contains(&"do"), "expected 'do': {names:?}");
        // No items from the repo root (no skills/ at root).
        assert!(!names.contains(&"review"), "unexpected 'review': {names:?}");
    }

    #[test]
    fn source_roots_override_beats_mindfile_roots() {
        // spec: DSC-51 STO-17
        // Source.roots (--root override) takes precedence over [source].roots in mind.toml.
        let tmp = TmpDir::new();
        let base = tmp.path();

        let clone = base.join("sources/local/test/repo");
        // Items only under "a/".
        write_file(
            &clone.join("a/skills/alpha/SKILL.md"),
            "---\ndescription: alpha\n---\n# alpha\n",
        );
        // Items only under "b/".
        write_file(
            &clone.join("b/skills/beta/SKILL.md"),
            "---\ndescription: beta\n---\n# beta\n",
        );
        // mind.toml says roots = ["b"], but the source override says ["a"].
        write_file(&clone.join("mind.toml"), "[source]\nroots = [\"b\"]\n");

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        // Consumer --root override points at "a".
        source.roots = Some(vec!["a".to_string()]);

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(
            names.contains(&"alpha"),
            "override root 'a' expected: {names:?}"
        );
        assert!(
            !names.contains(&"beta"),
            "toml root 'b' should be ignored: {names:?}"
        );
    }

    #[test]
    fn two_roots_are_unioned() {
        // spec: DSC-53
        let tmp = TmpDir::new();
        let base = tmp.path();

        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("a/skills/alpha/SKILL.md"),
            "---\ndescription: alpha\n---\n# alpha\n",
        );
        write_file(
            &clone.join("b/skills/beta/SKILL.md"),
            "---\ndescription: beta\n---\n# beta\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["a".to_string(), "b".to_string()]);

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(names.contains(&"alpha"), "expected alpha: {names:?}");
        assert!(names.contains(&"beta"), "expected beta: {names:?}");
    }

    #[test]
    fn duplicate_item_across_roots_is_an_error() {
        // spec: DSC-53
        let tmp = TmpDir::new();
        let base = tmp.path();

        let clone = base.join("sources/local/test/repo");
        // "review" skill under both "a/" and "b/".
        write_file(
            &clone.join("a/skills/review/SKILL.md"),
            "---\ndescription: review a\n---\n# review\n",
        );
        write_file(
            &clone.join("b/skills/review/SKILL.md"),
            "---\ndescription: review b\n---\n# review\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["a".to_string(), "b".to_string()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::DuplicateItem { ref name, .. } if name == "review"),
            "expected DuplicateItem: {err}"
        );
    }

    #[test]
    fn flat_skills_discovers_bare_dirs_and_composes_with_roots() {
        // spec: DSC-74
        // With flat_skills set, a skill is a bare-name directory containing a
        // direct SKILL.md under each scan root (no `skills/` container). The
        // SKILL.md anchor disambiguates a skill dir from an arbitrary one, and
        // agent discovery (a conventional `agents/` dir) is unchanged. It composes
        // with roots: here a single root `pkg`.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        // Flat skills directly under the `pkg` root.
        write_file(
            &clone.join("pkg/alpha/SKILL.md"),
            "---\ndescription: alpha\n---\n# alpha\n",
        );
        write_file(
            &clone.join("pkg/beta/SKILL.md"),
            "---\ndescription: beta\n---\n# beta\n",
        );
        // A bare dir with no SKILL.md must NOT be classified as a skill.
        write_file(&clone.join("pkg/notaskill/README.md"), "# nope\n");
        // Agent discovery under the same root is unchanged.
        write_file(
            &clone.join("pkg/agents/dev.md"),
            "---\ndescription: dev\n---\n# dev\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["pkg".to_string()]);
        source.flat_skills = true;

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        let skills: Vec<&str> = items
            .iter()
            .filter(|i| i.kind == ItemKind::Skill)
            .map(|i| i.name.as_str())
            .collect();
        assert!(
            skills.contains(&"alpha"),
            "expected flat skill alpha: {skills:?}"
        );
        assert!(
            skills.contains(&"beta"),
            "expected flat skill beta: {skills:?}"
        );
        assert!(
            !skills.contains(&"notaskill"),
            "a dir without SKILL.md must not be a skill: {skills:?}"
        );
        // The agent is still discovered conventionally.
        assert!(
            items
                .iter()
                .any(|i| i.kind == ItemKind::Agent && i.name == "dev"),
            "agent discovery must be unchanged under flat-skills"
        );
    }

    #[test]
    fn flat_skills_off_requires_skills_container() {
        // spec: DSC-74
        // With flat_skills false (the default), a bare-name skill dir at the root
        // is NOT discovered; the `skills/` container is required (DSC-10).
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("alpha/SKILL.md"),
            "---\ndescription: alpha\n---\n# alpha\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone); // flat_skills defaults false
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        assert!(
            items.is_empty(),
            "a root-level skill dir must not be found without flat-skills: {:?}",
            items.iter().map(|i| i.name.as_str()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn flat_skills_duplicate_across_roots_is_an_error() {
        // spec: DSC-74 DSC-53
        // Flat discovery composes with multi-root union and the within-source
        // uniqueness check: two roots each shipping a flat `alpha/SKILL.md` is a
        // DuplicateItem, exactly as for the containered layout.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("a/alpha/SKILL.md"),
            "---\ndescription: alpha a\n---\n# alpha\n",
        );
        write_file(
            &clone.join("b/alpha/SKILL.md"),
            "---\ndescription: alpha b\n---\n# alpha\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["a".to_string(), "b".to_string()]);
        source.flat_skills = true;

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::DuplicateItem { ref name, .. } if name == "alpha"),
            "expected DuplicateItem for a flat skill across two roots: {err}"
        );
    }

    #[test]
    fn non_directory_root_is_invalid_root_error() {
        // spec: DSC-52
        let tmp = TmpDir::new();
        let base = tmp.path();

        let clone = base.join("sources/local/test/repo");
        std::fs::create_dir_all(&clone).unwrap();

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["nonexistent".to_string()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::InvalidRoot { ref root, .. } if root == "nonexistent"),
            "expected InvalidRoot: {err}"
        );
    }

    #[test]
    fn authoritative_mind_toml_ignores_roots() {
        // spec: DSC-52
        let tmp = TmpDir::new();
        let base = tmp.path();

        let clone = base.join("sources/local/test/repo");
        // A rule declared explicitly in mind.toml.
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style rule\n---\n# style\n",
        );
        // Convention items under "sub/".
        write_file(
            &clone.join("sub/skills/review/SKILL.md"),
            "---\ndescription: review\n---\n# review\n",
        );
        write_file(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"guidelines/style.md\"\n",
            ),
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        // Consumer root pointing at "sub/" -- should be ignored for authoritative source.
        source.roots = Some(vec!["sub".to_string()]);

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        // Only the explicitly declared item; the convention root is ignored.
        assert!(names.contains(&"style"), "expected 'style': {names:?}");
        assert!(
            !names.contains(&"review"),
            "convention scan should be ignored: {names:?}"
        );
    }

    #[test]
    fn absolute_root_pointing_inside_the_clone_is_still_invalid() {
        // spec: DSC-52 CLI-16
        // A root must be repo-root-relative. An ABSOLUTE path is rejected even
        // when it names a real directory INSIDE the clone -- so only the
        // is_absolute() guard can catch it (the escape and is_dir checks would
        // both pass). This isolates the absolute-path guard from the escape guard.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("tools/skills/build/SKILL.md"),
            "---\ndescription: build\n---\n# build\n",
        );
        // The clone path must canonicalize stably (no symlinks in temp here).
        let abs_inside = clone.join("tools").canonicalize().unwrap();
        assert!(abs_inside.is_absolute());

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec![abs_inside.to_string_lossy().into_owned()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::InvalidRoot { .. }),
            "an absolute root, even inside the clone, must be InvalidRoot: {err}"
        );
        assert!(items.is_empty(), "absolute root must contribute nothing");
    }

    #[test]
    fn absolute_root_outside_the_clone_is_invalid() {
        // spec: DSC-52 CLI-16
        // The plain case: an absolute path outside the clone is rejected.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        std::fs::create_dir_all(&clone).unwrap();

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["/tmp".to_string()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::InvalidRoot { ref root, .. } if root == "/tmp"),
            "absolute root outside the clone must be InvalidRoot: {err}"
        );
    }

    #[test]
    fn parent_escaping_root_to_existing_sibling_is_invalid_root() {
        // spec: DSC-52 CLI-16
        // The escape guard must reject a `..` root that resolves to a real
        // directory OUTSIDE the clone. This is the adversarial case the is_dir()
        // check alone cannot catch (the sibling exists), so only the
        // canonicalize/starts_with guard stands between it and a read outside the
        // clone.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        // A sibling clone dir that exists and even has scannable items.
        let sibling = base.join("sources/local/test/other");
        write_file(
            &sibling.join("skills/leak/SKILL.md"),
            "---\ndescription: leaked\n---\n# leak\n",
        );
        std::fs::create_dir_all(&clone).unwrap();

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        // ../other escapes the clone but points at an existing directory.
        source.roots = Some(vec!["../other".to_string()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::InvalidRoot { ref root, .. } if root == "../other"),
            "escaping root must be InvalidRoot, not a silent read outside the clone: {err}"
        );
        assert!(
            items.is_empty(),
            "no items should leak from outside the clone"
        );
    }

    #[test]
    fn in_clone_dotdot_root_is_allowed() {
        // spec: DSC-50 DSC-52
        // A `..` segment that stays inside the clone (`tools/../tools`) is a
        // legitimate in-clone path and must be accepted, distinguishing it from a
        // genuinely escaping `../x`. Mirror test of the escape rejection: this
        // pins that the guard is not over-broad (rejecting all `..`).
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("tools/skills/build/SKILL.md"),
            "---\ndescription: build\n---\n# build\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.roots = Some(vec!["tools/../tools".to_string()]);

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(
            names.contains(&"build"),
            "in-clone .. should resolve: {names:?}"
        );
    }

    #[test]
    fn duplicate_item_check_is_scoped_to_one_source() {
        // spec: DSC-53
        // The (kind, bare_name) duplicate check is per-source: a `review` skill in
        // source A and a `review` skill in source B is NOT a DuplicateItem -- only
        // a collision WITHIN one source's roots is. Regression guard: if the dedup
        // scanned `out` from index 0 instead of this source's slice, this would
        // wrongly error.
        let tmp = TmpDir::new();
        let base = tmp.path();

        let clone_a = base.join("sources/local/test/repo");
        write_file(
            &clone_a.join("skills/review/SKILL.md"),
            "---\ndescription: review a\n---\n# review\n",
        );
        let clone_b = base.join("sources/local/other/repo");
        write_file(
            &clone_b.join("skills/review/SKILL.md"),
            "---\ndescription: review b\n---\n# review\n",
        );

        let paths = paths_for(base);
        let source_a = make_source_for(&clone_a);
        let mut source_b = make_source_for(&clone_b);
        source_b.name = "local/other/repo".to_string();
        source_b.owner = "other".to_string();

        let mut items = Vec::new();
        scan_source(&paths, &source_a, &mut items).unwrap();
        // Scanning B into the same `out` that already holds A's `review` must not
        // be seen as a duplicate.
        scan_source(&paths, &source_b, &mut items)
            .expect("same name in a different source is not a DuplicateItem");
        let reviews = items.iter().filter(|i| i.name == "review").count();
        assert_eq!(reviews, 2, "both sources' review items should be present");
    }

    #[test]
    fn duplicate_across_roots_collides_on_bare_name_under_a_prefix() {
        // spec: DSC-53
        // The duplicate check is on the BARE name, independent of any namespace
        // prefix: two roots each contributing a bare `review` collide even when
        // the source has a prefix/alias (which would prefix both identically).
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("a/skills/review/SKILL.md"),
            "---\ndescription: review a\n---\n# review\n",
        );
        write_file(
            &clone.join("b/skills/review/SKILL.md"),
            "---\ndescription: review b\n---\n# review\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.alias = Some("jk".to_string()); // a namespace prefix is in effect
        source.roots = Some(vec!["a".to_string(), "b".to_string()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::DuplicateItem { ref name, .. } if name == "review"),
            "bare-name collision must error regardless of prefix: {err}"
        );
    }

    #[test]
    fn explicit_empty_roots_list_discovers_nothing() {
        // spec: DSC-50
        // DSC-50 says an UNSET `roots` means a single implicit repo root. An
        // explicitly empty list (`roots = []`) is distinct: it is honored as
        // "scan zero roots", so nothing is discovered. This pins the
        // unset-vs-explicit-empty fork rather than letting [] silently fall back
        // to the repo root. See certification note (spec ambiguity).
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        // A conventional item at the repo root: it WOULD be found by the implicit
        // root, so if [] fell back to the repo root this item would appear.
        write_file(
            &clone.join("skills/review/SKILL.md"),
            "---\ndescription: review\n---\n# review\n",
        );
        write_file(&clone.join("mind.toml"), "[source]\nroots = []\n");

        let paths = paths_for(base);
        let source = make_source_for(&clone);

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        assert!(
            items.is_empty(),
            "an explicit empty roots list scans zero roots: {:?}",
            items.iter().map(|i| i.name.as_str()).collect::<Vec<_>>()
        );
    }

    #[test]
    fn unset_roots_falls_back_to_implicit_repo_root() {
        // spec: DSC-50
        // The counterpart to the empty-list case: with no roots configured at all,
        // discovery scans the repo root (the DSC-10..13 behavior). This is the
        // mutation guard distinguishing `None` (implicit ["."]) from `Some([])`.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/review/SKILL.md"),
            "---\ndescription: review\n---\n# review\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone); // roots: None, no mind.toml

        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(
            names.contains(&"review"),
            "unset roots scans the repo root: {names:?}"
        );
    }

    fn make_test_item(name: &str, description: Option<&str>) -> CatalogItem {
        CatalogItem {
            kind: ItemKind::Skill,
            name: name.to_string(),
            source: "test-source".to_string(),
            prefix: None,
            path: PathBuf::from("/tmp/fake"),
            description: description.map(|s| s.to_string()),
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        }
    }

    #[test]
    fn convention_discovers_bare_tool_dir_without_anchor() {
        // spec: TOOL-1 TOOL-5
        // A `tools/<name>/` directory is a tool with no anchor file; the
        // convention default entrypoint is a file named after the tool.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(&clone.join("tools/detect/detect"), "#!/bin/sh\necho hi\n");
        write_file(&clone.join("tools/detect/lib.sh"), "helper\n");

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let tool = items
            .iter()
            .find(|i| i.name == "detect")
            .expect("tool 'detect' discovered");
        assert_eq!(tool.kind, ItemKind::Tool);
        assert_eq!(tool.resolved_bin().as_deref(), Some("detect"));
    }

    #[test]
    fn tool_metadata_comes_from_optional_tool_md() {
        // spec: TOOL-2 TOOL-5 HOOK-70
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("tools/shard/TOOL.md"),
            "---\ndescription: shard a plan\nbin: shard.py\nbuild: make shard\n---\n# shard\n",
        );
        write_file(&clone.join("tools/shard/shard.py"), "print('x')\n");

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let tool = items.iter().find(|i| i.name == "shard").unwrap();
        assert_eq!(tool.description.as_deref(), Some("shard a plan"));
        // An explicit `bin:` wins over the convention default.
        assert_eq!(tool.resolved_bin().as_deref(), Some("shard.py"));
        // HOOK-70: the per-item build command is read from TOOL.md frontmatter.
        assert_eq!(tool.build.as_deref(), Some("make shard"));
    }

    #[test]
    fn resolved_bin_convention_default_requires_the_file() {
        // spec: TOOL-5
        // With no declared bin and no `tools/<name>/<name>` file present, there is
        // no resolvable entrypoint.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let dir = base.join("tools/empty");
        std::fs::create_dir_all(&dir).unwrap();
        let item = CatalogItem {
            kind: ItemKind::Tool,
            name: "empty".to_string(),
            source: "s".to_string(),
            prefix: None,
            path: dir,
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        };
        assert_eq!(item.resolved_bin(), None);
    }

    #[test]
    fn is_safe_item_name_rejects_traversal_and_separators() {
        // spec: DSC-71
        for ok in ["x", "my-skill", "a.b", "review2"] {
            assert!(is_safe_item_name(ok), "{ok:?} should be accepted");
        }
        for bad in ["", ".", "..", "a/b", "../x", "/etc", "a\\b", "x\0y"] {
            assert!(!is_safe_item_name(bad), "{bad:?} should be rejected");
        }
    }

    #[test]
    fn is_safe_link_rel_rejects_escape() {
        // spec: DSC-72
        for ok in ["rules/x.md", "skills/x", "commands/x.toml", "./a/b.md"] {
            assert!(is_safe_link_rel(ok), "{ok:?} should be accepted");
        }
        for bad in [
            "",
            "../../.bashrc",
            "/etc/passwd",
            "~/x",
            "a/../../b",
            "x\0y",
        ] {
            assert!(!is_safe_link_rel(bad), "{bad:?} should be rejected");
        }
    }

    #[test]
    fn from_decl_rejects_unsafe_name() {
        // spec: DSC-71
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = ItemDecl {
            kind: "rule".to_string(),
            name: "../../evil".to_string(),
            path: "rules/x.md".to_string(),
            link: None,
            description: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            hooks: Vec::new(),
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "an unsafe item name must be a schema error: {err}"
        );
    }

    #[test]
    fn from_decl_rejects_escaping_link() {
        // spec: DSC-72
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = ItemDecl {
            kind: "rule".to_string(),
            name: "x".to_string(),
            path: "rules/x.md".to_string(),
            link: Some("../../.bashrc".to_string()),
            description: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            hooks: Vec::new(),
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "an escaping link override must be a schema error: {err}"
        );
    }

    #[test]
    fn from_decl_rejects_bin_or_build_on_non_tool() {
        // spec: TOOL-7
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(&root.join("skills/x/SKILL.md"), "---\n---\n# x\n");
        let source = make_source_for(root);
        let decl = ItemDecl {
            kind: "skill".to_string(),
            name: "x".to_string(),
            path: "skills/x".to_string(),
            link: None,
            description: None,
            bin: Some("x".to_string()),
            build: None,
            install: None,
            uninstall: None,
            hooks: Vec::new(),
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "bin on a non-tool must be a schema error: {err}"
        );
    }

    #[test]
    fn discover_tools_glob_matches_the_directory() {
        // spec: TOOL-7
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(&clone.join("pkgs/detect/tool/detect"), "#!/bin/sh\n");
        write_file(
            &clone.join("mind.toml"),
            "[discover]\ntools = { include = [\"pkgs/*/tool\"] }\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        let tool = items.iter().find(|i| i.name == "tool").unwrap();
        assert_eq!(tool.kind, ItemKind::Tool);
    }

    #[test]
    fn empty_query_matches_all() {
        // spec: CLI-85
        let item = make_test_item("review", Some("Review the diff for bugs"));
        assert!(matches_query(&item, ""));
    }

    #[test]
    fn matches_by_effective_name() {
        // spec: CLI-85
        let item = make_test_item("review", Some("Review the diff for bugs"));
        assert!(matches_query(&item, "review"));
    }

    #[test]
    fn matches_by_description_when_name_does_not_contain_query() {
        // spec: CLI-85
        // "bugs" is only in the description, not the name
        let item = make_test_item("review", Some("Review the diff for bugs"));
        assert!(!item.effective_name().contains("bugs"));
        assert!(matches_query(&item, "bugs"));
    }

    #[test]
    fn match_is_case_insensitive_on_name() {
        // spec: CLI-85
        let item = make_test_item("Review", None);
        assert!(matches_query(&item, "REVIEW"));
        assert!(matches_query(&item, "review"));
        assert!(matches_query(&item, "ReViEw"));
    }

    #[test]
    fn match_is_case_insensitive_on_description() {
        // spec: CLI-85
        let item = make_test_item("x", Some("Implements a Spec with Tests"));
        assert!(matches_query(&item, "SPEC"));
        assert!(matches_query(&item, "spec"));
    }

    #[test]
    fn no_match_when_query_absent_from_both_name_and_description() {
        // spec: CLI-85
        let item = make_test_item("review", Some("Review the diff for bugs"));
        assert!(!matches_query(&item, "python"));
    }

    #[test]
    fn no_match_when_description_is_none_and_name_does_not_match() {
        // spec: CLI-85
        let item = make_test_item("review", None);
        assert!(!matches_query(&item, "bugs"));
    }

    #[test]
    fn empty_description_does_not_match_a_nonempty_query() {
        // spec: CLI-85
        // Some("") is distinct from None: an empty description string must not
        // spuriously match a non-empty query (it would if `contains` were
        // reasoned about backwards). The empty *query* still matches (all),
        // but a non-empty query against an empty description must not.
        let item = make_test_item("x", Some(""));
        assert!(matches_query(&item, ""));
        assert!(!matches_query(&item, "anything"));
    }

    #[test]
    fn whitespace_query_matches_a_description_that_contains_whitespace() {
        // spec: CLI-85
        // A non-empty query is a raw substring; it is not trimmed. A query of a
        // single space matches a description containing a space but a name that
        // has none.
        let item = make_test_item("review", Some("Review the diff"));
        assert!(!item.effective_name().contains(' '));
        assert!(matches_query(&item, " "));
    }

    #[test]
    fn substring_in_middle_of_word_matches() {
        // spec: CLI-85
        // Matching is substring, not word-boundary: a fragment inside a longer
        // word matches both in the name and in the description.
        let by_name = make_test_item("refactor", None);
        assert!(matches_query(&by_name, "factor"));
        let by_desc = make_test_item("x", Some("Performs refactoring"));
        assert!(matches_query(&by_desc, "factor"));
    }

    #[test]
    fn prefix_is_used_in_effective_name_match() {
        // spec: CLI-85
        let mut item = make_test_item("review", None);
        item.prefix = Some("jk".to_string());
        // effective_name() is "jk:review"
        assert!(matches_query(&item, "jk:review"));
        assert!(matches_query(&item, "jk"));
        // "review" is a substring of "jk:review", so it also matches
        assert!(matches_query(&item, "review"));
    }

    // ---- DEP-4: `requires:` frontmatter field populated from scan ----------

    #[test]
    fn requires_field_parsed_from_skill_frontmatter() {
        // spec: DEP-4
        // A `requires:` key in SKILL.md is read as a whitespace-split Vec.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/review/SKILL.md"),
            "---\ndescription: review\nrequires: skill:plan agent:test\n---\n# review\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items.iter().find(|i| i.name == "review").unwrap();
        assert_eq!(
            skill.requires,
            vec!["skill:plan".to_string(), "agent:test".to_string()],
            "requires must be whitespace-split from the frontmatter scalar"
        );
    }

    #[test]
    fn requires_field_absent_is_empty_vec() {
        // spec: DEP-4
        // When `requires:` is not present, the field is an empty Vec.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/review/SKILL.md"),
            "---\ndescription: review\n---\n# review\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items.iter().find(|i| i.name == "review").unwrap();
        assert!(
            skill.requires.is_empty(),
            "absent requires must yield empty Vec"
        );
    }

    #[test]
    fn requires_field_parsed_from_agent_frontmatter() {
        // spec: DEP-4
        // `requires:` works on an agent file, not just skills.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("agents/dev.md"),
            "---\ndescription: dev\nrequires: rule:style\n---\n# dev\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let agent = items.iter().find(|i| i.name == "dev").unwrap();
        assert_eq!(agent.requires, vec!["rule:style".to_string()],);
    }

    // ---- DSC-73: [[items]] path traversal guard ----------------------------

    #[test]
    fn from_decl_rejects_dotdot_path() {
        // spec: DSC-71 DSC-72 DSC-73
        // A [[items]] `path` with a `..` component must be rejected as MindToml
        // before root.join() can escape the clone. Without the guard,
        // root.join("../escape") silently resolves outside the clone.
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = crate::mindfile::ItemDecl {
            kind: "rule".to_string(),
            name: "evil".to_string(),
            path: "../escape".to_string(),
            link: None,
            description: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            hooks: Vec::new(),
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "a dotdot path must be a schema error: {err}"
        );
    }

    #[test]
    fn from_decl_rejects_absolute_path() {
        // spec: DSC-71 DSC-72 DSC-73
        // An absolute `path` (e.g. "/etc/passwd") is rejected as MindToml.
        // Rust's Path::join with an absolute operand discards `root` entirely,
        // so without this guard the install would copy from an arbitrary host path.
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = crate::mindfile::ItemDecl {
            kind: "rule".to_string(),
            name: "evil".to_string(),
            path: "/etc/passwd".to_string(),
            link: None,
            description: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            hooks: Vec::new(),
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "an absolute path must be a schema error: {err}"
        );
    }

    #[test]
    fn from_decl_accepts_subdir_path() {
        // spec: DSC-73
        // A path with in-bounds subdirectories is accepted; subdirectories are
        // legitimate (a source can organize items below the repo root).
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = crate::mindfile::ItemDecl {
            kind: "rule".to_string(),
            name: "style".to_string(),
            path: "sub/dir/style.md".to_string(),
            link: None,
            description: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            hooks: Vec::new(),
        };
        // The file need not exist; frontmatter reads return None for absent files.
        let item = from_decl(root, &source, &None, &decl).unwrap();
        assert_eq!(item.name, "style");
        assert_eq!(item.path, root.join("sub/dir/style.md"));
    }

    // ---- DSC-53 (authoritative branch): [[items]] duplicate guard ----------

    #[test]
    fn authoritative_mind_toml_duplicate_items_is_duplicate_item_error() {
        // spec: DSC-53
        // Two [[items]] entries with the same kind+name in one mind.toml must
        // be a DuplicateItem error, enforcing the (source, kind, bare_name)
        // identity invariant in the authoritative branch.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("rules/style.md"),
            "---\ndescription: style\n---\n",
        );
        write_file(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"rules/style.md\"\n",
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"rules/style.md\"\n",
            ),
        );
        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::DuplicateItem { ref name, .. } if name == "style"),
            "duplicate [[items]] entries must be DuplicateItem: {err}"
        );
    }

    // ---- agent_harness_name tests (NS-40) ----

    /// Build a minimal `CatalogItem` pointing at a given file for testing
    /// `agent_harness_name()`.
    fn agent_item(path: std::path::PathBuf, bare_name: &str) -> CatalogItem {
        CatalogItem {
            source: "src".to_string(),
            kind: ItemKind::Agent,
            name: bare_name.to_string(),
            prefix: None,
            path,
            description: None,
            link_rel: None,
            bin: None,
            build: None,
            install: None,
            uninstall: None,
            requires: Vec::new(),
            hooks: Vec::new(),
        }
    }

    #[test]
    fn agent_harness_name_reads_frontmatter_name() {
        // spec: NS-40 -- the harness name comes from the frontmatter `name:` field,
        // not the file stem.
        let dir = TmpDir::new();
        let p = dir.path().join("agents/coder.md");
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, "---\nname: dev\ndescription: d\n---\n# dev\n").unwrap();
        let item = agent_item(p, "coder");
        // bare catalog name is "coder", but frontmatter says "dev".
        assert_eq!(item.agent_harness_name(), Some("dev".to_string()));
    }

    #[test]
    fn agent_harness_name_falls_back_to_bare_name_when_frontmatter_absent() {
        // spec: NS-40 -- if there is no frontmatter name, fall back to the bare
        // catalog name (file stem).
        let dir = TmpDir::new();
        let p = dir.path().join("agents/coder.md");
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, "---\ndescription: d\n---\n# coder\n").unwrap();
        let item = agent_item(p, "coder");
        assert_eq!(item.agent_harness_name(), Some("coder".to_string()));
    }

    #[test]
    fn agent_harness_name_rejects_unsafe_frontmatter_name() {
        // spec: NS-40 -- a frontmatter `name:` that is not a safe path component
        // is ignored and the bare catalog name is used instead.
        let dir = TmpDir::new();
        let p = dir.path().join("agents/coder.md");
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, "---\nname: ../evil\ndescription: d\n---\n# coder\n").unwrap();
        let item = agent_item(p, "coder");
        // unsafe name is rejected; falls back to catalog name.
        assert_eq!(item.agent_harness_name(), Some("coder".to_string()));
    }

    #[test]
    fn agent_harness_name_returns_none_for_non_agents() {
        // spec: NS-40 -- only the Agent kind has a harness name.
        let dir = TmpDir::new();
        let p = dir.path().join("skills/review/SKILL.md");
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(&p, "---\nname: review\n---\n").unwrap();
        let mut item = agent_item(p, "review");
        item.kind = ItemKind::Skill;
        assert_eq!(item.agent_harness_name(), None);
    }
}

/// Plugin-manifest discovery tests (MKT-1..6).
/// Note: spec IDs are added in tests/cli.rs (shard 5); these are unit tests only.
#[cfg(test)]
mod plugin_tests {
    use super::*;
    use crate::paths::Paths;
    use crate::source::{Pin, Source};
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicU32, Ordering};

    static PLUGIN_COUNTER: AtomicU32 = AtomicU32::new(0);

    struct TmpDir(PathBuf);
    impl TmpDir {
        fn new() -> Self {
            let n = PLUGIN_COUNTER.fetch_add(1, Ordering::SeqCst);
            let p = std::env::temp_dir()
                .join(format!("mind-catalog-plugin-{}-{n}", std::process::id()));
            let _ = std::fs::remove_dir_all(&p);
            std::fs::create_dir_all(&p).unwrap();
            TmpDir(p)
        }
        fn path(&self) -> &std::path::Path {
            &self.0
        }
    }
    impl Drop for TmpDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    fn write_file(path: &std::path::Path, contents: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, contents).unwrap();
    }

    fn make_plugin_source(clone: &std::path::Path) -> Source {
        Source {
            name: "local/test/plugin-repo".to_string(),
            url: clone.to_string_lossy().into_owned(),
            host: "local".to_string(),
            owner: "test".to_string(),
            repo: "plugin-repo".to_string(),
            commit: None,
            description: None,
            alias: None,
            pin: Pin::default(),
            roots: None,
            flat_skills: false,
            origin: None,
            plugin_version: None,
            install_hooks: Vec::new(),
            install_hook: None,
            install_hook_commit: None,
        }
    }

    fn paths_for(base: &std::path::Path) -> Paths {
        Paths {
            mind_home: base.to_path_buf(),
            claude_home: base.join("claude"),
        }
    }

    // Plugin.json with skill + agent is discovered; prefix from plugin name (MKT-1, MKT-3, MKT-5).
    // Agent uses NS-40 harness-name from frontmatter. No rules or tools.
    #[test]
    fn plugin_json_discovers_skill_and_agent_with_plugin_name_prefix() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme","version":"1.0","description":"Acme plugin"}"#,
        );
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo skill\n---\n# foo\n",
        );
        // Agent with a distinct frontmatter name (NS-40 flattening)
        write_file(
            &clone.join("agents/bar.md"),
            "---\nname: bar-agent\ndescription: bar agent\n---\n# bar\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        // Skill: bare name "foo", effective name "acme:foo"
        let skill = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .expect("skill 'foo' must be discovered from plugin");
        assert_eq!(
            skill.effective_name(),
            "acme:foo",
            "skill must carry plugin name as prefix (MKT-5)"
        );
        assert_eq!(skill.prefix.as_deref(), Some("acme"));

        // Agent: bare catalog name "bar" (file stem), harness name from frontmatter
        let agent = items
            .iter()
            .find(|i| i.kind == ItemKind::Agent && i.name == "bar")
            .expect("agent 'bar' must be discovered from plugin");
        assert_eq!(
            agent.agent_harness_name(),
            Some("bar-agent".to_string()),
            "agent harness name must come from frontmatter `name:` field (NS-40)"
        );

        // No rules or tools from a plugin (MKT-3)
        assert!(
            !items.iter().any(|i| i.kind == ItemKind::Rule),
            "no rules must be emitted from a plugin (MKT-3)"
        );
        assert!(
            !items.iter().any(|i| i.kind == ItemKind::Tool),
            "no tools must be emitted from a plugin (MKT-3)"
        );
    }

    // A plugin that ships rules/ and tools/ dirs at its root: those kinds have no
    // plugin equivalent and must NOT be emitted (MKT-3). The existing discovery
    // test asserts "no rules/tools" but its fixture has no such dirs, so it would
    // pass even if the scan wrongly emitted them. This test creates real rules/ and
    // tools/ trees to make the negative assertion load-bearing.
    #[test]
    fn plugin_rules_and_tools_dirs_present_are_not_emitted() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme"}"#,
        );
        // A supported skill so the scan produces at least one item.
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );
        // A rules/ dir with a well-formed rule that convention discovery WOULD emit.
        write_file(
            &clone.join("rules/housestyle.md"),
            "---\ndescription: a rule\n---\n# housestyle\n",
        );
        // A tools/ dir with a tool that convention discovery WOULD emit.
        write_file(&clone.join("tools/helper/helper"), "#!/bin/sh\n");
        write_file(
            &clone.join("tools/helper/TOOL.md"),
            "---\ndescription: a tool\n---\n# helper\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        assert!(
            items
                .iter()
                .any(|i| i.kind == ItemKind::Skill && i.name == "foo"),
            "the plugin's skill must still be discovered"
        );
        assert!(
            !items.iter().any(|i| i.kind == ItemKind::Rule),
            "a rules/ dir at a plugin root must NOT be emitted (MKT-3): {:?}",
            items
                .iter()
                .map(|i| (i.kind, i.name.as_str()))
                .collect::<Vec<_>>()
        );
        assert!(
            !items.iter().any(|i| i.kind == ItemKind::Tool),
            "a tools/ dir at a plugin root must NOT be emitted (MKT-3): {:?}",
            items
                .iter()
                .map(|i| (i.kind, i.name.as_str()))
                .collect::<Vec<_>>()
        );
    }

    // A plugin agent WITHOUT a frontmatter `name:` flattens to its file stem as
    // the harness name (NS-40). The existing discovery test only covers an agent
    // that DOES carry a frontmatter name, so the fallback branch on the plugin
    // path was untested.
    #[test]
    fn plugin_agent_without_frontmatter_name_flattens_to_file_stem() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme"}"#,
        );
        // Agent file `agents/nameless.md` with NO `name:` key in its frontmatter.
        write_file(
            &clone.join("agents/nameless.md"),
            "---\ndescription: an agent with no name field\n---\n# nameless\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let agent = items
            .iter()
            .find(|i| i.kind == ItemKind::Agent && i.name == "nameless")
            .expect("plugin agent 'nameless' must be discovered");
        assert_eq!(
            agent.agent_harness_name(),
            Some("nameless".to_string()),
            "an agent with no frontmatter name must flatten to its file stem (NS-40)"
        );
    }

    // Consumer alias overrides the plugin name as the effective prefix (MKT-5).
    #[test]
    fn consumer_alias_overrides_plugin_name_as_prefix() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme"}"#,
        );
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );

        let paths = paths_for(base);
        let mut source = make_plugin_source(&clone);
        source.alias = Some("z".to_string());
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items.iter().find(|i| i.name == "foo").unwrap();
        assert_eq!(
            skill.effective_name(),
            "z:foo",
            "consumer alias must override plugin name as prefix (MKT-5)"
        );
    }

    // Explicitly cleared alias (Some("")) yields no prefix, overriding plugin name (MKT-5).
    #[test]
    fn cleared_alias_yields_no_prefix_overriding_plugin_name() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme"}"#,
        );
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );

        let paths = paths_for(base);
        let mut source = make_plugin_source(&clone);
        source.alias = Some(String::new()); // explicit empty = clear prefix
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items.iter().find(|i| i.name == "foo").unwrap();
        assert_eq!(
            skill.effective_name(),
            "foo",
            "an explicitly-cleared alias must suppress the plugin name prefix"
        );
        assert!(
            skill.prefix.is_none(),
            "prefix must be None when alias was cleared"
        );
    }

    // A [source]-only mind.toml alongside plugin.json: its prefix participates,
    // and items still come from the plugin (not convention). (MKT-2)
    #[test]
    fn source_only_mind_toml_prefix_participates_with_plugin_json() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme"}"#,
        );
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("agents/bar.md"),
            "---\ndescription: bar\n---\n# bar\n",
        );
        // [source]-only mind.toml: no [[items]] or [discover], just [source].prefix
        write_file(&clone.join("mind.toml"), "[source]\nprefix = \"mp\"\n");
        // Also place a conventional rule that would normally be found by convention scan
        // but must NOT appear (plugin defines the items)
        write_file(
            &clone.join("rules/should-not-appear.md"),
            "---\ndescription: nope\n---\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        // [source].prefix "mp" overrides plugin name "acme"
        let skill = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .expect("skill from plugin must be present");
        assert_eq!(
            skill.effective_name(),
            "mp:foo",
            "mind.toml [source].prefix must win over plugin name"
        );

        // Convention scan was skipped (rule not present)
        assert!(
            !items.iter().any(|i| i.name == "should-not-appear"),
            "convention scan must be skipped when plugin.json is present"
        );
    }

    // Authoritative mind.toml (with [[items]]) alongside plugin.json: plugin is suppressed (MKT-2).
    #[test]
    fn authoritative_mind_toml_suppresses_plugin_json() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // Plugin with a skill
        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"acme"}"#,
        );
        write_file(
            &clone.join("skills/plugin-skill/SKILL.md"),
            "---\ndescription: from plugin\n---\n",
        );
        // Authoritative mind.toml declares a different item
        write_file(
            &clone.join("rules/my-rule.md"),
            "---\ndescription: my rule\n---\n",
        );
        write_file(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"my-rule\"\n",
                "path = \"rules/my-rule.md\"\n",
            ),
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        // Only the mind.toml-declared item; plugin skill must NOT appear
        assert_eq!(
            items.len(),
            1,
            "authoritative mind.toml must suppress plugin.json (MKT-2); got: {:?}",
            items
                .iter()
                .map(|i| (i.kind, i.name.as_str()))
                .collect::<Vec<_>>()
        );
        assert_eq!(items[0].name, "my-rule");
        assert!(
            items.iter().all(|i| i.kind != ItemKind::Skill),
            "plugin skill must not appear when authoritative mind.toml is present"
        );
    }

    // Malformed plugin.json is propagated as a MindToml scan error (MKT-9).
    #[test]
    fn malformed_plugin_json_is_scan_error() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{not valid json"#,
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "malformed plugin.json must propagate as MindToml error (MKT-9): {err:?}"
        );
    }

    // plugin_skipped_components counts commands/ and hooks/ dirs (MKT-4).
    #[test]
    fn plugin_skipped_components_counts_unsupported_dirs() {
        let tmp = TmpDir::new();
        let plugin_root = tmp.path().join("my-plugin");

        std::fs::create_dir_all(plugin_root.join("commands")).unwrap();
        std::fs::create_dir_all(plugin_root.join("hooks")).unwrap();

        let skipped = plugin_skipped_components(&plugin_root);
        assert!(
            skipped.commands > 0,
            "commands/ dir must be counted as skipped"
        );
        assert!(skipped.hooks > 0, "hooks/ dir must be counted as skipped");
        assert!(
            skipped.total() >= 2,
            "at least 2 skipped components: {:?}",
            skipped
        );
    }

    // ---------------------------------------------------------------------------
    // Marketplace in-repo scan tests (MKT-14)
    // ---------------------------------------------------------------------------

    // Two in-repo entries with explicit `skills` arrays each discover only their
    // listed skill dirs, namespaced under their respective entry names.
    #[test]
    fn marketplace_in_repo_with_skills_array_scans_explicit_skill_dirs() {
        // spec: MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // marketplace.json: two entries both pointing at "./" (the repo root),
        // each with an explicit skills array.
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Acme Market",
                "plugins": [
                    {"name": "p1", "source": "./", "skills": ["./skills/foo"]},
                    {"name": "p2", "source": "./", "skills": ["./skills/bar"]}
                ]
            }"#,
        );
        // Skill dirs at the repo root (plugin_root = clone_root for "./").
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo skill\n---\n# foo\n",
        );
        write_file(
            &clone.join("skills/bar/SKILL.md"),
            "---\ndescription: bar skill\n---\n# bar\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        // foo should appear under p1's prefix.
        let foo = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .expect("skill 'foo' must be discovered from marketplace entry p1");
        assert_eq!(
            foo.effective_name(),
            "p1:foo",
            "foo must carry entry name 'p1' as prefix (MKT-14)"
        );

        // bar should appear under p2's prefix.
        let bar = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "bar")
            .expect("skill 'bar' must be discovered from marketplace entry p2");
        assert_eq!(
            bar.effective_name(),
            "p2:bar",
            "bar must carry entry name 'p2' as prefix (MKT-14)"
        );
    }

    // An in-repo entry with no `skills` array falls back to conventional skills/
    // directory scanning within the plugin root.
    #[test]
    fn marketplace_in_repo_without_skills_array_falls_back_to_convention_scan() {
        // spec: MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // One entry with source "./" and no skills field.
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Acme Market",
                "plugins": [
                    {"name": "p1", "source": "./"}
                ]
            }"#,
        );
        // Skill baz should be discovered via conventional skills/ scan.
        write_file(
            &clone.join("skills/baz/SKILL.md"),
            "---\ndescription: baz skill\n---\n# baz\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let baz = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "baz")
            .expect(
                "skill 'baz' must be discovered via conventional scan when skills array is absent",
            );
        assert_eq!(
            baz.effective_name(),
            "p1:baz",
            "baz must carry entry name 'p1' as prefix (MKT-14)"
        );
    }

    // An explicit `skills` array limits scanning to only the listed dirs; skills
    // present in skills/ but not in the array must NOT be discovered (no double-count).
    #[test]
    fn marketplace_in_repo_skills_array_does_not_double_count() {
        // spec: MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // Entry lists only ./skills/foo; skills/qux also exists but must be excluded.
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Acme Market",
                "plugins": [
                    {"name": "p1", "source": "./", "skills": ["./skills/foo"]}
                ]
            }"#,
        );
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo skill\n---\n# foo\n",
        );
        // qux is in skills/ but NOT in the skills array.
        write_file(
            &clone.join("skills/qux/SKILL.md"),
            "---\ndescription: qux skill\n---\n# qux\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        // foo is discovered.
        assert!(
            items
                .iter()
                .any(|i| i.kind == ItemKind::Skill && i.name == "foo"),
            "skill 'foo' must be discovered (it is in the skills array)"
        );
        // qux is NOT discovered (not in the skills array; conventional scan bypassed).
        assert!(
            !items
                .iter()
                .any(|i| i.kind == ItemKind::Skill && i.name == "qux"),
            "skill 'qux' must NOT be discovered when it is absent from the skills array (MKT-14)"
        );
    }

    // Plugin whose name is a reserved kind word (e.g. "skill") falls back to no
    // prefix rather than erroring -- resilience over strict enforcement (NS-25, MKT-5).
    #[test]
    fn plugin_with_reserved_kind_name_falls_back_to_no_prefix() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // Plugin named "skill" -- a reserved kind word per NS-25
        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            r#"{"name":"skill"}"#,
        );
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        // Must NOT error; reserved kind word is silently skipped as prefix
        scan_source(&paths, &source, &mut items)
            .expect("a plugin named with a reserved kind word must not fail scan");

        let skill = items.iter().find(|i| i.name == "foo").unwrap();
        assert_eq!(
            skill.effective_name(),
            "foo",
            "reserved kind word as plugin name must fall through to no prefix"
        );
        assert!(
            skill.prefix.is_none(),
            "prefix must be None when plugin name is a reserved kind word"
        );
    }

    // ---------------------------------------------------------------------------
    // H4: Path-traversal guard in scan_marketplace_in_repo_plugins (MKT-14, MKT-9)
    // ---------------------------------------------------------------------------

    // A marketplace entry whose `source` path is a symlink that points outside the
    // clone root must be skipped silently -- no items, no error.
    #[test]
    fn marketplace_symlink_outside_clone_is_skipped() {
        // spec: MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // An "outside" directory with a skill that should NOT be discovered.
        let outside = base.join("outside-clone");
        write_file(
            &outside.join("skills/secret/SKILL.md"),
            "---\ndescription: secret\n---\n",
        );

        // Create the clone root and a symlink `clone/external` -> `../outside-clone`.
        std::fs::create_dir_all(clone.join(".claude-plugin")).unwrap();
        #[cfg(unix)]
        std::os::unix::fs::symlink(&outside, clone.join("external")).unwrap();
        // On non-Unix platforms, skip this test by writing no marketplace.json so
        // the scan yields zero items but doesn't fail.
        #[cfg(not(unix))]
        {
            return;
        }

        // marketplace.json declares an in-repo entry pointing at the symlink.
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Acme Market",
                "plugins": [
                    {"name": "escape", "source": "external"}
                ]
            }"#,
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        // Must not error; must not discover the skill outside the clone.
        scan_source(&paths, &source, &mut items)
            .expect("path-traversal via symlink must be skipped, not errored");
        assert!(
            !items.iter().any(|i| i.name == "secret"),
            "skill behind a symlink escaping the clone must NOT be discovered (MKT-14, MKT-9)"
        );
    }

    // ---------------------------------------------------------------------------
    // H5 / M13: per-plugin namespacing when has_explicit_prefix=true (MKT-13)
    // ---------------------------------------------------------------------------

    // No explicit consumer override: entry name is used as the default prefix (MKT-8).
    // Verifies the pre-existing baseline still passes after the H5 refactor.
    #[test]
    fn marketplace_no_override_uses_entry_name_as_prefix() {
        // spec: MKT-14 MKT-13
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Market",
                "plugins": [
                    {"name": "myplugin", "source": "./", "skills": ["./skills/alpha"]}
                ]
            }"#,
        );
        write_file(
            &clone.join("skills/alpha/SKILL.md"),
            "---\ndescription: alpha\n---\n",
        );

        // No alias set -> no explicit override.
        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "alpha")
            .expect("skill 'alpha' must be discovered");
        assert_eq!(
            skill.effective_name(),
            "myplugin:alpha",
            "entry name must be the default prefix when no consumer override is set (MKT-8)"
        );
    }

    // Explicit outer prefix set (Some("outer")): items are named outer:entry:skill.
    #[test]
    fn marketplace_outer_prefix_combines_with_entry_name() {
        // spec: MKT-14 MKT-13
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Market",
                "plugins": [
                    {"name": "myplugin", "source": "./", "skills": ["./skills/beta"]}
                ]
            }"#,
        );
        write_file(
            &clone.join("skills/beta/SKILL.md"),
            "---\ndescription: beta\n---\n",
        );

        // Set alias "outer" -> has_explicit_prefix=true, outer_prefix=Some("outer").
        let paths = paths_for(base);
        let mut source = make_plugin_source(&clone);
        source.alias = Some("outer".to_string());
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "beta")
            .expect("skill 'beta' must be discovered");
        assert_eq!(
            skill.effective_name(),
            "outer:myplugin:beta",
            "outer prefix and entry name must combine (MKT-13): outer:entry:item"
        );
    }

    // Explicit empty prefix (namespace=""): outer prefix cleared but per-plugin
    // entry-name prefix remains intact (MKT-13).
    #[test]
    fn marketplace_cleared_outer_prefix_keeps_entry_name_prefix() {
        // spec: MKT-14 MKT-13
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Market",
                "plugins": [
                    {"name": "myplugin", "source": "./", "skills": ["./skills/gamma"]}
                ]
            }"#,
        );
        write_file(
            &clone.join("skills/gamma/SKILL.md"),
            "---\ndescription: gamma\n---\n",
        );

        // alias = Some("") -> has_explicit_prefix=true, outer_prefix=None (cleared).
        let paths = paths_for(base);
        let mut source = make_plugin_source(&clone);
        source.alias = Some(String::new());
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "gamma")
            .expect("skill 'gamma' must be discovered");
        assert_eq!(
            skill.effective_name(),
            "myplugin:gamma",
            "cleared outer prefix must leave per-plugin entry-name prefix intact (MKT-13)"
        );
    }

    // ---------------------------------------------------------------------------
    // M5a: ANSI stripping of entry.name before use as prefix (MKT-14)
    // ---------------------------------------------------------------------------

    // An entry whose name contains ANSI escape sequences must produce a clean prefix.
    #[test]
    fn marketplace_entry_name_with_ansi_produces_clean_prefix() {
        // spec: MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // Entry name with embedded ANSI bold sequence: "\x1b[1mplugin\x1b[0m"
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            "{\"name\":\"Market\",\"plugins\":[{\"name\":\"\\u001b[1mplugin\\u001b[0m\",\"source\":\"./\",\"skills\":[\"./skills/delta\"]}]}",
        );
        write_file(
            &clone.join("skills/delta/SKILL.md"),
            "---\ndescription: delta\n---\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let skill = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "delta")
            .expect("skill 'delta' must be discovered");
        // The effective prefix must be "plugin" with ANSI stripped, not the raw ANSI string.
        assert_eq!(
            skill.effective_name(),
            "plugin:delta",
            "ANSI sequences in entry.name must be stripped before use as prefix (MKT-14)"
        );
        // The raw ANSI sequence must NOT appear in the prefix.
        assert!(
            !skill.prefix.as_deref().unwrap_or("").contains('\x1b'),
            "prefix must not contain raw ANSI escape (\\x1b) after stripping"
        );
        // Positive check: prefix is the clean "plugin".
        assert_eq!(
            skill.prefix.as_deref(),
            Some("plugin"),
            "prefix must be 'plugin' after stripping ANSI escapes"
        );
    }

    // ---------------------------------------------------------------------------
    // M12: Agent scanning in scan_marketplace_in_repo_plugins (MKT-14)
    // ---------------------------------------------------------------------------

    // A marketplace in-repo entry with no `skills` array and an agent markdown file
    // must discover the agent as ItemKind::Agent.
    #[test]
    fn marketplace_in_repo_entry_discovers_agents() {
        // spec: MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // Entry points at "./" with no skills array; place an agent file.
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Acme Market",
                "plugins": [
                    {"name": "acme", "source": "./"}
                ]
            }"#,
        );
        write_file(
            &clone.join("agents/myagent.md"),
            "---\ndescription: my agent\n---\n# myagent\n",
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let agent = items
            .iter()
            .find(|i| i.kind == ItemKind::Agent && i.name == "myagent")
            .expect("agent 'myagent' must be discovered from marketplace in-repo entry");
        assert_eq!(
            agent.effective_name(),
            "acme:myagent",
            "agent must be namespaced under its marketplace entry name (MKT-14)"
        );
    }
}