mind-cli 0.47.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
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
//! 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>`
//! - `commands/<name>.md`      -> command `<name>`
//! - `tools/<name>/`           -> tool    `<name>` (no anchor file required)
//!
//! 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::sanitize::ItemKey;
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. For a
    /// workflow it comes from the `meta` object instead, a `.js` file having no
    /// frontmatter (WF-4).
    pub description: Option<String>,
    /// A workflow's `meta.whenToUse` (WF-5), shown beside the description
    /// wherever an item's description is shown (WF-51). `None` for every other
    /// kind, and for a workflow that declares none.
    ///
    /// A field of its own rather than something folded into `description` at
    /// scan time: a `mind.toml` `[[items]].description` override (DSC-32)
    /// replaces the description and leaves this standing, which folding would
    /// make impossible to express. Display-only -- it is not recorded in the
    /// manifest, and `dump` does not emit it.
    pub when_to_use: 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>,
    /// 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 effective ignore patterns (IGN-1), resolved at scan: the
    /// item's own `[[items]].ignore` when it declared one, else the source's
    /// `[source].ignore`. `None` until [`resolve_ignores`] fills it in, which
    /// `scan_source_at` does for every item it produces; read it through
    /// [`CatalogItem::ignore_set`] rather than directly, so the built-in VCS
    /// set (IGN-2) is never accidentally skipped.
    pub ignore: Option<Vec<String>>,
    /// Item-relative file paths opted into token expansion via the frontmatter
    /// `expand:` key (NS-57). Whitespace-split raw strings as written, e.g.
    /// `["resources/pr.py"]`. At install these non-markdown files are expanded
    /// like markdown, with path tokens rendered absolute (TOOL-20). Empty when
    /// absent.
    pub expand: Vec<String>,
    /// The item's full resolved lifecycle hooks (HOOK-86, HOOK-132), in
    /// execution order, from whichever ONE declaration site supplied them: a
    /// root `mind.toml` `[[items]]` entry (its scalar `install`/`update`/
    /// `uninstall` shorthand folded in ahead of its `[[items.hooks]]` array),
    /// else the item directory's own `mind.toml` `[[hooks]]` (HOOK-131), else
    /// the item's frontmatter scalars (HOOK-130). The sites do not merge, so
    /// this list always matches something as written in the source. Every
    /// consumer reads hooks from here: execution, `mind review` (HOOK-134), and
    /// `hooks list`.
    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)
    }

    /// Whether this item's UNPREFIXED source spelled a namespace into its bare
    /// name (DSC-99).
    ///
    /// A prefix component may not contain `:` (`namespace::is_safe_prefix_component`,
    /// NS-72), but an item name may: commands.md CMD-2/CMD-6 recommend the
    /// spelling for a command group (`commands/frontend:build.md`), so the
    /// character cannot be banned. The consequence is that an unprefixed source
    /// shipping `commands/acme:deploy.md` installs `acme:deploy`, which reads
    /// exactly like `deploy` from a source prefixed `acme`. This predicate is
    /// the detection the identity itself cannot provide; it is pure, and the
    /// verbs that decide trust (`meld`, `learn`, `review`) are what report it.
    ///
    /// spec: DSC-99
    pub fn forges_namespace(&self) -> bool {
        self.prefix.is_none() && self.name.contains(':')
    }

    /// 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 Ok(text) = frontmatter::text_capped(&self.path)
            && let Some(fm_name) = frontmatter::field(&text, "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 update hooks (HOOK-120, HOOK-125), in execution
    /// order: what runs in place of the install hooks when the item is
    /// re-installed over an existing install.
    // spec: HOOK-125
    pub fn update_hooks(&self) -> Vec<&ResolvedHook> {
        self.hooks
            .iter()
            .filter(|h| h.event == HookEvent::Update)
            .collect()
    }

    /// The hooks to run when installing this item: its update hooks when this
    /// is a re-install over an existing install of the same effective name and
    /// the item declares any, else its install hooks (HOOK-125).
    // spec: HOOK-125
    pub fn install_time_hooks(&self, is_update: bool) -> Vec<&ResolvedHook> {
        if is_update {
            let update = self.update_hooks();
            if !update.is_empty() {
                return update;
            }
        }
        self.install_hooks()
    }

    /// 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.
    ///
    /// Returns an [`ItemKey`] (DSC-95): `key()` embeds the bare name, which is
    /// source-controlled (a filename or `[[items]]` value) and can carry
    /// ANSI/control/bidi code points, so the raw and display readings are
    /// distinct types. `.as_str()` for identity (matching store/manifest
    /// identity); `.display()` at every human/`--json` print site -- `ItemKey`
    /// has no `Display`, so passing it straight to `println!`/`format!` is a
    /// compile error. This mirrors the single-capture-point sanitize the
    /// description gets in `build_item` (DSC-94), for the field that keys
    /// identity and so cannot be sanitized in place.
    pub fn key(&self) -> ItemKey {
        ItemKey::new(format!("{}:{}", self.kind.as_str(), self.effective_name()))
    }

    /// This item's compiled ignore set (IGN-1/IGN-2): its resolved patterns
    /// plus the built-in VCS directories, which apply whether or not the source
    /// declared anything.
    pub fn ignore_set(&self) -> Result<crate::ignore::IgnoreSet> {
        crate::ignore::IgnoreSet::new(
            self.ignore.as_deref().unwrap_or_default(),
            &self.key().display(),
        )
    }

    /// This item's content hash (LIFE-15), excluding what its ignore set
    /// removes (IGN-10).
    ///
    /// Every drift comparison goes through here rather than calling
    /// `hash::hash_path` on `self.path`: the recorded manifest hash was computed
    /// with this item's ignores applied, so a comparison hash computed without
    /// them would differ forever and report permanent, unfixable drift.
    pub fn content_hash(&self) -> Result<String> {
        crate::hash::hash_path_ignoring(&self.path, &self.ignore_set()?)
    }

    /// The item's anchor file, the one an ignore pattern may not exclude
    /// (IGN-5): `SKILL.md` / `TOOL.md` for a directory item, and for a
    /// single-file item the file itself, which is the item.
    ///
    /// A tool's `TOOL.md` is optional (a tool needs no anchor file at all), so
    /// IGN-5 protects it only when the tool actually has one: a tool with no
    /// `TOOL.md` has nothing under it named `TOOL.md` for an ignore pattern to
    /// exclude, so naming that file in an error would refer to a file the tool
    /// does not ship.
    pub fn anchor_file(&self) -> Option<&'static str> {
        match self.kind {
            ItemKind::Skill => Some("SKILL.md"),
            ItemKind::Tool => self.path.join("TOOL.md").is_file().then_some("TOOL.md"),
            // An agent/rule/command/workflow item IS its file: `path` names the
            // file, so there is nothing under the item an ignore pattern could
            // match.
            ItemKind::Agent | ItemKind::Rule | ItemKind::Command | ItemKind::Workflow => None,
            // spec: RES-5 -- a resource has no anchor file; every file under it
            // is content.
            ItemKind::Resource => None,
        }
    }

    /// The description as a display surface shows it: the description itself,
    /// with a workflow's `whenToUse` appended as `<description> - <whenToUse>`,
    /// the way the harness's own workflow list renders the pair (WF-51).
    ///
    /// This is the HUMAN display join: `probe --no-tui`, the probe TUI's
    /// catalog rows, and query matching ([`matches_query`]) go through here.
    /// An item with no `whenToUse` -- every item of every other kind -- reads
    /// exactly as `description` does.
    ///
    /// The `--json` surfaces do NOT use it: `probe --json` and `recall --json`
    /// emit `description` unchanged and `whenToUse` as its own `when_to_use`
    /// key (WF-62), so a JSON consumer never has to split the joined string.
    ///
    /// spec: WF-51
    pub fn display_description(&self) -> Option<String> {
        match (&self.description, &self.when_to_use) {
            (Some(d), Some(w)) => Some(format!("{d} - {w}")),
            (Some(d), None) => Some(d.clone()),
            // A workflow whose `meta` gave a `whenToUse` and no `description`
            // is malformed by the harness's own rules (WF-30 reports it), but
            // showing what it does have beats showing nothing.
            (None, Some(w)) => Some(w.clone()),
            (None, None) => None,
        }
    }

    /// Convenience for [`ItemKey::display`] on `self.key()` (DSC-95).
    pub fn display_key(&self) -> String {
        self.key().display()
    }

    /// The bare name sanitized for display (DSC-95); see [`Self::display_key`].
    pub fn display_name(&self) -> String {
        crate::sanitize::strip_ansi(&self.name)
    }

    /// The effective (possibly prefixed) name sanitized for display (DSC-95);
    /// see [`Self::display_key`]. Used for the `--json` `name` field.
    pub fn display_effective_name(&self) -> String {
        crate::sanitize::strip_ansi(&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;
    }
    // spec: WF-51 -- the displayed description, so a query matches the
    // `whenToUse` a workflow row actually shows.
    item.display_description()
        .is_some_and(|d| d.to_lowercase().contains(&q))
}

thread_local! {
    /// Stable identities `(source, kind, bare name)` a scan on this thread
    /// dropped for an unreadable item manifest (DSC-98).
    static UNREADABLE: std::cell::RefCell<std::collections::HashSet<(String, ItemKind, String)>> =
        std::cell::RefCell::new(std::collections::HashSet::new());
}

fn record_unreadable(source: &str, kind: ItemKind, name: &str) {
    UNREADABLE.with(|u| {
        u.borrow_mut()
            .insert((source.to_string(), kind, name.to_string()))
    });
}

/// Whether a scan in this process dropped the item `(source, kind, name)`
/// because its own manifest could not be read (DSC-98). The source still
/// ships such an item, so its absence from the catalog is not a removal
/// upstream and nothing prunes it (LIFE-57, CLI-245).
// spec: DSC-123
pub fn dropped_as_unreadable(source: &str, kind: ItemKind, name: &str) -> bool {
    UNREADABLE.with(|u| {
        u.borrow()
            .contains(&(source.to_string(), kind, name.to_string()))
    })
}

/// Scan every melded source for installable items.
///
/// A source whose linked working tree has vanished
/// ([`MindError::LinkedSourceGone`]) is skipped with a stderr warning rather
/// than aborting the whole walk (CLI-212, CLI-213): the one dead source no
/// longer takes down `recall`/`probe`/`learn` for every other source. Every
/// other scan failure (a version gate, a bad `--root`, a duplicate item, ...)
/// still aborts the whole call exactly as before -- this is a narrow
/// degradation for the one failure mode a user cannot fix by re-running the
/// same command. A targeted single-source scan (`meld`'s or `learn`'s own
/// fresh clone, via a one-source registry) is unaffected in practice: the
/// directory it just cloned into cannot itself be gone.
pub fn scan(paths: &Paths, registry: &Registry) -> Result<Vec<CatalogItem>> {
    // spec: PRG-4 -- the scan prints only through `render::scan_warn`, which
    // clears the spinner first.
    let _step = crate::progress::step_if_idle(|| "scanning melded sources".to_string());
    let mut items = Vec::new();
    for source in &registry.sources {
        items.extend(scan_one(paths, source)?);
    }
    Ok(items)
}

/// One source's catalog, every failure an error and nothing printed: for a
/// caller that skips a source it cannot scan without speaking for it.
pub fn scan_one_strict(paths: &Paths, source: &Source) -> Result<Vec<CatalogItem>> {
    let mut items = Vec::new();
    scan_source(paths, source, &mut items)?;
    Ok(items)
}

/// [`scan`] for a single source. A linked source whose working tree is gone
/// yields no items and a warning rather than an error, as in the full scan.
pub fn scan_one(paths: &Paths, source: &Source) -> Result<Vec<CatalogItem>> {
    match scan_one_strict(paths, source) {
        Ok(items) => Ok(items),
        // spec: CLI-212 CLI-213
        Err(e @ MindError::LinkedSourceGone { .. }) => {
            // spec: DSC-102 -- muted while the TUI owns the terminal.
            crate::render::scan_warn(format!("warning: {e}"));
            Ok(Vec::new())
        }
        Err(e) => Err(e),
    }
}

/// Source names already warned about a reserved-word prefix in this process
/// (DSC-112), so the warning prints once per source however many scans a verb
/// runs.
static WARNED_RESERVED: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
    std::sync::OnceLock::new();

/// True the first time it is called for `source_name` in this process.
///
/// spec: DSC-112
fn first_reserved_warning(source_name: &str) -> bool {
    let set = WARNED_RESERVED.get_or_init(Default::default);
    // A poisoned lock only means another thread panicked mid-insert; the set
    // is still usable, and a duplicate warning beats none.
    let mut guard = set.lock().unwrap_or_else(|e| e.into_inner());
    guard.insert(source_name.to_string())
}

/// Source names already warned about an unmet `min-mind-version` in this
/// process (DSC-40), so the warning prints once per source per run.
static WARNED_VERSION: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> =
    std::sync::OnceLock::new();

/// True the first time it is called for `source_name` in this process. Meld
/// calls it when it shows its own warning, so the scan after it stays quiet.
///
/// spec: DSC-40
pub(crate) fn first_version_warning(source_name: &str) -> bool {
    let set = WARNED_VERSION.get_or_init(Default::default);
    let mut guard = set.lock().unwrap_or_else(|e| e.into_inner());
    guard.insert(source_name.to_string())
}

/// The warning for a source whose `min-mind-version` this binary does not
/// meet (DSC-40, DSC-116).
pub(crate) fn newer_mind_warning(source_name: &str, required: &str) -> String {
    format!(
        "warning: source '{}' requires mind >= {}, but this is mind {}; it may not work as \
         expected. Run `mind evolve` to update",
        crate::sanitize::strip_ansi(source_name),
        required,
        env!("CARGO_PKG_VERSION"),
    )
}

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<()> {
    scan_source_reporting(clone_root.as_ref(), source, out).map(drop)
}

/// [`scan_source_at`], returning the convention resources the RES-3 pruning
/// dropped from `out`, for `review`'s `unreferenced-resource` advisory
/// (RES-14).
pub(crate) fn scan_source_reporting(
    clone_root: &Path,
    source: &Source,
    out: &mut Vec<CatalogItem>,
) -> Result<Vec<CatalogItem>> {
    // spec: CLI-212 -- a linked source's working tree can vanish after meld (a
    // relocated or deleted /tmp fixture, a `cd` past a relative clean-up).
    // Detect it here, before `MindToml::load`'s NotFound-as-absent handling or
    // a convention-scan `InvalidRoot` obscure the real cause with a less
    // actionable message.
    if source.is_linked() && !clone_root.is_dir() {
        return Err(MindError::LinkedSourceGone {
            source_name: source.name.clone(),
            path: clone_root.display().to_string(),
        });
    }
    // spec: DSC-112 -- a source melded before a prefix word became reserved
    // still fails `MindToml::load`'s NS-25 check on every scan, and the bare
    // `ReservedPrefix` message is written for a meld that has not happened yet.
    // Re-point it at the one thing an already-melded user can do.
    let mindfile = MindToml::load(clone_root).map_err(|e| melded_prefix_error(source, e))?;

    // spec: DSC-40 -- a source that wants a newer `mind` is scanned anyway,
    // with a warning: meld already asked before registering it (DSC-116), and
    // failing every later verb would take the whole lobe down over it.
    if let Some(required) = crate::mindfile::unmet_min_version(mindfile.as_ref())
        && first_version_warning(&source.name)
    {
        crate::render::scan_warn(newer_mind_warning(&source.name, required));
    }

    // 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`.
    // Both inputs are validated where they are SET (the `--as`/`--namespace`
    // alias in commands.rs, the `[source].prefix` at mindfile load) -- but a
    // registry entry is never re-validated, and the reserved list grows: an
    // alias recorded before `workflow` (or any future kind word) joined it is
    // still in `sources.json` and still in effect here.
    let prefix = source
        .alias
        .clone()
        .or_else(|| mindfile.as_ref().and_then(|m| m.source.prefix.clone()))
        .filter(|p| !p.is_empty());
    // spec: DSC-112 -- advisory, not a gate: the items are installed under this
    // prefix already, and failing every scanning verb would take the user's
    // whole lobe down over a naming problem. Warn and carry on, the way the
    // unguarded-reference and vanished-source paths do.
    // A verb can scan the same source several times in one run (upgrade syncs,
    // then rescans), so the warning is printed once per source per process.
    if let Some(p) = &prefix
        && matches!(
            namespace::validate_prefix(p),
            Err(MindError::ReservedPrefix { .. })
        )
        && first_reserved_warning(&source.name)
    {
        crate::render::scan_warn(format!(
            "warning: source '{}': its namespace prefix '{}' is a word mind now reserves, so \
             '{}:<name>' reads as a kind-qualified ref rather than a namespaced item; unmeld \
             it, then re-meld with `--namespace <other>` to rename it",
            crate::sanitize::strip_ansi(&source.name),
            crate::sanitize::strip_ansi(p),
            crate::sanitize::strip_ansi(p),
        ));
    }

    // spec: IGN-1 -- the source-level list every item falls back to when it
    // declared none of its own. Captured before the branches below so both the
    // item-link path and the ordinary scan resolve against the same list.
    let source_ignore: Vec<String> = mindfile
        .as_ref()
        .and_then(|m| m.source.ignore.clone())
        .unwrap_or_default();
    let scan_start = out.len();

    // spec: LNK-7 -- an item-link instance's catalog is exactly the linked
    // skill. The repo's declared inventory (an authoritative mind.toml, a
    // .claude-plugin/ manifest) does not gate it; the DSC-40 version gate and
    // the [source] metadata handled above still apply.
    if let Some(item_path) = &source.item_path {
        scan_item_link(clone_root, source, &prefix, item_path, out)?;
        resolve_ignores(&mut out[scan_start..], &source_ignore)?;
        return Ok(Vec::new());
    }

    let base_start = out.len();
    let addroot_prefix = scan_source_layers(clone_root, source, &mindfile, &prefix, out)?;
    let add_start = out.len();
    // spec: DSC-84 -- the consumer's --add-root roots compose with whatever
    // layer the match above found authoritative.
    // spec: DSC-86 -- add-root items use the layer's effective prefix: for a
    // single-plugin source that is the plugin-name default, so the whole meld
    // shares one namespace.
    scan_add_roots(clone_root, source, &addroot_prefix, base_start, out)?;
    // spec: RES-3 RES-4 -- convention resources are offered only when
    // referenced. An authoritative mind.toml's own items are declared, so
    // only what the added roots contributed is convention there; otherwise
    // (convention or a plugin manifest, which has no resources) everything
    // from `base_start` on is.
    let convention_from = if mindfile.as_ref().is_some_and(|m| m.is_authoritative()) {
        add_start
    } else {
        base_start
    };
    let dropped = prune_unreferenced_resources(out, base_start, convention_from);
    // spec: IGN-1 -- one resolution point for every item this scan produced,
    // whatever discovery layer found it (convention, an authoritative
    // mind.toml, a plugin manifest, or an added root).
    resolve_ignores(&mut out[scan_start..], &source_ignore)?;
    Ok(dropped)
}

/// The convention resources among `items` that no other item references
/// (RES-3), as indices into `items`. `convention_from` is the index the
/// convention-discovered part of `items` starts at (RES-4: a declared resource
/// is never a candidate). Every item that is not a candidate is a root, so a
/// candidate survives when a root depends on it, directly or through another
/// surviving candidate (`deps::reachable`).
fn unreferenced_resources(items: &[CatalogItem], convention_from: usize) -> Vec<usize> {
    let is_candidate = |i: usize| i >= convention_from && items[i].kind == ItemKind::Resource;
    if !(0..items.len()).any(is_candidate) {
        return Vec::new();
    }
    let roots: Vec<usize> = (0..items.len()).filter(|&i| !is_candidate(i)).collect();
    let reached = crate::deps::reachable(items, &roots, read_expanding_text);
    (0..items.len())
        .filter(|&i| is_candidate(i) && !reached.contains(&i))
        .collect()
}

/// Remove the convention resources no item references from `out[start..]`
/// (RES-3) and return them. Silent: an unreferenced entry under `resources/`
/// is most often something unrelated to the source's items (a project's
/// install script), so `review` is where an author hears about it (RES-14).
fn prune_unreferenced_resources(
    out: &mut Vec<CatalogItem>,
    start: usize,
    convention_from: usize,
) -> Vec<CatalogItem> {
    let drop: std::collections::HashSet<usize> =
        unreferenced_resources(&out[start..], convention_from - start)
            .into_iter()
            .map(|i| i + start)
            .collect();
    if drop.is_empty() {
        return Vec::new();
    }
    let mut dropped = Vec::new();
    let mut kept = Vec::with_capacity(out.len() - drop.len());
    for (i, item) in std::mem::take(out).into_iter().enumerate() {
        if drop.contains(&i) {
            dropped.push(item);
        } else {
            kept.push(item);
        }
    }
    *out = kept;
    dropped
}

/// All of an item's token-expanding text, concatenated: the files install
/// expands tokens in (`namespace::item_expands_tokens`, NS-53/NS-57), read
/// no-follow (DSC-108). The input to dependency edges at scan time (RES-3).
fn read_expanding_text(item: &CatalogItem) -> String {
    let mut buf = String::new();
    for file in crate::review::item_files(item) {
        if !namespace::item_expands_tokens(item, &item.path, &file) {
            continue;
        }
        if !is_regular_file_nofollow(&file) {
            continue;
        }
        if let Ok(content) = std::fs::read_to_string(&file) {
            buf.push_str(&content);
            buf.push('\n');
        }
    }
    buf
}

/// Re-word a `MindToml::load` failure that refused the source's declared
/// `[source].prefix` as a reserved word, for a source that is already melded.
///
/// Every other load failure passes through untouched. `ReservedPrefix` alone is
/// re-pointed: it is the one refusal that can appear for a source the user
/// already melded successfully (the reserved list is append-only, so a word can
/// become reserved under a registered source), and its own message tells the
/// user only that the prefix "cannot be used" -- advice for a meld they already
/// did, with no mention of the source or of `unmeld`.
///
/// spec: DSC-112
fn melded_prefix_error(source: &Source, e: MindError) -> MindError {
    match e {
        MindError::ReservedPrefix { prefix } => MindError::MeldedSourceReservedPrefix {
            source_name: crate::sanitize::strip_ansi(&source.name),
            prefix: crate::sanitize::strip_ansi(&prefix),
        },
        other => other,
    }
}

/// Fill in each item's effective ignore list and validate it (IGN-1/4/5/12).
///
/// An item that declared its own list keeps it (the list REPLACES the source's
/// rather than adding to it); an item that declared none inherits the source's.
/// The built-in VCS set is not stored here: it lives in
/// [`crate::ignore::IgnoreSet`] and applies to every item either way, so it
/// cannot be lost by an item declaring an empty list.
fn resolve_ignores(items: &mut [CatalogItem], source_ignore: &[String]) -> Result<()> {
    // spec: DSC-95 -- the literal declaration site named below carries no
    // source-controlled text, so it needs no sanitizing (unlike a display key,
    // which does and gets it from `display_key()`).
    const SOURCE_LABEL: &str = "mind.toml [source].ignore";
    for item in items.iter_mut() {
        // M9-a: capture whether THIS item declared its own list before it gets
        // overwritten by the inherited one below, so an error can still name
        // where the bad pattern was actually written. Without this, a bad
        // entry in `[source].ignore` is reported against whichever item's scan
        // happened to reach the check first (`skill:a: invalid ignore pattern
        // ...`), sending the author to look for an `ignore` key on that item
        // that does not exist, and the blamed item can change across a re-run.
        let declared_own = item.ignore.is_some();
        if !declared_own {
            item.ignore = Some(source_ignore.to_vec());
        }
        let label = if declared_own {
            item.display_key()
        } else {
            SOURCE_LABEL.to_string()
        };
        // Compiling validates every pattern (IGN-4) at scan, so a malformed or
        // unsafe entry is reported when the source is read rather than at the
        // install that would silently not exclude what it names. Compiled
        // directly here (not via `item.ignore_set()`, which always labels by
        // the item) so the error names the declaration site above.
        let set =
            crate::ignore::IgnoreSet::new(item.ignore.as_deref().unwrap_or_default(), &label)?;

        // spec: IGN-5 -- an item may not ignore the file that defines it, which
        // would install it as an empty directory that discovery still offers.
        if let Some(anchor) = item.anchor_file()
            && set.is_under_ignored(std::path::Path::new(anchor))
        {
            let entry = item
                .ignore
                .as_deref()
                .unwrap_or_default()
                .iter()
                .find(|e| {
                    crate::ignore::IgnoreSet::new(std::slice::from_ref(e), "")
                        .is_ok_and(|one| one.is_under_ignored(std::path::Path::new(anchor)))
                })
                .cloned()
                .unwrap_or_else(|| anchor.to_string());
            return Err(MindError::IgnoresOwnAnchor {
                item: label,
                entry: crate::sanitize::strip_ansi(&entry),
                anchor: anchor.to_string(),
            });
        }

        // spec: IGN-12 -- `expand:` and `ignore` naming the same file
        // contradict each other; that is an authoring mistake, named rather
        // than resolved by a silent precedence rule.
        for file in &item.expand {
            let rel = std::path::Path::new(file);
            if !set.is_under_ignored(rel) {
                continue;
            }
            let entry = item
                .ignore
                .as_deref()
                .unwrap_or_default()
                .iter()
                .find(|e| {
                    crate::ignore::IgnoreSet::new(std::slice::from_ref(e), "")
                        .is_ok_and(|one| one.is_under_ignored(rel))
                })
                .cloned()
                // L14: when no declared entry matched, the exclusion came from
                // the built-in set; name the specific one (`.git`/`.hg`/`.svn`/
                // `.bzr`) rather than the generic "a built-in ignore" prose.
                .or_else(|| builtin_match(rel).map(str::to_string))
                .unwrap_or_else(|| "a built-in ignore".to_string());
            return Err(MindError::ExpandsIgnoredFile {
                item: label,
                file: crate::sanitize::strip_ansi(file),
                entry: crate::sanitize::strip_ansi(&entry),
            });
        }
    }
    Ok(())
}

/// Whether `rel` (or an ancestor of it) has a path component that names one of
/// the built-in VCS directories (IGN-2), so an error can name the specific
/// built-in that excluded a path instead of a generic placeholder (L14).
fn builtin_match(rel: &Path) -> Option<&'static str> {
    rel.components().find_map(|c| match c {
        std::path::Component::Normal(name) => crate::ignore::BUILTIN_IGNORES
            .iter()
            .find(|n| **n == name.to_string_lossy())
            .copied(),
        _ => None,
    })
}

/// Whether an item-link path names a single FILE item rather than a skill
/// directory (LNK-20): any `.md` path, since a `.../SKILL.md` link has already
/// had its anchor segment stripped at parse (LNK-1).
pub(crate) fn is_file_link(item_path: &str) -> bool {
    item_path.ends_with(".md")
}

/// Whether an item-link path names a workflow's own file (LNK-20, WF-6): its
/// parent directory is `workflows/` AND its extension is `.js`, the shape the
/// convention scan calls a workflow (WF-1). A workflow is never a valid
/// item-link target -- a blob link takes a `.md` file, a tree link a skill
/// directory (LNK-20)
/// -- so `scan_item_link` uses this to tell "the path names a deliberately
/// unsupported kind" apart from "the path is simply wrong", raising
/// [`MindError::LinkKindNotSupported`] instead of the generic `LinkNotASkill`.
///
/// The parent check is what keeps the claim true: a `.js` anywhere else
/// (`lib/util.js`) is not a workflow and must not be called one. It is refused
/// too, by [`is_js_link_path`], but with a message that says only what mind
/// knows: the link form does not take a JavaScript file.
fn is_workflow_link_path(item_path: &str) -> bool {
    let path = Path::new(item_path);
    let parent_is_workflows = path
        .parent()
        .and_then(|p| p.file_name())
        .is_some_and(|n| n == ItemKind::Workflow.dir());
    parent_is_workflows && is_js_link_path(item_path)
}

/// Whether an item-link path names a JavaScript file (LNK-20): a `.js`
/// extension, compared as the workflow scan compares it (WF-3).
fn is_js_link_path(item_path: &str) -> bool {
    Path::new(item_path)
        .extension()
        .is_some_and(|e| e == kind_extension(ItemKind::Workflow))
}

/// Resolve a file link's kind (LNK-21), first hit wins: the consumer's explicit
/// kind, else the containing directory (`agents/`, `rules/`, `commands/`), else
/// the file's own frontmatter `kind:`.
///
/// Directory outranks frontmatter so a link installs the same item a whole-repo
/// meld would: a convention scan classifies by directory (DSC-11..14).
fn resolve_file_link_kind(source: &Source, item_path: &str, file: &Path) -> Result<ItemKind> {
    let mismatch = |kind: ItemKind, reason: &str| MindError::LinkKindMismatch {
        source_name: source.name.clone(),
        path: item_path.to_string(),
        kind: kind.as_str().to_string(),
        reason: reason.to_string(),
    };
    // spec: LNK-21 step 1 -- `--kind` / the curator entry's `kind =`.
    if let Some(kind) = source.item_kind {
        if !is_file_kind(kind) {
            return Err(mismatch(
                kind,
                "the link names a file, and a skill or tool is a directory",
            ));
        }
        return Ok(kind);
    }
    // spec: LNK-21 step 2 -- the containing directory.
    if let Some(kind) = Path::new(item_path)
        .parent()
        .and_then(|p| p.file_name())
        .and_then(|n| ItemKind::from_dir(&n.to_string_lossy()))
        .filter(|k| is_file_kind(*k))
    {
        return Ok(kind);
    }
    // spec: LNK-21 step 3 -- the file's own frontmatter `kind:`. DSC-91: read
    // through the size-capped text reader, not a raw `read_to_string`, so a
    // link to a huge attacker-hosted file cannot force an unbounded read here.
    let text = crate::frontmatter::text_capped(file)?;
    if let Some(declared) = crate::frontmatter::field(&text, "kind") {
        let kind = ItemKind::parse(declared.trim()).ok_or_else(|| MindError::LinkKindMismatch {
            source_name: source.name.clone(),
            path: item_path.to_string(),
            kind: crate::sanitize::strip_ansi(declared.trim()),
            reason: "not an item kind (expected agent, rule, or command); pass \
                     --kind <agent|rule|command> to override the frontmatter"
                .to_string(),
        })?;
        if !is_file_kind(kind) {
            return Err(mismatch(
                kind,
                "its frontmatter declares a directory kind, but the link names a file",
            ));
        }
        return Ok(kind);
    }
    Err(MindError::LinkKindUnresolved {
        source_name: source.name.clone(),
        path: item_path.to_string(),
    })
}

/// Whether a kind is one a single file can be (LNK-20): skills and tools are
/// directories.
fn is_file_kind(kind: ItemKind) -> bool {
    matches!(kind, ItemKind::Agent | ItemKind::Rule | ItemKind::Command)
}

/// Catalog an item-link source instance (LNK-7): the one item at `item_path`,
/// a skill directory or a single file (LNK-20). The path was validated at parse
/// (LNK-10); the confinement re-check here guards a hand-edited sources.json.
fn scan_item_link(
    clone_root: &Path,
    source: &Source,
    prefix: &Option<String>,
    item_path: &str,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    let file_link = is_file_link(item_path);
    let bad_target = || {
        if file_link {
            MindError::LinkNotAFile {
                source_name: source.name.clone(),
                path: item_path.to_string(),
            }
        } else {
            MindError::LinkNotASkill {
                source_name: source.name.clone(),
                path: item_path.to_string(),
            }
        }
    };
    if !plugin_manifest::is_safe_manifest_path(item_path) {
        return Err(bad_target());
    }
    // Canonicalize the root FIRST and join onto that (rather than joining onto
    // `clone_root` and canonicalizing the result) so a non-existent `target`
    // still falls back to a path under `canon_root`: on a host where the temp
    // root itself is behind a symlink (e.g. macOS's `/tmp` -> `/private/tmp`),
    // canonicalizing only the existing side left a non-existent target's
    // fallback un-resolved, so it failed `starts_with` against the resolved
    // root and misreported as `LinkNotASkill`/`LinkNotAFile` instead of
    // reaching the shape-specific checks below.
    let canon_root = clone_root
        .canonicalize()
        .unwrap_or_else(|_| clone_root.to_path_buf());
    let target = canon_root.join(item_path);
    let canon = target.canonicalize().unwrap_or_else(|_| target.clone());
    if !canon.starts_with(&canon_root) {
        return Err(bad_target());
    }
    // The checks run on the canonical `target`; the item itself carries the
    // path under the clone root as the caller named it, like every other scan
    // path, so a symlinked temp root does not leak its resolved form into the
    // catalog.
    let item_path_abs = clone_root.join(item_path);
    let (kind, path, meta) = if file_link {
        if !target.is_file() {
            return Err(bad_target());
        }
        // spec: LNK-21 -- a file item is its own metadata anchor.
        let kind = resolve_file_link_kind(source, item_path, &target)?;
        (kind, item_path_abs.clone(), item_path_abs)
    } else {
        // spec: LNK-21 -- a directory link is always the skill reading, so an
        // explicit kind naming anything else is a mismatch.
        if let Some(kind) = source.item_kind.filter(|k| *k != ItemKind::Skill) {
            return Err(MindError::LinkKindMismatch {
                source_name: source.name.clone(),
                path: item_path.to_string(),
                kind: kind.as_str().to_string(),
                reason: "the link names a directory, which is always a skill".to_string(),
            });
        }
        let skill_md = target.join("SKILL.md");
        // spec: DSC-115 -- the skill dir and its anchor are classified
        // no-follow, as in the convention scan: a symlinked `SKILL.md` or
        // skill directory is not a skill.
        if !(is_dir_nofollow(&target) && is_regular_file_nofollow(&skill_md)) {
            if is_workflow_link_path(item_path) {
                return Err(MindError::LinkKindNotSupported {
                    source_name: source.name.clone(),
                    path: item_path.to_string(),
                });
            }
            // spec: WF-6 -- a `.js` outside `workflows/` is refused as well,
            // but as what it is: a JavaScript file the link form does not take.
            // Calling it a workflow would be a claim the path does not support.
            if is_js_link_path(item_path) {
                return Err(MindError::LinkNotLinkableFile {
                    source_name: source.name.clone(),
                    path: item_path.to_string(),
                });
            }
            return Err(bad_target());
        }
        let meta = item_path_abs.join("SKILL.md");
        (ItemKind::Skill, item_path_abs, meta)
    };
    if let Some(item) = make_item(clone_root, source, prefix, kind, path, &meta)? {
        out.push(item);
    }
    Ok(())
}

/// Scan the authoritative discovery layer for a source: an authoritative
/// `mind.toml` (DSC-3), a `.claude-plugin/` manifest (MKT-2/MKT-14), or the
/// convention scan (DSC-10..13), in that precedence.
///
/// Returns the effective prefix `--add-root` items should install under
/// (DSC-86): the single-plugin arm's plugin-name default when that arm ran,
/// else the outer source prefix unchanged. A marketplace's per-entry
/// namespaces never apply (there is no single entry to attribute an added
/// root to).
fn scan_source_layers(
    clone_root: &Path,
    source: &Source,
    mindfile: &Option<MindToml>,
    prefix: &Option<String>,
    out: &mut Vec<CatalogItem>,
) -> Result<Option<String>> {
    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 {
                // spec: DSC-98 -- a dropped item is simply not offered; the
                // rest of the declared inventory still is.
                let Some(item) = from_decl(clone_root, source, prefix, decl)? else {
                    continue;
                };
                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(prefix.clone())
        }
        mt => {
            // MKT-15: an own-item scan layout means the repo's own items are
            // defined through convention at a chosen layout, so a co-present
            // `.claude-plugin/` manifest's own-item layer is suppressed and
            // convention discovery (honoring roots/flat-skills) runs instead. The
            // layout may come from the source's own mind.toml (`[source].roots` /
            // `[source].flat-skills`) OR from a consumer override persisted on the
            // source (`meld --root` / `--flat-skills`, DSC-51/DSC-75): both are the
            // same "define my own items by convention" signal, so a consumer flag
            // is not a silent no-op on a manifest source. A bare
            // `[discover].sources` list is a curator directive, NOT an own-item
            // directive, so it does not suppress the manifest (MKT-16): the
            // manifest still supplies the immediate source's items and the curator
            // layer composes on top (handled at meld time in commands.rs). (The
            // authoritative `[[items]]`/`[discover]`-glob case never reaches this
            // arm; it is handled by the `is_authoritative()` arm above.)
            let suppress_manifest = source.roots.is_some()
                || source.flat_skills
                || mt.as_ref().is_some_and(|m| m.declares_scan_layout());

            // 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 (and not suppressed
            // by MKT-15), 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 for external entries; in-repo entries are
            // scanned directly here (MKT-14).
            //
            // The "found and ignored" NOTE (for both the authoritative and the
            // MKT-15 scan-layout suppression cases) is commands.rs's
            // responsibility; catalog stays quiet (MKT-2).
            if !suppress_manifest
                && 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.

                // spec: DSC-86 -- add-root items share the plugin's namespace.
                return Ok(plugin_prefix);
            }

            // 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
            // for the immediate source: when found (and not suppressed by MKT-15),
            // convention discovery is skipped. MKT-15: a mind.toml scan layout
            // suppresses only the manifest's own-item (in-repo plugin) layer; the
            // marketplace's external curator entries still compose (commands.rs).
            if !suppress_manifest
                && 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,
                )?;
                // Marketplace is authoritative (MKT-2 / MKT-14); per-entry
                // namespaces do not reach add-root items (DSC-86).
                return Ok(prefix.clone());
            }

            // 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 {
                validate_scan_root(clone_root, r, &source.name)?;
            }

            // 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(prefix.clone())
        }
    }
}

/// Validate a convention scan root: not absolute, inside the clone (no `..`
/// escape, including via symlinks), and an existing directory. Shared by the
/// effective-roots scan (DSC-52) and the `--add-root` scan (DSC-84).
fn validate_scan_root(clone_root: &Path, root: &str, source_name: &str) -> Result<()> {
    let invalid = || MindError::InvalidRoot {
        source_name: source_name.to_string(),
        root: root.to_string(),
    };
    if Path::new(root).is_absolute() {
        return Err(invalid());
    }
    let full = clone_root.join(root);
    // 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(invalid());
    }
    if !full.is_dir() {
        return Err(invalid());
    }
    Ok(())
}

/// Convention-scan the consumer's `--add-root` roots and union the results
/// with the items the authoritative layer contributed (DSC-84..86, MKT-17).
///
/// Each added root is scanned in BOTH skill layouts at once - the `skills/`
/// container (DSC-10) and flat bare-name directories (DSC-74) - since the
/// SKILL.md anchor disambiguates them and a `--flat-skills` override cannot be
/// combined with composition (it suppresses a plugin manifest, MKT-15). Agent,
/// rule, and tool discovery under each root is the usual convention.
fn scan_add_roots(
    clone_root: &Path,
    source: &Source,
    prefix: &Option<String>,
    base_start: usize,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    let Some(add_roots) = source.add_roots.as_ref().filter(|r| !r.is_empty()) else {
        return Ok(());
    };
    // spec: DSC-84 -- the InvalidRoot rules match --root.
    for r in add_roots {
        validate_scan_root(clone_root, r, &source.name)?;
    }
    let canon = |p: &Path| -> PathBuf { p.canonicalize().unwrap_or_else(|_| p.to_path_buf()) };
    let base_paths: std::collections::HashSet<PathBuf> =
        out[base_start..].iter().map(|it| canon(&it.path)).collect();
    let add_start = out.len();
    for r in add_roots {
        let root = clone_root.join(r);
        // Flat pass (skills as bare child dirs) plus agents/rules/tools ...
        scan_convention(&root, source, prefix, true, out)?;
        // ... and the containered skills/ pass. The two cannot overlap: a
        // `skills` child dir is only a flat skill if it holds a direct
        // SKILL.md, in which case it has no skill subdirs of its own.
        let skills_dir = root.join(ItemKind::Skill.dir());
        for entry in read_container_opt(&skills_dir)? {
            let skill_md = entry.join("SKILL.md");
            // spec: DSC-108 -- classified no-follow, as the convention scan
            // does: a symlinked skill dir or anchor would read a file outside
            // the clone into the catalog.
            if is_dir_nofollow(&entry)
                && is_regular_file_nofollow(&skill_md)
                && let Some(item) = make_item(
                    clone_root,
                    source,
                    prefix,
                    ItemKind::Skill,
                    entry,
                    &skill_md,
                )?
            {
                out.push(item);
            }
        }
    }
    // spec: DSC-85 -- drop add-root items the authoritative layer already
    // contributed (same on-disk path); the layer's entry wins, keeping its
    // namespace and metadata.
    let mut added: Vec<CatalogItem> = out.split_off(add_start);
    added.retain(|it| !base_paths.contains(&canon(&it.path)));
    // spec: DSC-87/DSC-89 -- two add-root passes can surface the SAME on-disk
    // item AS THE SAME KIND (e.g. `--add-root . --add-root skills` both finding
    // `skills/foo` as a Skill, one via the skills/ container pass and one via
    // the flat-skills pass). That is a same-(kind, path) overlap, not a name
    // collision, so keep exactly one entry per (kind, canonical path) among the
    // added items rather than letting both survive to the (kind, effective-name)
    // uniqueness check below and error out. The key includes `kind` (DSC-89): a
    // single on-disk path can legitimately contribute up to one item PER KIND --
    // e.g. `tools/foo/` (a Tool, no anchor file required) that also carries a
    // `SKILL.md` (a Skill) surfaces as both when reached by different add-roots
    // (`--add-root .` finds it via the tools/ pass, `--add-root tools` finds it
    // via the flat-skills pass); keying on path alone would silently drop
    // whichever kind lost the race.
    let mut seen_add_paths: std::collections::HashSet<(ItemKind, PathBuf)> =
        std::collections::HashSet::new();
    added.retain(|it| seen_add_paths.insert((it.kind, canon(&it.path))));
    out.extend(added);
    // spec: DSC-85 -- (kind, effective name) uniqueness across the source's
    // whole offering (authoritative layer + added roots).
    let mut seen: std::collections::HashSet<(ItemKind, String)> = std::collections::HashSet::new();
    for item in &out[base_start..] {
        let key = (item.kind, item.effective_name());
        if !seen.insert(key.clone()) {
            return Err(MindError::DuplicateItem {
                source_name: source.name.clone(),
                kind: key.0,
                name: key.1,
            });
        }
    }
    Ok(())
}

/// Classify an `[[items]]` declared path WITHOUT following or opening it
/// (DSC-108, DSC-73). `Ok(true)` keeps the item; `Ok(false)` drops it after a
/// warning (DSC-98 style): the final component, or a skill/tool anchor file,
/// is a symlink or not a regular file (a fifo, socket, or device would hang or
/// stream on read). A path whose canonical form leaves the clone (reached
/// through a symlinked parent directory) is a hard error, the way an escaping
/// `[discover]` glob match is (DSC-81).
///
/// spec: DSC-108 DSC-73
fn declared_path_is_own(
    root: &Path,
    source: &Source,
    kind: ItemKind,
    rel: &str,
    path: &Path,
    safe_name: &str,
) -> Result<bool> {
    let drop_with = |shown: &str, what: &str| {
        crate::render::scan_warn(format!(
            "warning: source '{}': [[items]] entry '{safe_name}' path '{}' {what}; a declared \
             item must be the repo's own file or directory, so it is not offered",
            crate::sanitize::strip_ansi(&source.name),
            crate::sanitize::strip_ansi(shown),
        ));
        Ok(false)
    };
    let Ok(md) = std::fs::symlink_metadata(path) else {
        // Absent: nothing to classify; later stages report it as they did.
        return Ok(true);
    };
    if md.file_type().is_symlink() {
        return drop_with(rel, "is a symlink");
    }
    // The final component is the repo's own entry; an intermediate symlinked
    // directory can still carry it outside the clone.
    let canon_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let canon = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
    if !canon.starts_with(&canon_root) {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "item '{safe_name}' path '{}' resolves outside the repo root",
                crate::sanitize::strip_ansi(rel)
            ),
        });
    }
    match kind {
        // spec: RES-4 -- a declared resource is a file or a directory, like the
        // entry a convention scan would find (RES-1); it has no anchor to check.
        ItemKind::Agent
        | ItemKind::Rule
        | ItemKind::Command
        | ItemKind::Workflow
        | ItemKind::Resource => {
            let ft = md.file_type();
            if !ft.is_file() && !ft.is_dir() {
                return drop_with(rel, "is not a regular file");
            }
        }
        ItemKind::Skill | ItemKind::Tool => {
            let anchor = meta_file(kind, path);
            if let Ok(am) = std::fs::symlink_metadata(&anchor) {
                let anchor_rel = format!("{}/{}", rel.trim_end_matches('/'), file_name(&anchor));
                if am.file_type().is_symlink() {
                    return drop_with(&anchor_rel, "is a symlink");
                }
                if !am.file_type().is_file() {
                    return drop_with(&anchor_rel, "is not a regular file");
                }
            }
        }
    }
    Ok(true)
}

/// Build a catalog item from an explicit `[[items]]` declaration.
///
/// `Ok(None)` means the item was dropped with a warning (DSC-98), exactly as in
/// [`make_item`]: a declared item is not exempt, since the manifest it cannot
/// read is the item's own, not the one that declared it.
fn from_decl(
    root: &Path,
    source: &Source,
    prefix: &Option<String>,
    decl: &ItemDecl,
) -> Result<Option<CatalogItem>> {
    // DSC-95: `decl.*` fields are source-controlled and are echoed back in these
    // rejection messages, so sanitize each before it reaches stderr.
    let safe_name = crate::sanitize::strip_ansi(&decl.name);
    let kind = ItemKind::parse(&decl.kind).ok_or_else(|| MindError::MindToml {
        path: root.join("mind.toml"),
        msg: format!(
            "unknown item kind '{}' for '{}'",
            crate::sanitize::strip_ansi(&decl.kind),
            safe_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 '{safe_name}' is unsafe: it must be a single path component (no '/', \
                 '\\', '.', '..', NUL, a control character, or a bidi/zero-width Unicode code point)"
            ),
        });
    }
    // spec: RES-5 RES-6 -- a resource is store-only with no exception: it is
    // data an item reads by token, never something an agent home offers.
    if kind == ItemKind::Resource && decl.link.is_some() {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "`link` is not valid on a resource item ('{safe_name}'): a resource is store-only \
                 and reached by {{{{resources:{safe_name}}}}}"
            ),
        });
    }
    if let Some(link) = &decl.link {
        if !is_safe_link_rel(link) {
            return Err(MindError::MindToml {
                path: root.join("mind.toml"),
                msg: format!(
                    "item '{safe_name}' has an unsafe link '{}': it must be a relative path inside \
                     the agent home (no leading '/' or '~', no '..' component, no NUL)",
                    crate::sanitize::strip_ansi(link)
                ),
            });
        }
        // spec: DSC-97 -- confine the link target to a kind directory so a
        // source cannot plant a file at the agent-home root (e.g.
        // `settings.json`) or inside a harness's own config directory, and keep
        // `commands/` (which makes its contents invocable as `/<name>`) for
        // command items alone.
        if !is_confined_link_target(link, kind) {
            return Err(MindError::MindToml {
                path: root.join("mind.toml"),
                msg: format!(
                    "item '{safe_name}' has a link '{}' outside a kind directory: it must begin \
                     with 'skills/', 'agents/', 'rules/', 'commands/', 'workflows/', or 'tools/' (a \
                     link cannot place a file at the agent-home root or inside a harness's own \
                     config, e.g. 'settings.json'), and only a command may link into \
                     'commands/' and only a workflow into 'workflows/', since the harness offers \
                     or runs what it finds there",
                    crate::sanitize::strip_ansi(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 '{}' ('{safe_name}')",
                crate::sanitize::strip_ansi(&decl.kind)
            ),
        });
    }
    // 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 '{safe_name}' has an unsafe path '{}': must be a relative path inside the \
                 clone (no leading '/' or '~', no '..' component, no NUL)",
                crate::sanitize::strip_ansi(&decl.path)
            ),
        });
    }
    let path = root.join(&decl.path);
    // spec: DSC-109 -- a workflow IS one `.js` file (WF-1), and its own file is
    // the metadata file the scan reads (`meta_file`). A declared entry whose
    // path names a directory therefore has no `meta` to read, installs a whole
    // tree at a link target the harness tries to load as a script, and reports
    // a directory's size in `review`. The author wrote this path, so it is a
    // hard refusal here rather than a warn-and-skip. Classified no-follow
    // (DSC-108): a symlink is not a directory to this check; it is dropped at
    // scan by the DSC-108 guard below, never offered.
    if kind == ItemKind::Workflow
        && std::fs::symlink_metadata(&path).is_ok_and(|m| m.file_type().is_dir())
    {
        return Err(MindError::MindToml {
            path: root.join("mind.toml"),
            msg: format!(
                "workflow item '{safe_name}' has a path '{}' that is a directory; a workflow is a \
                 single .js file, so the path must name that file",
                crate::sanitize::strip_ansi(&decl.path)
            ),
        });
    }
    // spec: DSC-108 DSC-73 -- a declared path is classified no-follow, like
    // every convention and glob match, before anything opens it.
    if !declared_path_is_own(root, source, kind, &decl.path, &path, &safe_name)? {
        return Ok(None);
    }
    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).
    //
    // spec: HOOK-132 -- only a declaration that says something about hooks is
    // authoritative. One that says nothing leaves the item free to declare its
    // own (its directory manifest, else its frontmatter), so pass `None` rather
    // than an empty list, which would read as "declared: no hooks".
    let hooks = decl
        .declares_hooks()
        .then(|| decl.resolved_item_hooks(&root.join("mind.toml")))
        .transpose()?;
    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(),
            hooks,
            ignore: decl.ignore.clone(),
            // An authoritative `[[items]]` path is always repo-root-relative
            // (DSC-52), so the source manifest that declared this item lives
            // exactly here.
            manifest_dir: Some(root),
        },
    )
}

/// 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.
///
/// Also rejects a control character or a security-blocked Unicode code point
/// (a bidi override, a directional mark, or a zero-width character -- DSC-96,
/// mirroring `namespace::is_safe_prefix_component`'s NS-72 guard). Identity is
/// the raw name (it keys the store path, the symlink, and the manifest, and
/// the cross-source collision check compares it raw), while display sanitizes
/// only at print time (DSC-95); left unchecked here, a hostile source could
/// ship a name that renders identically to a trusted item's name in every
/// human-facing surface while installing as a distinct item, defeating both
/// the visual comparison a user makes before approving an install and the
/// collision check that would otherwise warn them.
pub(crate) 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;
    }
    // spec: DSC-96
    if crate::sanitize::has_blocked_chars(name) {
        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.
///
/// This alone does not confine `rel` to a kind directory: a `[[items]] link`
/// value additionally needs [`is_confined_link_target`] (DSC-97). `path`
/// (DSC-73) reuses only this function, not the confinement check -- a source
/// path lives inside the clone, not the agent home, so "which kind directory"
/// does not apply to it.
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))
}

/// True when a (already `is_safe_link_rel`-checked) link target's first real
/// path component names one of the six kind directories -- `skills`, `agents`,
/// `rules`, `commands`, `workflows`, or `tools` -- and, for `commands/` and
/// `workflows/`, the item is itself of that kind (DSC-97, WF-8). A leading `./`
/// is skipped so `./skills/x` and `skills/x` are treated alike.
///
/// Confines a `[[items]] link` override to landing alongside items an
/// ordinary (non-`link`) install would produce, so it can change only the
/// linked name/subdirectory within a kind directory, never place a symlink at
/// the agent-home root or inside a harness's own config directory. Without
/// this, `is_safe_link_rel` alone accepts any relative path inside the agent
/// home, including e.g. `settings.json`: a malicious source's item content
/// (JSON with a `hooks` key) installed under that name becomes the Claude
/// harness's own settings file on the next `learn`, executing an
/// attacker-chosen command with no mind hook-consent prompt involved.
///
/// The four original kind directories stay mutually interchangeable (TOOL-4: a
/// tool surfaced under `agents/`). `commands/` and `workflows/` are the
/// exceptions, because a file in either is not inert content the harness merely
/// offers: it becomes the slash command `/<name>`, or a workflow the `Workflow`
/// tool will run. Any kind linking into one of them turns source-controlled
/// prose into something invocable, which a consumer who filtered their install
/// to "rules only" never asked for.
fn is_confined_link_target(rel: &str, kind: ItemKind) -> bool {
    use std::path::Component;
    let mut comps = Path::new(rel)
        .components()
        .skip_while(|c| matches!(c, Component::CurDir));
    match comps.next() {
        Some(Component::Normal(first)) => {
            let first = first.to_string_lossy();
            // spec: DSC-97 WF-8 -- only a command may land in `commands/`, and
            // only a workflow in `workflows/`; both turn a file into something
            // the harness runs rather than content it offers.
            for invocable in [ItemKind::Command, ItemKind::Workflow] {
                if first == invocable.dir() {
                    return kind == invocable;
                }
            }
            [
                ItemKind::Skill,
                ItemKind::Agent,
                ItemKind::Rule,
                ItemKind::Tool,
            ]
            .iter()
            .any(|k| k.dir() == first)
        }
        _ => false,
    }
}

/// Read a lifecycle hook scalar (`install:`/`update:`/`uninstall:`, HOOK-130)
/// from an item's already-read meta file frontmatter. Read for EVERY kind: a
/// skill's `SKILL.md`, a tool's `TOOL.md`, and an agent's, rule's, or command's
/// own `.md`, so an item can declare its own hooks without the source's root
/// manifest having to become authoritative for the whole repo. An empty or
/// whitespace-only value is treated as absent (HOOK-3).
///
/// spec: HOOK-130
fn lifecycle_frontmatter(meta_text: &str, key: &str) -> Option<String> {
    nonempty(frontmatter::field(meta_text, key))
}

/// The hooks an item declares for itself, for an item whose root `mind.toml`
/// `[[items]]` entry declared none (or that was found by convention, which has
/// no entry at all): the item directory's own `mind.toml` `[[hooks]]`
/// (HOOK-131) when it declares any, else the item's frontmatter scalars
/// (HOOK-130), each as one required hook of its event.
///
/// The two sites do not merge (HOOK-132). Only a directory-backed kind can
/// carry an item manifest; an agent, rule, or command IS its file and has no
/// directory of its own to put one in.
///
/// `Ok(None)` means "drop this item": its own `mind.toml` is unreadable as an
/// item manifest, and a warning naming the file has been printed (DSC-98). The
/// failure is scoped to the item rather than the scan, so one stray manifest in
/// one source cannot take down `recall`/`probe`/`learn` for every melded
/// source; dropping the item (rather than treating it as hook-free) keeps the
/// HOOK-131 guarantee that a malformed manifest never degrades to "this item
/// declares no hooks", since an item nobody is offered can run no hook.
// spec: HOOK-131 HOOK-132 DSC-98
fn item_declared_hooks(
    manifest_dir: Option<&Path>,
    source: &Source,
    kind: ItemKind,
    name: &str,
    path: &Path,
    meta_text: &str,
) -> Result<Option<Vec<ResolvedHook>>> {
    // HOOK-131: the source's own root `mind.toml` is never read as an item
    // manifest. An item may point AT the source root (`[[items]] path = "."`),
    // where the two files are the same file; reading it as an item manifest
    // would reject the source's own inventory as an unknown key.
    // `path.is_dir()`: a declared skill may point at its `SKILL.md` rather than
    // the directory holding it, and a file has no item manifest beside it.
    if matches!(kind, ItemKind::Skill | ItemKind::Tool)
        && path.is_dir()
        && !manifest_dir.is_some_and(|dir| same_dir(path, dir))
    {
        let manifest_path = path.join("mind.toml");
        let loaded = crate::mindfile::ItemToml::load(path)
            .and_then(|m| m.map(|m| m.resolved_hooks(&manifest_path)).transpose());
        match loaded {
            Ok(Some(hooks)) if !hooks.is_empty() => return Ok(Some(hooks)),
            Ok(_) => {}
            // spec: DSC-98 DSC-102
            Err(e) => {
                record_unreadable(&source.name, kind, name);
                crate::render::scan_warn(format!(
                    "warning: skipping {} '{}' in source '{}': {e}",
                    kind.as_str(),
                    crate::sanitize::strip_ansi(name),
                    crate::sanitize::strip_ansi(&source.name)
                ));
                return Ok(None);
            }
        }
    }
    let mut out: Vec<ResolvedHook> = Vec::new();
    for (key, event) in [
        ("install", HookEvent::Install),
        ("update", HookEvent::Update),
        ("uninstall", HookEvent::Uninstall),
    ] {
        if let Some(run) = lifecycle_frontmatter(meta_text, key) {
            out.push(ResolvedHook {
                run,
                name: None,
                optional: false,
                event,
            });
        }
    }
    Ok(Some(out))
}

/// Whether two paths name the same directory, comparing canonicalized forms
/// (so `<root>/.` and `<root>` match) and falling back to the literal paths
/// when either cannot be canonicalized.
fn same_dir(a: &Path, b: &Path) -> bool {
    let canon = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
    canon(a) == canon(b)
}

/// 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_text: &str,
    key: &str,
) -> Option<String> {
    if kind != ItemKind::Tool {
        return None;
    }
    match explicit {
        Some(v) => Some(v),
        None => frontmatter::field(meta_text, key),
    }
}

/// Field overrides from a `[[items]]` declaration, plus the per-item scan
/// context. Every override 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<'a> {
    description: Option<String>,
    link: Option<String>,
    bin: Option<String>,
    build: Option<String>,
    /// The item's fully resolved lifecycle hooks (HOOK-86) in execution order:
    /// the scalar install/update/uninstall shorthand folded in ahead of any
    /// `[[items.hooks]]` array entries. `Some` only when the `[[items]]` entry
    /// declared at least one hook, which makes it authoritative for this item
    /// (HOOK-132); `None` lets `build_item` fall through to the item's own
    /// declaration sites (its directory manifest, else its frontmatter).
    hooks: Option<Vec<ResolvedHook>>,
    /// The item's own `[[items]].ignore` (IGN-1), when it declared one. `None`
    /// means "not declared", which `resolve_ignores` fills from the source
    /// list; `Some(vec![])` is an explicit "no patterns" that overrides it.
    ignore: Option<Vec<String>>,
    /// The directory whose `mind.toml` is the SOURCE's manifest, never an
    /// item's (HOOK-131): an item whose path IS that directory
    /// (`[[items]] path = "."`) must not have the source's own inventory read
    /// as its item manifest.
    ///
    /// Not simply the clone root: a convention scan passes the SCAN root, which
    /// is `clone_root.join(r)` for each `[source].roots` / `--root` entry, and
    /// a plugin scan passes the plugin root. So the guard fires only when an
    /// item sits at the root it was scanned from -- which is where the two
    /// files could be the same file. `None` disables the guard entirely.
    manifest_dir: Option<&'a Path>,
}

/// 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.
///
/// `Ok(None)` means the item is dropped from the catalog with a warning already
/// printed: today only DSC-98 (an unreadable item manifest) does that.
///
/// spec: DSC-91 -- the meta file (`SKILL.md`/`TOOL.md`/agent/rule/command
/// `.md`) is read ONCE here, size-capped, and every frontmatter lookup below
/// runs against that one text; an oversized meta file fails the scan with
/// `MindError::MetadataTooLarge` instead of being read in full.
///
/// spec: WF-55 -- with one exception, the workflow. A workflow's "meta file" is
/// its whole `.js` body, so the cap would make one oversized file fail the scan
/// of the entire source. The read stays capped (a source is untrusted), but for
/// this kind an over-cap file reads as NO readable metadata and the item is
/// catalogued without a description, which is the WF-5 "yields nothing" case
/// and lands in WF-30's `workflow-unloadable` report.
fn build_item(
    source: &Source,
    prefix: &Option<String>,
    kind: ItemKind,
    name: String,
    path: PathBuf,
    meta: &Path,
    ov: ItemOverrides<'_>,
) -> Result<Option<CatalogItem>> {
    // L14: one capped read per item per scan. Each `frontmatter::field` call
    // below parses this text rather than re-reading the file, so adding a key
    // to the set an item may declare costs no additional I/O.
    // spec: RES-5 -- a resource carries no metadata of its own, so nothing is
    // read from it: no description, `requires`, `expand`, or hook scalars,
    // whatever its extension, and a large data file cannot trip the cap.
    let meta_text = if kind == ItemKind::Resource {
        String::new()
    } else {
        match frontmatter::text_capped(meta) {
            Ok(text) => text,
            // spec: WF-55 -- workflows only. Every other kind keeps DSC-91's
            // hard failure: their meta file is a small header beside the
            // content, and an 8 MiB one is a defect worth stopping on, not
            // something to catalogue with a silently missing description.
            Err(MindError::MetadataTooLarge { .. }) if kind == ItemKind::Workflow => String::new(),
            Err(e) => return Err(e),
        }
    };
    // HOOK-132: exactly one declaration site supplies an item's hooks. A
    // `[[items]]` entry that declared any is authoritative and the caller passes
    // it here (`ItemDecl::resolved_item_hooks`: scalar shorthand folded ahead of
    // the `[[items.hooks]]` array). Otherwise the item speaks for itself, via
    // its own directory manifest (HOOK-131) or its frontmatter (HOOK-130).
    let hooks = match ov.hooks {
        Some(hooks) => hooks,
        None => {
            match item_declared_hooks(ov.manifest_dir, source, kind, &name, &path, &meta_text)? {
                Some(hooks) => hooks,
                // spec: DSC-98 -- the item's own manifest is unreadable; drop
                // the item (warned) instead of the whole scan.
                None => return Ok(None),
            }
        }
    };
    // 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::field(&meta_text, "requires")
        .map(|s| s.split_whitespace().map(str::to_owned).collect())
        .unwrap_or_default();
    // NS-57: read the `expand:` frontmatter scalar the same way -- a
    // whitespace-split list of item-relative files to expand tokens in, even
    // though they are not markdown. Absent or empty -> empty Vec.
    let expand: Vec<String> = frontmatter::field(&meta_text, "expand")
        .map(|s| s.split_whitespace().map(str::to_owned).collect())
        .unwrap_or_default();
    // NS-56: a `description:` (or any other non-`name:` frontmatter field) may
    // carry a `{{ns:name}}` token wrapped by `templatize`/`review --fix`. The
    // catalog is a display surface (`recall`/`probe`/`dump`), not the expanded
    // store copy, so flatten it to the bare name here -- the single capture
    // point -- rather than showing the raw token to a human.
    //
    // spec: DSC-94 -- B4: a source-controlled description (frontmatter or an
    // `[[items]]` override) reaches every display surface (`recall`, `probe
    // --no-tui`, `--json`) from this one capture point, so sanitize it here
    // exactly as the plugin-manifest path already does (commands.rs), closing
    // the raw-ANSI/bidi-override gap for the biggest funnel of source text.
    //
    // spec: WF-4 WF-5 WF-51 -- a workflow's description and `whenToUse` come
    // from its `meta` object rather than a frontmatter block, read out of the
    // same one capped text (`meta_text` IS the whole `.js` file here). An
    // `[[items]].description` override still wins, as for every kind (DSC-32),
    // and leaves `whenToUse` standing.
    let wf_meta = if kind == ItemKind::Workflow {
        crate::workflow_meta::parse(&meta_text)
    } else {
        crate::workflow_meta::WorkflowMeta::default()
    };
    let sanitized = |d: String| crate::sanitize::strip_ansi(&namespace::flatten_display(&d));
    let description = match ov.description {
        Some(d) => Some(d),
        None => match kind {
            // A blank `description: ''` is no description, so it reads as the
            // WF-5 "yields nothing" case rather than an empty one.
            ItemKind::Workflow => wf_meta.description.filter(|d| !d.trim().is_empty()),
            _ => frontmatter::field(&meta_text, "description"),
        },
    }
    .map(sanitized);
    let when_to_use = wf_meta
        .when_to_use
        .filter(|w| !w.trim().is_empty())
        .map(sanitized);
    Ok(Some(CatalogItem {
        kind,
        name,
        source: source.name.clone(),
        prefix: prefix.clone(),
        path,
        description,
        when_to_use,
        link_rel: ov.link,
        bin: tool_field(kind, ov.bin, &meta_text, "bin"),
        build: tool_field(kind, ov.build, &meta_text, "build"),
        requires,
        // spec: IGN-1 -- carried as declared; `resolve_ignores` fills a `None`
        // from the source-level list once the whole scan is in hand.
        ignore: ov.ignore,
        expand,
        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, ItemKind::Skill)? {
        // The glob points at the SKILL.md; the item is its parent dir.
        // resolve_globs already validated the derived name (DSC-81/DSC-96), so
        // make_item's skip path is not expected to trigger here; handle it
        // anyway rather than assuming.
        if let Some(dir) = skill_md.parent()
            && let Some(item) = make_item(
                root,
                source,
                prefix,
                ItemKind::Skill,
                dir.to_path_buf(),
                &skill_md,
            )?
        {
            out.push(item);
        }
    }
    for (kind, globs) in [
        (ItemKind::Agent, &discover.agents),
        (ItemKind::Rule, &discover.rules),
        // spec: CMD-4 -- `[discover].commands` globs match the command FILE.
        // spec: WF-6 -- and `[discover].workflows` the workflow FILE, as the
        // agent, rule, and command globs do.
        (ItemKind::Command, &discover.commands),
        (ItemKind::Workflow, &discover.workflows),
    ] {
        for md in resolve_globs(root, globs, kind)? {
            if let Some(item) = make_item(root, source, prefix, kind, md.clone(), &md)? {
                out.push(item);
            }
        }
    }
    // Tool globs match the tool directory itself; its `TOOL.md` (if any) is the
    // metadata source.
    for dir in resolve_globs(root, &discover.tools, ItemKind::Tool)? {
        if !tool_anchor_ok(&dir) {
            continue;
        }
        let meta = dir.join("TOOL.md");
        if let Some(item) = make_item(root, source, prefix, ItemKind::Tool, dir, &meta)? {
            out.push(item);
        }
    }
    // spec: RES-4 -- resource globs match the entry itself, a file or a
    // directory; anything else a pattern matches (a fifo, a socket) is not one.
    for entry in resolve_globs(root, &discover.resources, ItemKind::Resource)? {
        if !(is_regular_file_nofollow(&entry) || is_dir_nofollow(&entry)) {
            continue;
        }
        if let Some(item) = make_item(
            root,
            source,
            prefix,
            ItemKind::Resource,
            entry.clone(),
            &entry,
        )? {
            out.push(item);
        }
    }
    Ok(())
}

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

/// The file extension a single-file kind's convention scan requires, without the
/// dot. A directory kind (skill, tool) reports `""` as a sentinel meaning "no
/// file extension applies"; that is safe only because every current caller in
/// this loop passes Agent/Rule/Command/Workflow, never Skill or Tool.
/// `Path::extension` is NOT guaranteed to never equal `""`: a file literally
/// named `foo.` (`Path::new("foo.").extension()`) is `Some("")`, so a Skill or
/// Tool arm added here later would need its own guard, not this sentinel.
///
/// spec: WF-3 -- `.js` for a workflow, `.md` for every other file kind.
fn kind_extension(kind: ItemKind) -> &'static str {
    match kind {
        ItemKind::Agent | ItemKind::Rule | ItemKind::Command => "md",
        ItemKind::Workflow => "js",
        ItemKind::Skill | ItemKind::Tool | ItemKind::Resource => "",
    }
}

/// Convention scan: fixed `skills/`, `agents/`, `rules/`, `commands/`,
/// `workflows/`, and `tools/` 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())
    };
    let skill_entries = if flat_skills {
        read_dir_opt(&skills_dir)?
    } else {
        read_container_opt(&skills_dir)?
    };
    for entry in skill_entries {
        let skill_md = entry.join("SKILL.md");
        // spec: DSC-108 -- no-follow for BOTH halves of the skill shape. A
        // symlinked anchor is the worse of the two: `SKILL.md` is the file whose
        // frontmatter becomes the item's description, so following it would
        // republish a linked-to file's `description:` into the catalog on top of
        // answering whether the path exists.
        if is_dir_nofollow(&entry)
            && is_regular_file_nofollow(&skill_md)
            && let Some(item) = make_item(root, source, prefix, ItemKind::Skill, entry, &skill_md)?
        {
            out.push(item);
        }
    }

    // spec: CMD-1 CMD-2 -- a command is a flat `commands/<name>.md`, the same
    // shape (and so the same scan) as an agent or a rule.
    // spec: WF-1 WF-2 WF-3 -- a workflow is the same shape again, flat under
    // `workflows/`, differing only in extension. `.js` is compared
    // case-sensitively, as the harness compares it: a `.JS`, `.mjs`, or `.ts`
    // sibling would never load, so mind does not discover it either.
    for kind in [
        ItemKind::Agent,
        ItemKind::Rule,
        ItemKind::Command,
        ItemKind::Workflow,
    ] {
        let ext = kind_extension(kind);
        let kind_dir = root.join(kind.dir());
        for entry in read_container_opt(&kind_dir)? {
            // spec: DSC-108 -- no-follow classification, so a symlink here is
            // not an item whatever it points at.
            if is_regular_file_nofollow(&entry)
                && entry.extension().is_some_and(|e| e == ext)
                && let Some(item) = make_item(root, source, prefix, kind, entry.clone(), &entry)?
            {
                out.push(item);
            }
        }
    }

    // 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_container_opt(&tools_dir)? {
        // spec: DSC-108 -- a tool needs no anchor file, so the directory
        // classification is the entire test of whether the item exists; a
        // symlink there is the oracle in its purest form.
        if is_dir_nofollow(&entry) && tool_anchor_ok(&entry) {
            let meta = entry.join("TOOL.md");
            if let Some(item) = make_item(root, source, prefix, ItemKind::Tool, entry, &meta)? {
                out.push(item);
            }
        }
    }

    // spec: RES-1 -- every immediate entry of `resources/` that is a regular
    // file or a directory, classified no-follow (DSC-108), and not a dot-entry
    // (`.gitkeep`, `.DS_Store`). Whether each is offered is decided after the
    // whole source is scanned (RES-3, `prune_unreferenced_resources`).
    let resources_dir = root.join(ItemKind::Resource.dir());
    for entry in read_container_opt(&resources_dir)? {
        if file_name(&entry).starts_with('.') {
            continue;
        }
        if (is_regular_file_nofollow(&entry) || is_dir_nofollow(&entry))
            && let Some(item) = make_item(
                root,
                source,
                prefix,
                ItemKind::Resource,
                entry.clone(),
                &entry,
            )?
        {
            out.push(item);
        }
    }
    Ok(())
}

/// Build a [`CatalogItem`], deriving its bare name from the path and its
/// description from `meta_file`'s frontmatter, then applying the prefix.
///
/// Returns `Ok(None)` -- skipping the item rather than failing the whole scan
/// -- when the derived name fails the DSC-96 safety check (a control
/// character or a security-blocked Unicode code point): unlike an explicit
/// `[[items]]` declaration (a hard error, since the author wrote the name),
/// a convention-derived name comes from an arbitrary filename in the source
/// tree, so one hostile file should not make an otherwise-good repo
/// un-meldable. A warning is printed to stderr so the skip is not silent.
/// `build_item` skips on the same terms when the item's own `mind.toml` is
/// unreadable (DSC-98).
///
/// spec: DSC-91 -- bubbles a size-cap failure from `build_item`'s capped
/// frontmatter read.
fn make_item(
    root: &Path,
    source: &Source,
    prefix: &Option<String>,
    kind: ItemKind,
    path: PathBuf,
    meta: &Path,
) -> Result<Option<CatalogItem>> {
    let bare = match kind {
        // Directory-shaped items take the directory name; file items the stem.
        ItemKind::Skill | ItemKind::Tool => file_name(&path),
        // spec: RES-2 -- a resource keeps its full file name, extension
        // included, so `allowlist.json` and `allowlist.yaml` stay distinct.
        ItemKind::Resource => file_name(&path),
        // spec: WF-1 WF-21 -- a workflow's name is its file stem, as for every
        // other file-shaped kind, and NOT its `meta.name` (WF-20).
        ItemKind::Agent | ItemKind::Rule | ItemKind::Command | ItemKind::Workflow => path
            .file_stem()
            .map(|s| s.to_string_lossy().into_owned())
            .unwrap_or_default(),
    };
    // spec: DSC-96 DSC-102
    if !is_safe_item_name(&bare) {
        crate::render::scan_warn(format!(
            "warning: skipping {} '{}' in source '{}': unsafe item name (a control character or \
             a bidi/zero-width Unicode code point)",
            kind.as_str(),
            crate::sanitize::strip_ansi(&bare),
            crate::sanitize::strip_ansi(&source.name)
        ));
        return Ok(None);
    }
    // Convention discovery carries no overrides: every field falls back to the
    // item's own declaration sites (HOOK-131/132: its directory manifest, else
    // its frontmatter). `root` is the scan root this item was found under, which
    // is the one directory whose `mind.toml` could be the source's own.
    build_item(
        source,
        prefix,
        kind,
        bare,
        path,
        meta,
        ItemOverrides {
            manifest_dir: Some(root),
            ..ItemOverrides::default()
        },
    )
}

/// Scan a plugin root for the four components a plugin and `mind` share:
/// skills, agents, commands, and workflows (MKT-3, MKT-18, WF-40).
///
/// A plugin's component layout matches `mind`'s convention layout (DSC-10,
/// DSC-11, DSC-14, WF-2): `skills/<name>/SKILL.md` -> Skill, `agents/<name>.md`
/// -> Agent, `commands/<name>.md` -> Command, `workflows/<name>.js` -> Workflow.
/// Rules and tools have no plugin equivalent and are not emitted, and a plugin
/// component with no `mind` equivalent (`hooks/`, `.mcp.json`, ...) is reported
/// instead ([`plugin_skipped_components`], MKT-4). 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_container_opt(&skills_dir)? {
        let skill_md = entry.join("SKILL.md");
        // spec: DSC-108 -- classified exactly as the convention scan's skills
        // are: the rule is the scan's, not one layout's.
        if is_dir_nofollow(&entry)
            && is_regular_file_nofollow(&skill_md)
            && let Some(item) = make_item(
                plugin_root,
                source,
                prefix,
                ItemKind::Skill,
                entry,
                &skill_md,
            )?
        {
            out.push(item);
        }
    }
    // 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_container_opt(&agents_dir)? {
        // spec: DSC-108 -- an `agents/<name>.md` is classified the same way here
        // as in the convention scan; a plugin layout is not a second answer to
        // whether a symlink is an item.
        if is_regular_file_nofollow(&entry)
            && entry.extension().is_some_and(|e| e == "md")
            && let Some(item) = make_item(
                plugin_root,
                source,
                prefix,
                ItemKind::Agent,
                entry.clone(),
                &entry,
            )?
        {
            out.push(item);
        }
    }
    // Commands and workflows: flat `commands/<name>.md` (DSC-14, MKT-18) and
    // `workflows/<name>.js` (WF-2, WF-40) at the plugin root. Both sit at mind's
    // own convention path, so they map like agents do.
    scan_plugin_flat_items(plugin_root, source, prefix, out)?;
    Ok(())
}

/// Scan a plugin root's flat single-file components: `commands/<name>.md`
/// (MKT-18) and `workflows/<name>.js` (WF-40).
///
/// Shared by the single-plugin scan and the marketplace in-repo entry scan, so
/// both map a plugin's commands and workflows the same way. A missing directory
/// yields nothing (DSC-13). The scan is flat and extension-exact, per CMD-2 and
/// WF-2/WF-3; what it leaves behind is counted by [`unmapped_flat_entries`] so
/// the drop is not silent (MKT-4).
// spec: MKT-18 CMD-1 WF-40
fn scan_plugin_flat_items(
    plugin_root: &Path,
    source: &Source,
    prefix: &Option<String>,
    out: &mut Vec<CatalogItem>,
) -> Result<()> {
    for kind in [ItemKind::Command, ItemKind::Workflow] {
        let ext = kind_extension(kind);
        let kind_dir = plugin_root.join(kind.dir());
        for entry in read_container_opt(&kind_dir)? {
            // spec: DSC-108 -- a plugin's flat components are classified the
            // same no-follow way as the convention scan's.
            if is_regular_file_nofollow(&entry)
                && entry.extension().is_some_and(|e| e == ext)
                && let Some(item) =
                    make_item(plugin_root, source, prefix, kind, entry.clone(), &entry)?
            {
                out.push(item);
            }
        }
    }
    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 = crate::sanitize::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/NS-28): fall back to no prefix when entry name is
                    // a reserved kind word or not a safe path component, rather than making
                    // the entry un-installable.  Note: we use is_safe_prefix_component here
                    // rather than validate_prefix because the NS-29 extended reserved list
                    // is a gate for user-supplied prefixes only; auto-generated names from
                    // marketplace entry names (e.g. "plugin") must remain usable.
                    if !entry_name.is_empty()
                        && namespace::is_safe_prefix_component(&entry_name)
                        && !matches!(entry_name.as_str(), "skill" | "agent" | "rule" | "tool")
                    {
                        Some(entry_name.clone())
                    } else {
                        None
                    }
                }
            }
        } else {
            // No override; use entry name as default namespace prefix (MKT-8).
            // Resilience (NS-25/NS-28): same rationale as above -- use the
            // is_safe_prefix_component check rather than the full validate_prefix so
            // that NS-29 words (e.g. "plugin") remain valid auto-generated prefixes.
            if !entry_name.is_empty()
                && namespace::is_safe_prefix_component(&entry_name)
                && !matches!(entry_name.as_str(), "skill" | "agent" | "rule" | "tool")
            {
                Some(entry_name.clone())
            } else {
                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");
                // spec: DSC-108 -- no-follow, as in every other scan route.
                if is_dir_nofollow(&skill_dir)
                    && is_regular_file_nofollow(&skill_md)
                    && let Some(item) = make_item(
                        &plugin_root,
                        source,
                        &plugin_prefix,
                        ItemKind::Skill,
                        skill_dir,
                        &skill_md,
                    )?
                {
                    out.push(item);
                }
            }
        } else {
            // No explicit skills array: scan plugin_root/skills/ conventionally.
            let skills_dir = plugin_root.join(ItemKind::Skill.dir());
            for entry_path in read_container_opt(&skills_dir)? {
                let skill_md = entry_path.join("SKILL.md");
                // spec: DSC-108
                if is_dir_nofollow(&entry_path)
                    && is_regular_file_nofollow(&skill_md)
                    && let Some(item) = make_item(
                        &plugin_root,
                        source,
                        &plugin_prefix,
                        ItemKind::Skill,
                        entry_path,
                        &skill_md,
                    )?
                {
                    out.push(item);
                }
            }
        }

        // 4. Scan agents and commands (always): agents/<name>.md and
        //    commands/<name>.md at the plugin root (DSC-11, DSC-14, MKT-3,
        //    MKT-18). Neither is ever narrowed by the entry's explicit `skills`
        //    list, which only ever names skill directories.
        let agents_dir = plugin_root.join(ItemKind::Agent.dir());
        for agent_path in read_container_opt(&agents_dir)? {
            // spec: DSC-108
            if is_regular_file_nofollow(&agent_path)
                && agent_path.extension().is_some_and(|e| e == "md")
                && let Some(item) = make_item(
                    &plugin_root,
                    source,
                    &plugin_prefix,
                    ItemKind::Agent,
                    agent_path.clone(),
                    &agent_path,
                )?
            {
                out.push(item);
            }
        }
        scan_plugin_flat_items(&plugin_root, source, &plugin_prefix, out)?;
    }
    Ok(())
}

/// Count unsupported Claude plugin components present at a plugin root (MKT-4).
///
/// Checks for the directory-based component with no `mind` equivalent
/// (`hooks/`) 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 calls it at meld time
/// and prints the summary via `SkippedComponents::summary`.
///
/// spec: MKT-18 WF-40 -- a `commands/<name>.md` or `workflows/<name>.js` file
/// is NOT counted: it maps to the `command` or `workflow` kind and is
/// installed, so reporting it as skipped would be a lie in the one message
/// whose job is to say what was dropped.
/// spec: MKT-4 -- but an entry those scans do NOT map (both are flat and
/// extension-exact, CMD-2 and WF-2/WF-3) is counted, so a nested
/// `commands/frontend/component.md`, a `commands/do.sh`, or a
/// `workflows/deploy.ts` is reported rather than dropped in silence.
pub fn plugin_skipped_components(plugin_root: &Path) -> plugin_manifest::SkippedComponents {
    let mut sc = plugin_manifest::SkippedComponents::default();
    if plugin_root.join("hooks").is_dir() {
        sc.hooks = 1;
    }
    if plugin_root.join(".mcp.json").is_file() {
        sc.mcp_servers = 1;
    }
    sc.commands = unmapped_flat_entries(
        &plugin_root.join(ItemKind::Command.dir()),
        kind_extension(ItemKind::Command),
    );
    sc.workflows = unmapped_flat_entries(
        &plugin_root.join(ItemKind::Workflow.dir()),
        kind_extension(ItemKind::Workflow),
    );
    sc
}

/// How many entries of a plugin's `commands/` or `workflows/` directory the
/// flat, extension-exact scan ([`scan_plugin_flat_items`]) leaves behind: every
/// subdirectory (the nested `commands/<group>/<name>.md` layout the harness
/// allows, CMD-2) and every file with the wrong extension. One count per
/// immediate entry, not per nested file: the entry is what the user sees in the
/// repo.
///
/// A dot-prefixed entry (`.gitkeep`, `.DS_Store`) is not counted: it is not a
/// component an author meant to publish, and reporting it as a dropped one
/// would make the note noise. A read failure counts nothing either: this is a
/// report, and it must not turn a permission error on one directory into a
/// failed meld.
// spec: MKT-4
fn unmapped_flat_entries(dir: &Path, ext: &str) -> u32 {
    // spec: MKT-4 DSC-108 -- a symlinked `commands/`/`workflows/` folder is
    // never scanned (`read_container_opt`), so it is one unmapped entry; it is
    // not listed, since listing it would walk a directory outside the source.
    if is_symlink(dir) {
        return 1;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return 0;
    };
    let mut n = 0;
    for entry in entries.flatten() {
        let path = entry.path();
        if file_name(&path).starts_with('.') {
            continue;
        }
        // spec: DSC-108 MKT-4 -- "mapped" must mean exactly what the scan maps,
        // classified the same no-follow way. A symlinked `workflows/x.js` is not
        // an item (DSC-108), so counting it as mapped here would make it the one
        // thing MKT-4 exists to prevent: a component dropped in silence.
        let mapped = is_regular_file_nofollow(&path) && path.extension().is_some_and(|e| e == ext);
        if !mapped {
            n += 1;
        }
    }
    n
}

/// 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"),
        // A workflow has no frontmatter file either; its own `.js` is what
        // `build_item` reads, for the `meta` object rather than a `---` block
        // (WF-4, WF-5).
        ItemKind::Agent | ItemKind::Rule | ItemKind::Command | ItemKind::Workflow => {
            path.to_path_buf()
        }
        // spec: RES-5 -- never read: `build_item` skips the metadata read for a
        // resource, whose content is data rather than a frontmatter header.
        ItemKind::Resource => path.to_path_buf(),
    }
}

/// Expand a glob pattern rooted at `root`, returning sorted matches.
fn glob_paths(root: &Path, pattern: &str, kind: ItemKind) -> Result<Vec<PathBuf>> {
    // spec: DSC-81 -- confinement of [discover] globs to the clone root.
    // Reject absolute patterns and patterns with `..` components up front,
    // before the glob expands and before any filesystem access.
    {
        let pp = Path::new(pattern);
        // DSC-95: the glob is source-controlled and is echoed back in the
        // rejection message, so sanitize it before it reaches stderr -- an
        // absolute/`..` glob is exactly the hostile-source case, and its raw
        // text must not carry a terminal-injection payload.
        if pp.is_absolute() || pattern.starts_with('~') {
            return Err(MindError::MindToml {
                path: root.join("mind.toml"),
                msg: format!(
                    "discover glob '{}' is absolute; globs must be relative to the repo root",
                    crate::sanitize::strip_ansi(pattern)
                ),
            });
        }
        use std::path::Component;
        if pp.components().any(|c| c == Component::ParentDir) {
            return Err(MindError::MindToml {
                path: root.join("mind.toml"),
                msg: format!(
                    "discover glob '{}' contains '..'; globs must not escape the repo root",
                    crate::sanitize::strip_ansi(pattern)
                ),
            });
        }
    }

    // Canonicalize the root FIRST and glob from that (rather than globbing from
    // `root` and canonicalizing each match) so a match that is a dangling
    // symlink -- whose own canonicalize() fails and falls back to the matched
    // path verbatim -- still falls back to a path under `canonical_root`: on a
    // host where the temp root itself is behind a symlink (e.g. macOS's `/tmp`
    // -> `/private/tmp`), the fallback path failed `starts_with` against the
    // resolved root below and misreported a merely-dangling link as an
    // escaping one, before DSC-108's symlink filter ever got a look at it.
    let canonical_root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let joined = canonical_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 '{}': {e}",
            crate::sanitize::strip_ansi(pattern)
        ),
    })?;
    let mut out = Vec::new();
    for entry in paths {
        match entry {
            Ok(p) => {
                // spec: DSC-81 -- canonicalize each match and verify it stays
                // within the clone root. A symlink that points outside the root
                // would pass a lexical `starts_with` but fail after canonicalization.
                let canonical = p.canonicalize().unwrap_or_else(|_| p.clone());
                if !canonical.starts_with(&canonical_root) {
                    return Err(MindError::MindToml {
                        path: root.join("mind.toml"),
                        msg: format!(
                            "discover glob '{}' matched '{}' which is outside the repo root",
                            crate::sanitize::strip_ansi(pattern),
                            crate::sanitize::strip_ansi(&p.display().to_string())
                        ),
                    });
                }
                // spec: DSC-114 DSC-109 -- a workflow IS one `.js` file (WF-1),
                // so a glob match that is not a regular, non-symlink `.js` file
                // (a directory, a `README.md`, a link) is not a workflow. Dropped
                // silently, like the DSC-108 filter below, and placed after the
                // DSC-81 escape check so an escaping link stays a hard error.
                if kind == ItemKind::Workflow
                    && !(is_regular_file_nofollow(&p) && p.extension().is_some_and(|e| e == "js"))
                {
                    continue;
                }
                // Derive the item name from the matched path and verify it is safe.
                // spec: DSC-83 -- for skill globs the pattern points at SKILL.md;
                // the bare skill name is the parent directory name. For all other
                // kinds the matched path's stem is the bare name.
                let item_name = if kind == ItemKind::Skill {
                    p.parent()
                        .and_then(|d| d.file_name())
                        .map(|s| s.to_string_lossy().into_owned())
                        .unwrap_or_default()
                } else if kind == ItemKind::Resource {
                    // spec: RES-2 RES-4 -- the full file name, extension kept.
                    file_name(&p)
                } else {
                    p.file_stem()
                        .or_else(|| p.file_name())
                        .map(|s| s.to_string_lossy().into_owned())
                        .unwrap_or_default()
                };
                if !is_safe_item_name(&item_name) {
                    return Err(MindError::MindToml {
                        path: root.join("mind.toml"),
                        msg: format!(
                            "discover glob '{}' matched '{}' whose derived name '{}' is unsafe",
                            crate::sanitize::strip_ansi(pattern),
                            crate::sanitize::strip_ansi(&p.display().to_string()),
                            crate::sanitize::strip_ansi(&item_name)
                        ),
                    });
                }
                // spec: DSC-108 -- a glob matches by NAME, so without this the
                // authoritative layer is a second route to the very oracle the
                // convention scan's no-follow classification closes. Dropped
                // silently (as the convention scan drops such an entry) rather
                // than refused: a pattern matching a stray link is not an
                // authoring error the way an escaping or unsafely-named match
                // is. Placed AFTER the DSC-81 escape check on purpose, so a link
                // resolving outside the root stays the hard error it was.
                // For a skill glob the match is the anchor and the ITEM is its
                // parent directory, so both have to be the repo's own entries.
                let linked = is_symlink(&p)
                    || (kind == ItemKind::Skill && p.parent().is_some_and(is_symlink));
                if linked {
                    continue;
                }
                // The glob ran under the canonical root; hand back the match
                // under the root the caller named, so the item's path keeps the
                // non-canonical form every other scan path carries (DSC-81).
                out.push(root.join(p.strip_prefix(&canonical_root).unwrap_or(&p)));
            }
            Err(e) => {
                let path = e.path().to_path_buf();
                return Err(MindError::io(path, e.into()));
            }
        }
    }
    out.sort();
    Ok(out)
}

/// True when `path` is a REGULAR file, classified WITHOUT following a symlink.
///
/// The scan runs over a tree the source controls entirely, so `Path::is_file`
/// (which follows) would answer about whatever a symlink points
/// at: a repo full of `workflows/<probe>.js` symlinks aimed at absolute paths on
/// the machine running the scan turns the item listing into a file-existence
/// oracle, and `review`'s size report would print a linked-to file's byte count.
/// Classifying by symlink metadata keeps every answer about the repo's own
/// entries. It also matches the install copy walk, which rejects a symlink
/// inside an item tree outright (LIFE-42, `install::copy_recursive_at`), so a
/// symlink that is not discovered here was never installable anyway.
///
/// spec: DSC-108
fn is_regular_file_nofollow(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_file())
}

/// True when a tool directory's optional `TOOL.md` anchor is acceptable: absent
/// (a tool needs no anchor), or a regular non-symlink file. A symlinked or
/// non-file `TOOL.md` would have its target's `description`/`bin`/`build` read
/// into the catalog, so the tool is not offered.
///
/// spec: DSC-115
fn tool_anchor_ok(dir: &Path) -> bool {
    match std::fs::symlink_metadata(dir.join("TOOL.md")) {
        Ok(m) => m.file_type().is_file(),
        Err(_) => true,
    }
}

/// True when `path` is a directory, classified WITHOUT following a symlink.
///
/// The companion to [`is_regular_file_nofollow`] for the directory-shaped kinds.
/// A skill is a directory plus a `SKILL.md` anchor and a tool is a bare
/// directory, so without this the oracle the flat kinds close stays open one
/// kind over -- and for a skill it is worse than an existence bit, since the
/// anchor's frontmatter `description:` is read into the catalog and shown by
/// `recall`/`probe`. An item found through a link could not be installed anyway
/// (LIFE-42 refuses a symlinked item root in `install::copy_recursive_at`), so
/// discovering one only ever produces an offer `mind` cannot honor.
///
/// spec: DSC-108
fn is_dir_nofollow(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_dir())
}

/// True when `path` is itself a symlink (its LAST component; an intermediate
/// link is resolved, as everywhere else in the scan).
///
/// spec: DSC-108
fn is_symlink(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink())
}

/// Read a directory's entries, treating "not found" as empty.
/// [`read_dir_opt`] for a kind container (`skills/`, `agents/`, `workflows/`,
/// ...): a container that is itself a symlink yields nothing, since listing it
/// would walk a directory outside the source before the per-entry no-follow
/// checks ever ran.
///
/// spec: DSC-108
fn read_container_opt(dir: &Path) -> Result<Vec<PathBuf>> {
    if is_symlink(dir) {
        return Ok(Vec::new());
    }
    read_dir_opt(dir)
}

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;

    // ---- item-link path classification (LNK-20, WF-6) -----------------

    /// Only a `.js` directly under `workflows/` is a workflow. The two
    /// predicates pick different refusals, so the boundary between them is what
    /// decides whether the operator is told the path names an unsupported kind
    /// or an unlinkable file: a `lib/util.js` called a workflow would name an
    /// item that does not exist.
    // spec: WF-6 LNK-20
    #[test]
    fn only_a_js_directly_under_workflows_is_a_workflow_link_path() {
        for path in [
            "workflows/deploy.js",
            "pkg/workflows/deploy.js",
            "workflows/DEPLOY.js",
        ] {
            assert!(
                is_workflow_link_path(path),
                "'{path}' names a workflow file"
            );
            assert!(is_js_link_path(path), "'{path}' is also a JavaScript file");
        }

        for path in [
            // right extension, wrong place
            "lib/util.js",
            "deploy.js",
            "workflows/nested/deep.js",
            // right place, wrong extension: the scan is `.js`-exact (WF-3)
            "workflows/deploy.mjs",
            "workflows/deploy.ts",
            "workflows/deploy.js.md",
            "workflows/deploy",
        ] {
            assert!(
                !is_workflow_link_path(path),
                "'{path}' must not be called a workflow"
            );
        }

        for path in ["lib/util.js", "deploy.js", "workflows/nested/deep.js"] {
            assert!(
                is_js_link_path(path),
                "'{path}' is a JavaScript file, refused as one"
            );
        }
        for path in ["skills/review/SKILL.md", "agents/dev.md", "workflows"] {
            assert!(
                !is_js_link_path(path),
                "'{path}' is not a JavaScript file at all"
            );
        }
    }

    // ---- 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,
            as_alias: None,
            pin: Pin::default(),
            roots: None,
            flat_skills: false,
            full_history: false,
            add_roots: None,
            item_path: None,
            item_kind: None,
            curated_by: None,
            origin: None,
            plugin_version: None,
            install_hooks: Vec::new(),
            items_hooks: Vec::new(),
            install_hook: None,
            install_hook_commit: None,
            profiles: None,
            profile_snapshot: None,
            whole_snapshot: None,
            auto_update: 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}"
        );
    }

    // ---- CLI-212/CLI-213: a linked source whose clone dir has vanished ----

    // spec: CLI-212
    #[test]
    fn scan_source_reports_linked_source_gone_when_clone_dir_is_missing() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        // Never created: this source's linked working tree is "gone".
        let clone = base.join("sources/local/test/repo");

        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();
        match err {
            MindError::LinkedSourceGone {
                ref source_name,
                ref path,
            } => {
                assert_eq!(source_name, "local/test/repo");
                assert!(
                    path.contains("repo"),
                    "path must name the vanished dir: {path}"
                );
            }
            other => panic!("expected LinkedSourceGone, got {other:?}"),
        }
    }

    // spec: CLI-212
    // The PRECEDENCE clause: "raised ... BEFORE a less specific error (a
    // convention-scan `InvalidRoot`, or `MindToml::load` silently treating the
    // missing directory as 'no mind.toml') could obscure the real cause". Both
    // obscuring paths are reachable for the same vanished directory, and
    // neither was driven -- so nothing distinguished "the check exists" from
    // "the check runs early enough to matter".
    #[test]
    fn linked_source_gone_wins_over_the_less_specific_scan_errors() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let paths = paths_for(base);
        let clone = base.join("sources/local/test/repo"); // never created

        // (a) With a `--root` override set, a directory-based scan of a missing
        // root would report `InvalidRoot`, which names a root the user never
        // typed wrong instead of the real cause.
        let mut rooted = make_source_for(&clone);
        rooted.roots = Some(vec!["packages/agents".to_string()]);
        let mut items = Vec::new();
        assert!(
            matches!(
                scan_source(&paths, &rooted, &mut items).unwrap_err(),
                MindError::LinkedSourceGone { .. }
            ),
            "a vanished working tree must not be reported as an InvalidRoot"
        );

        // (b) Without any root override, `MindToml::load` treats the missing
        // directory as "no mind.toml" and the convention scan would simply find
        // nothing -- a silent, empty, successful scan. It must be the error
        // instead.
        let plain = make_source_for(&clone);
        let mut items = Vec::new();
        assert!(
            scan_source(&paths, &plain, &mut items).is_err(),
            "a vanished working tree must not scan as a healthy source with no items"
        );
        assert!(items.is_empty());
    }

    // spec: CLI-212 CLI-213
    #[test]
    fn scan_degrades_past_a_gone_linked_source_and_keeps_the_rest() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let paths = paths_for(base);

        // Source A: a real clone with one item.
        let clone_a = base.join("sources/local/a/repo");
        write_file(
            &clone_a.join("skills/alpha/SKILL.md"),
            "---\ndescription: alpha\n---\n# alpha\n",
        );
        let mut source_a = make_source_for(&clone_a);
        source_a.name = "local/a/repo".to_string();
        source_a.owner = "a".to_string();

        // Source B: a linked source whose clone dir was never created.
        let clone_b = base.join("sources/local/b/repo");
        let mut source_b = make_source_for(&clone_b);
        source_b.name = "local/b/repo".to_string();
        source_b.owner = "b".to_string();

        let registry = Registry {
            sources: vec![source_a, source_b],
        };
        let items = scan(&paths, &registry).expect(
            "scan() must degrade past the gone linked source, not hard-fail the whole call",
        );
        let names: Vec<_> = items.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["alpha"],
            "the gone source must be skipped and the good source's items kept: {names:?}"
        );
    }

    // spec: CLI-212
    // The narrowness of the degradation: any OTHER scan failure (here, a bad
    // --root) still aborts the whole `scan()` call exactly as before.
    #[test]
    fn scan_still_hard_fails_on_a_non_gone_scan_error() {
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(&clone.join("README.md"), "hi");

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

        let registry = Registry {
            sources: vec![source],
        };
        let err = scan(&paths, &registry).unwrap_err();
        assert!(
            matches!(err, MindError::InvalidRoot { .. }),
            "a non-LinkedSourceGone failure must still abort scan(): {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()),
            when_to_use: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        }
    }

    #[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,
            when_to_use: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        };
        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", "caf\u{00e9}"] {
            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_item_name_rejects_blocked_unicode() {
        // spec: DSC-96 -- a control character or a security-blocked Unicode
        // code point (bidi override, zero-width) is rejected even though it is
        // not a path separator, so a name cannot render identically to a
        // trusted item's name while installing as a distinct identity.
        for bad in [
            "revie\u{200B}w", // zero-width space mid-name
            "pay\u{202E}oot", // right-to-left override
            "a\x01b",         // C0 control character
        ] {
            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,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        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_bidi_name() {
        // spec: DSC-96 -- a declared `[[items]] name` carrying a security-blocked
        // Unicode code point is a hard error, since the author wrote it
        // explicitly (unlike a convention-derived name, which is skipped with a
        // warning instead, see `convention_scan_skips_item_with_unsafe_name`).
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = ItemDecl {
            kind: "rule".to_string(),
            name: "revie\u{200B}w".to_string(),
            path: "rules/x.md".to_string(),
            link: None,
            description: None,
            bin: None,
            build: None,
            install: None,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "a bidi/zero-width name must be a schema error: {err}"
        );
    }

    #[test]
    fn convention_scan_skips_item_with_unsafe_name_and_warns() {
        // spec: DSC-96 -- a convention-derived name (a filename in the source
        // tree, not an author-declared value) is skipped with a warning rather
        // than failing the whole scan, so one hostile filename does not make an
        // otherwise-good repo un-meldable.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(&root.join("rules/good.md"), "---\n---\n# good\n");
        write_file(&root.join("rules/b\u{200B}ad.md"), "---\n---\n# bad\n");
        let paths = paths_for(root);
        let source = make_source_for(root);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();
        assert_eq!(
            items.iter().filter(|i| i.kind == ItemKind::Rule).count(),
            1,
            "only the safely-named item should surface: {items:?}"
        );
        assert!(items.iter().any(|i| i.name == "good"));
        assert!(
            !items.iter().any(|i| i.name.contains('\u{200B}')),
            "the unsafely-named item must not be in the catalog"
        );
    }

    #[test]
    fn is_confined_link_target_requires_a_kind_directory() {
        // spec: DSC-97
        // The four original kind directories stay mutually interchangeable, so
        // a rule may still surface under any of them (TOOL-4's cross-kind case).
        for ok in [
            "skills/x",
            "agents/x.md",
            "rules/x.md",
            "tools/x",
            "./rules/x.md",
        ] {
            assert!(
                is_confined_link_target(ok, ItemKind::Rule),
                "{ok:?} should be accepted"
            );
        }
        for bad in ["settings.json", "hooks/x.json", ".claude/settings.json", ""] {
            assert!(
                !is_confined_link_target(bad, ItemKind::Rule),
                "{bad:?} should be rejected"
            );
        }
    }

    #[test]
    fn only_a_command_may_link_into_the_commands_directory() {
        // spec: DSC-97 -- a file under `commands/` is not inert: the harness
        // offers it as `/<name>`. So the cross-kind allowance stops at that one
        // directory; otherwise a source's rule (or skill, or tool) content
        // becomes an invocable slash command a consumer who filtered their
        // install to "rules only" never asked for.
        for kind in [
            ItemKind::Skill,
            ItemKind::Agent,
            ItemKind::Rule,
            ItemKind::Tool,
        ] {
            assert!(
                !is_confined_link_target("commands/deploy.md", kind),
                "{kind:?} must not be able to link into commands/"
            );
        }
        assert!(
            is_confined_link_target("commands/deploy.md", ItemKind::Command),
            "a command's own kind directory must still be allowed"
        );
        assert!(
            is_confined_link_target("commands/frontend/component.md", ItemKind::Command),
            "a command may still nest inside its own kind directory (CMD-2)"
        );
        // The reverse direction is unchanged: a command may surface under
        // another kind directory, like any other item.
        assert!(is_confined_link_target(
            "rules/deploy.md",
            ItemKind::Command
        ));
    }

    #[test]
    fn only_a_workflow_may_link_into_the_workflows_directory() {
        // spec: WF-8 -- `workflows/` carries DSC-97's extra condition for the
        // same reason `commands/` does: a file there is not content the harness
        // offers, it is something the harness runs.
        for kind in [
            ItemKind::Skill,
            ItemKind::Agent,
            ItemKind::Rule,
            ItemKind::Command,
            ItemKind::Tool,
        ] {
            assert!(
                !is_confined_link_target("workflows/deploy.js", kind),
                "{kind:?} must not be able to link into workflows/"
            );
        }
        assert!(
            is_confined_link_target("workflows/deploy.js", ItemKind::Workflow),
            "a workflow's own kind directory must be allowed"
        );
        // `workflows/` joins the accepted set, so a workflow may still surface
        // under another kind directory and the two conditions do not interfere.
        assert!(is_confined_link_target(
            "rules/deploy.md",
            ItemKind::Workflow
        ));
        assert!(!is_confined_link_target(
            "commands/deploy.md",
            ItemKind::Workflow
        ));
    }

    #[test]
    fn a_workflow_takes_its_description_and_when_to_use_from_meta() {
        // spec: WF-1 WF-2 WF-3 WF-4 WF-51
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("workflows/review.js"),
            "export const meta = {\n  name: 'review-changes',\n  \
             description: 'Review changed files',\n  whenToUse: 'before a PR',\n}\n",
        );
        // Flat and `.js`-only: neither of these is an item (WF-2, WF-3).
        write_file(
            &root.join("workflows/nested/deep.js"),
            "export const meta = {}",
        );
        write_file(&root.join("workflows/modern.mjs"), "export const meta = {}");
        let paths = paths_for(root);
        let source = make_source_for(root);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let wfs: Vec<_> = items
            .iter()
            .filter(|i| i.kind == ItemKind::Workflow)
            .collect();
        assert_eq!(wfs.len(), 1, "one flat `.js` workflow only: {items:?}");
        let wf = wfs[0];
        // spec: WF-21 -- the name is the file stem, NOT the `meta.name`.
        assert_eq!(wf.name, "review");
        assert_eq!(wf.description.as_deref(), Some("Review changed files"));
        assert_eq!(wf.when_to_use.as_deref(), Some("before a PR"));
        assert_eq!(
            wf.display_description().as_deref(),
            Some("Review changed files - before a PR"),
            "a display surface reads the pair as the harness renders it"
        );
    }

    #[test]
    fn a_declared_description_overrides_meta_and_leaves_when_to_use() {
        // spec: WF-4 WF-51 DSC-32 -- the `[[items]]` override replaces the
        // description read from `meta`; `whenToUse` is a separate field, so it
        // survives, which is the case folding the two together could not express.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("workflows/review.js"),
            "export const meta = {\n  description: 'from meta',\n  \
             whenToUse: 'before a PR',\n}\n",
        );
        write_file(
            &root.join("mind.toml"),
            "[[items]]\nkind = \"workflow\"\nname = \"review\"\n\
             path = \"workflows/review.js\"\ndescription = \"declared\"\n",
        );
        let paths = paths_for(root);
        let source = make_source_for(root);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let wf = items
            .iter()
            .find(|i| i.kind == ItemKind::Workflow)
            .expect("the declared workflow");
        assert_eq!(wf.description.as_deref(), Some("declared"));
        assert_eq!(wf.when_to_use.as_deref(), Some("before a PR"));
        assert_eq!(
            wf.display_description().as_deref(),
            Some("declared - before a PR")
        );
    }

    #[test]
    fn an_unreadable_workflow_meta_lists_without_a_description() {
        // spec: WF-5 WF-31 -- the reader never fails a scan on the shape of a
        // workflow's code. A file with no `meta` at all is still an item.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("workflows/odd.js"),
            "const meta = buildMeta()\nexport { meta }\n",
        );
        let paths = paths_for(root);
        let source = make_source_for(root);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).unwrap();

        let wf = items
            .iter()
            .find(|i| i.kind == ItemKind::Workflow)
            .expect("the workflow is still discovered");
        assert_eq!(wf.name, "odd");
        assert_eq!(wf.description, None);
        assert_eq!(wf.when_to_use, None);
        assert_eq!(wf.display_description(), None);
    }

    #[test]
    fn from_decl_rejects_a_non_command_linking_into_commands() {
        // spec: DSC-97 -- the scan-level refusal, so the rejection happens
        // before install ever runs, and the message says why.
        let tmp = TmpDir::new();
        let root = tmp.path();
        let source = make_source_for(root);
        let decl = ItemDecl {
            kind: "rule".to_string(),
            name: "style".to_string(),
            path: "rules/style.md".to_string(),
            link: Some("commands/deploy.md".to_string()),
            description: None,
            bin: None,
            build: None,
            install: None,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        match &err {
            MindError::MindToml { msg, .. } => assert!(
                msg.contains("commands/"),
                "the message must name the directory it refused: {msg}"
            ),
            other => panic!("expected a MindToml schema error, got: {other:?}"),
        }
        // The same declaration as a command is accepted.
        let decl = ItemDecl {
            kind: "command".to_string(),
            path: "commands/deploy.md".to_string(),
            ..decl
        };
        assert!(
            from_decl(root, &source, &None, &decl).is_ok(),
            "a command linking into commands/ must still be accepted"
        );
    }

    #[test]
    fn from_decl_rejects_link_outside_kind_directory() {
        // spec: DSC-97 -- H4: an `[[items]] link` outside a kind directory
        // (e.g. the agent-home root) is rejected before install ever runs, so
        // a source cannot plant a symlink at `settings.json` and have a
        // harness read attacker-controlled item content as its own config.
        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("settings.json".to_string()),
            description: None,
            bin: None,
            build: None,
            install: None,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        let err = from_decl(root, &source, &None, &decl).unwrap_err();
        assert!(
            matches!(err, MindError::MindToml { .. }),
            "a link outside a kind directory 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,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        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,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        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 expand_field_parsed_and_split_from_frontmatter() {
        // spec: NS-57
        // An `expand:` key in SKILL.md is read as a whitespace-split Vec, the
        // same scalar form `requires:` uses; absent yields 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\nexpand:  resources/pr.py   bin/run.sh \n---\n# review\n",
        );
        write_file(
            &clone.join("skills/plain/SKILL.md"),
            "---\ndescription: plain\n---\n# plain\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 review = items.iter().find(|i| i.name == "review").unwrap();
        assert_eq!(
            review.expand,
            vec!["resources/pr.py".to_string(), "bin/run.sh".to_string()],
            "expand must be whitespace-split from the frontmatter scalar"
        );
        let plain = items.iter().find(|i| i.name == "plain").unwrap();
        assert!(
            plain.expand.is_empty(),
            "absent expand 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,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        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,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        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,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        };
        // The file need not exist; frontmatter reads return None for absent files.
        let item = from_decl(root, &source, &None, &decl)
            .unwrap()
            .expect("a well-formed declaration is not dropped");
        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,
            when_to_use: None,
            link_rel: None,
            bin: None,
            build: None,
            requires: Vec::new(),
            expand: Vec::new(),
            hooks: Vec::new(),
            ignore: None,
        }
    }

    #[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_falls_back_when_frontmatter_is_oversized() {
        // spec: DSC-91 NS-40 -- this read goes through the same size-capped
        // helper every other metadata read uses; an oversized frontmatter file
        // must not be read in full, and must be treated like an unreadable one:
        // fall back to the bare catalog name rather than error out (the method
        // returns `Option`, not `Result`). The file STARTS with a valid header
        // naming `other`, so an uncapped read would return `other`: only the
        // cap makes this fall back to the bare name.
        use std::io::Write as _;
        let dir = TmpDir::new();
        let p = dir.path().join("agents/coder.md");
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        let mut file = std::fs::File::create(&p).unwrap();
        file.write_all(b"---\nname: other\n---\n").unwrap();
        file.set_len(crate::error::METADATA_SIZE_LIMIT + 1).unwrap();
        drop(file);
        let item = agent_item(p, "coder");
        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);
    }

    #[test]
    fn the_reserved_prefix_warning_is_owed_once_per_source() {
        // spec: DSC-112 -- the gate the scan consults before warning: true the
        // first time a source is seen in this process, false after, and
        // independent per source.
        let a = format!("local/test/dsc112-a-{}", std::process::id());
        let b = format!("local/test/dsc112-b-{}", std::process::id());
        assert!(first_reserved_warning(&a), "first sighting warns");
        assert!(!first_reserved_warning(&a), "a repeat sighting does not");
        assert!(first_reserved_warning(&b), "another source still warns");
        assert!(!first_reserved_warning(&b));
    }

    #[test]
    fn only_a_reserved_prefix_consumes_the_reserved_warning() {
        // spec: DSC-112 -- the scan warns only when validate_prefix fails with
        // ReservedPrefix. An UnsafePrefix alias is a different problem the
        // warning's text does not describe, so it must not consume (or print)
        // the once-per-source warning.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(&root.join("rules/style.md"), "---\ndescription: d\n---\n");

        let mut unsafe_src = make_source_for(root);
        unsafe_src.name = format!("local/test/dsc112-unsafe-{}", std::process::id());
        unsafe_src.alias = Some("a:b".to_string());
        let mut out = Vec::new();
        scan_source_at(root, &unsafe_src, &mut out).unwrap();
        assert!(
            first_reserved_warning(&unsafe_src.name),
            "an unsafe (non-reserved) prefix must not fire the reserved-word warning"
        );

        let mut reserved_src = make_source_for(root);
        reserved_src.name = format!("local/test/dsc112-reserved-{}", std::process::id());
        reserved_src.alias = Some("workflow".to_string());
        let mut out = Vec::new();
        scan_source_at(root, &reserved_src, &mut out).unwrap();
        assert!(
            !first_reserved_warning(&reserved_src.name),
            "a reserved prefix must have fired the warning during the scan"
        );
    }

    #[cfg(unix)]
    #[test]
    fn workflow_glob_matches_only_regular_js_files() {
        // spec: DSC-114 -- a `[discover].workflows` glob drops a directory, a
        // non-.js file, and a symlink; only a regular .js file is a match.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(&root.join("workflows/ok.js"), "export const meta = {}\n");
        write_file(&root.join("workflows/README.md"), "# readme\n");
        write_file(&root.join("workflows/dir.js/inner.txt"), "x\n");
        std::os::unix::fs::symlink(root.join("workflows/ok.js"), root.join("workflows/link.js"))
            .unwrap();
        let matches = glob_paths(root, "workflows/*", ItemKind::Workflow).unwrap();
        let names: Vec<String> = matches.iter().map(|p| file_name(p)).collect();
        assert_eq!(names, vec!["ok.js".to_string()], "got {names:?}");
        // Other kinds are unaffected by the workflow filter.
        let md = glob_paths(root, "workflows/*", ItemKind::Rule).unwrap();
        assert!(md.len() > 1, "non-workflow globs keep matching: {md:?}");
    }

    #[cfg(unix)]
    #[test]
    fn item_link_skill_requires_a_regular_anchor() {
        // spec: DSC-115 -- an item link's SKILL.md must be a regular file, and
        // its directory a real directory, not links.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("skills/good/SKILL.md"),
            "---\ndescription: g\n---\n",
        );
        write_file(
            &root.join("elsewhere/real.md"),
            "---\ndescription: SECRET\n---\n",
        );
        std::fs::create_dir_all(root.join("skills/linked")).unwrap();
        std::os::unix::fs::symlink(
            root.join("elsewhere/real.md"),
            root.join("skills/linked/SKILL.md"),
        )
        .unwrap();
        std::os::unix::fs::symlink(root.join("skills/good"), root.join("skills/dirlink")).unwrap();

        let scan = |item_path: &str| {
            let mut src = make_source_for(root);
            src.item_path = Some(item_path.to_string());
            let mut out = Vec::new();
            scan_source_at(root, &src, &mut out).map(|_| out)
        };
        let ok = scan("skills/good").unwrap();
        assert_eq!(ok.len(), 1, "the regular skill is still linkable");
        assert!(matches!(
            scan("skills/linked"),
            Err(MindError::LinkNotASkill { .. })
        ));
        assert!(matches!(
            scan("skills/dirlink"),
            Err(MindError::LinkNotASkill { .. })
        ));
    }

    #[cfg(unix)]
    #[test]
    fn a_tool_with_a_symlinked_anchor_is_not_offered() {
        // spec: DSC-115 -- TOOL.md is optional, but when present it must be a
        // regular non-symlink file: by convention scan and by glob.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("elsewhere/real.md"),
            "---\ndescription: SECRET\n---\n",
        );
        write_file(&root.join("tools/bare/run.sh"), "#!/bin/sh\n");
        write_file(
            &root.join("tools/plain/TOOL.md"),
            "---\ndescription: p\n---\n",
        );
        write_file(&root.join("tools/linked/run.sh"), "#!/bin/sh\n");
        std::os::unix::fs::symlink(
            root.join("elsewhere/real.md"),
            root.join("tools/linked/TOOL.md"),
        )
        .unwrap();

        let names = |out: &Vec<CatalogItem>| {
            let mut v: Vec<String> = out.iter().map(|i| i.name.clone()).collect();
            v.sort();
            v
        };
        let src = make_source_for(root);
        let mut out = Vec::new();
        scan_source_at(root, &src, &mut out).unwrap();
        assert_eq!(names(&out), vec!["bare", "plain"], "convention scan");

        write_file(
            &root.join("mind.toml"),
            "[discover]\ntools = { include = [\"tools/*\"] }\n",
        );
        let mut out = Vec::new();
        scan_source_at(root, &src, &mut out).unwrap();
        assert_eq!(names(&out), vec!["bare", "plain"], "glob scan");
        assert!(
            out.iter()
                .all(|i| i.description.as_deref() != Some("SECRET"))
        );
    }

    #[test]
    fn a_blank_workflow_description_and_when_to_use_are_none() {
        // spec: WF-63 -- an empty or whitespace-only meta string is no value.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("workflows/blank.js"),
            "export const meta = { name: 'blank', description: '   ', whenToUse: '' }\n",
        );
        write_file(
            &root.join("workflows/full.js"),
            "export const meta = { name: 'full', description: 'd', whenToUse: 'w' }\n",
        );
        let src = make_source_for(root);
        let mut out = Vec::new();
        scan_source_at(root, &src, &mut out).unwrap();
        let blank = out.iter().find(|i| i.name == "blank").unwrap();
        assert_eq!(blank.description, None);
        assert_eq!(blank.when_to_use, None);
        let full = out.iter().find(|i| i.name == "full").unwrap();
        assert_eq!(full.description.as_deref(), Some("d"));
        assert_eq!(full.when_to_use.as_deref(), Some("w"));
    }

    /// An `ItemDecl` with only kind, name, path, and link set.
    fn bare_decl(kind: &str, name: &str, path: &str, link: Option<&str>) -> ItemDecl {
        ItemDecl {
            kind: kind.to_string(),
            name: name.to_string(),
            path: path.to_string(),
            link: link.map(str::to_string),
            description: None,
            bin: None,
            build: None,
            install: None,
            update: None,
            uninstall: None,
            hooks: Vec::new(),
            ignore: None,
        }
    }

    #[test]
    fn from_decl_link_refusal_names_the_workflow_only_rule() {
        // spec: WF-8 DSC-97 -- a non-workflow linking into `workflows/` is
        // refused, and the message states the own-kind-only rule for both
        // invocable directories.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(&root.join("rules/style.md"), "---\ndescription: d\n---\n");
        let source = make_source_for(root);
        let decl = bare_decl(
            "rule",
            "style",
            "rules/style.md",
            Some("workflows/deploy.js"),
        );
        match from_decl(root, &source, &None, &decl) {
            Err(MindError::MindToml { msg, .. }) => {
                assert!(
                    msg.contains("only a workflow into 'workflows/'"),
                    "the message must state the workflow-only rule: {msg}"
                );
                assert!(
                    msg.contains("'commands/', 'workflows/', or 'tools/'"),
                    "the message must list every kind directory: {msg}"
                );
            }
            other => panic!("expected a MindToml schema error, got: {other:?}"),
        }
    }

    #[cfg(unix)]
    #[test]
    fn from_decl_drops_a_declared_fifo_without_opening_it() {
        // spec: DSC-108 -- a fifo at a declared workflow path would block the
        // first read forever; the scan classifies it no-follow and drops it
        // without opening it.
        let tmp = TmpDir::new();
        let root = tmp.path().to_path_buf();
        std::fs::create_dir_all(root.join("workflows")).unwrap();
        let fifo = root.join("workflows/pipe.js");
        let made = std::process::Command::new("mkfifo")
            .arg(&fifo)
            .status()
            .is_ok_and(|s| s.success());
        if !made {
            // No `mkfifo` on this host: nothing to exercise.
            return;
        }
        let source = make_source_for(&root);
        let decl = bare_decl("workflow", "pipe", "workflows/pipe.js", None);
        let (tx, rx) = std::sync::mpsc::channel();
        let thread_root = root.clone();
        std::thread::spawn(move || {
            let r = from_decl(&thread_root, &source, &None, &decl).map(|o| o.is_none());
            let _ = tx.send(r);
        });
        let got = rx
            .recv_timeout(std::time::Duration::from_secs(10))
            .expect("from_decl must not hang on a fifo");
        assert!(
            matches!(got, Ok(true)),
            "a declared fifo must be dropped (Ok(None)): {got:?}"
        );
        // Unblock a leaked reader, should one exist, before the dir is removed.
        let _ = std::fs::remove_file(&fifo);
    }

    #[cfg(unix)]
    #[test]
    fn discover_match_path_keeps_the_non_canonical_root() {
        // spec: DSC-81 -- the glob runs under the canonical root, but the item
        // carries its path under the root the scan was given, as every other
        // scan path does, so a symlinked root does not leak its resolved form.
        let tmp = TmpDir::new();
        let real = tmp.path().join("real");
        write_file(
            &real.join("agents/coder.md"),
            "---\ndescription: coder\n---\n",
        );
        write_file(
            &real.join("skills/review/SKILL.md"),
            "---\ndescription: review\n---\n",
        );
        write_file(
            &real.join("mind.toml"),
            "[discover]\nagents = { include = [\"agents/*.md\"] }\n\
             skills = { include = [\"skills/*/SKILL.md\"] }\n",
        );
        let link = tmp.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        let source = make_source_for(&link);
        let mut items = Vec::new();
        scan_source_at(&link, &source, &mut items).unwrap();
        assert_eq!(items.len(), 2, "both matches are offered: {items:?}");
        for it in &items {
            assert!(
                it.path.starts_with(&link),
                "the item path must be under the non-canonical root {}: {}",
                link.display(),
                it.path.display()
            );
        }
    }

    #[cfg(unix)]
    #[test]
    fn item_link_path_keeps_the_non_canonical_root() {
        // spec: LNK-7 DSC-81 -- the confinement check runs on the canonical
        // target, but the item carries its path under the clone root.
        let tmp = TmpDir::new();
        let real = tmp.path().join("real");
        write_file(
            &real.join("skills/review/SKILL.md"),
            "---\ndescription: review\n---\n",
        );
        let link = tmp.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();
        let mut source = make_source_for(&link);
        source.item_path = Some("skills/review".to_string());
        let mut items = Vec::new();
        scan_source_at(&link, &source, &mut items).unwrap();
        assert_eq!(items.len(), 1, "the linked skill is offered: {items:?}");
        assert_eq!(items[0].path, link.join("skills/review"));
    }

    // ---- DSC-81: [discover] glob confinement --------------------------------

    #[test]
    fn glob_paths_rejects_absolute_pattern() {
        // spec: DSC-81 -- an absolute pattern in [discover] must be rejected at
        // parse time, before any filesystem access.
        let tmp = TmpDir::new();
        let root = tmp.path();
        let err = glob_paths(root, "/etc/passwd", ItemKind::Agent).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("absolute"),
            "error must mention 'absolute': {msg}"
        );
    }

    #[test]
    fn glob_paths_rejects_parent_dir_in_pattern() {
        // spec: DSC-81 -- a `..` component in the pattern must be rejected before
        // any filesystem access, preventing escape from the clone root.
        let tmp = TmpDir::new();
        let root = tmp.path();
        let err = glob_paths(root, "../outside/*.md", ItemKind::Agent).unwrap_err();
        let msg = err.to_string();
        assert!(msg.contains(".."), "error must mention '..': {msg}");
    }

    #[test]
    fn glob_paths_accepts_normal_relative_pattern() {
        // spec: DSC-81 -- a normal relative glob must be accepted and match files
        // within the root.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("agents/coder.md"),
            "---\ndescription: coder\n---\n",
        );
        let matches = glob_paths(root, "agents/*.md", ItemKind::Agent).unwrap();
        assert_eq!(matches.len(), 1, "should find one match: {matches:?}");
        assert!(
            matches[0].ends_with("coder.md"),
            "matched the wrong file: {matches:?}"
        );
    }

    #[test]
    fn glob_paths_skill_rejects_hostile_parent_dir_name() {
        // spec: DSC-83 -- for skill globs the safe-component check must be applied
        // to the parent directory name (the bare skill name), not the SKILL.md
        // stem. A skill directory whose name contains a path separator is rejected.
        let tmp = TmpDir::new();
        let root = tmp.path();
        // A backslash in a directory name is valid on Linux but rejected by
        // is_safe_item_name, so it exercises the check on the right name.
        write_file(
            &root.join("packages").join("evil\\skill").join("SKILL.md"),
            "---\ndescription: hostile\n---\n",
        );
        let err = glob_paths(root, "packages/*/SKILL.md", ItemKind::Skill).unwrap_err();
        let msg = err.to_string();
        assert!(
            msg.contains("unsafe"),
            "error must mention 'unsafe' for hostile parent dir name: {msg}"
        );
    }

    #[test]
    fn glob_paths_skill_accepts_normal_parent_dir_name() {
        // spec: DSC-83 -- a skill whose parent directory has a safe name is accepted.
        let tmp = TmpDir::new();
        let root = tmp.path();
        write_file(
            &root.join("packages/good-skill/SKILL.md"),
            "---\ndescription: fine\n---\n",
        );
        let matches = glob_paths(root, "packages/*/SKILL.md", ItemKind::Skill).unwrap();
        assert_eq!(matches.len(), 1, "should find one match: {matches:?}");
        assert!(
            matches[0].ends_with("SKILL.md"),
            "matched the wrong file: {matches:?}"
        );
    }

    #[test]
    fn overlapping_add_roots_same_canonical_item_dedupes_instead_of_erroring() {
        // spec: DSC-87 -- two --add-root roots surfacing the same on-disk skill
        // (e.g. `--add-root . --add-root skills`, where the "." pass finds it via
        // the skills/ container and the "skills" pass finds it via the flat-skills
        // scan) must de-duplicate to a single catalog entry rather than raising
        // DuplicateItem. An authoritative mind.toml (declaring an unrelated item)
        // keeps the base layer from also picking up skills/foo via convention.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\n",
        );
        // Authoritative mind.toml: declares one unrelated item so the base layer
        // does not itself discover skills/foo via convention scanning.
        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);
        source.add_roots = Some(vec![".".to_string(), "skills".to_string()]);

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

        let foos: Vec<_> = items
            .iter()
            .filter(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .collect();
        assert_eq!(
            foos.len(),
            1,
            "overlapping add-roots surfacing the same on-disk item must dedupe to one entry: {items:?}"
        );
    }

    #[test]
    fn add_roots_same_path_different_kind_surfaces_both_items() {
        // spec: DSC-89 -- a single on-disk path can contribute up to one item PER
        // KIND. `tools/foo/` needs no anchor file (DSC-13), so a tools directory
        // that also carries a `SKILL.md` is both a valid Tool and a valid Skill.
        // With `--add-root . --add-root tools`, the "." root's tools/ pass finds
        // it as a Tool and the "tools" root's flat-skills pass finds the SAME
        // directory as a Skill: two DIFFERENT kinds at the same path, so the
        // DSC-87 same-path dedup must NOT collapse them into one -- both must
        // survive. (Pre-DSC-89, keying the dedup on path alone silently dropped
        // whichever kind's scan pass ran second.)
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("tools/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\n",
        );
        // Authoritative mind.toml (an unrelated declared item) so the base layer
        // does not itself discover tools/foo via ordinary convention scanning;
        // it is reachable only through the two add-roots passes.
        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);
        source.add_roots = Some(vec![".".to_string(), "tools".to_string()]);

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

        let foo_tool = items
            .iter()
            .any(|i| i.kind == ItemKind::Tool && i.name == "foo");
        let foo_skill = items
            .iter()
            .any(|i| i.kind == ItemKind::Skill && i.name == "foo");
        assert!(
            foo_tool,
            "the tools/ pass must still surface foo as a Tool: {items:?}"
        );
        assert!(
            foo_skill,
            "the flat-skills pass over the `tools` add-root must still surface \
             foo as a Skill, alongside the Tool at the same path: {items:?}"
        );
    }

    #[test]
    fn distinct_path_name_collision_between_add_root_items_still_errors() {
        // spec: DSC-85 -- a same-(kind, effective-name) collision between two
        // add-root items at DISTINCT on-disk paths remains a DuplicateItem error;
        // only a same-canonical-path overlap (DSC-87) de-duplicates.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        // Two distinct on-disk skill directories that both resolve to the bare
        // name "foo": one flat at the repo root, one flat under "nested".
        write_file(
            &clone.join("foo/SKILL.md"),
            "---\ndescription: foo at root\n---\n# foo\n",
        );
        write_file(
            &clone.join("nested/foo/SKILL.md"),
            "---\ndescription: foo nested\n---\n# foo\n",
        );
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\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);
        source.add_roots = Some(vec![".".to_string(), "nested".to_string()]);

        let mut items = Vec::new();
        let err = scan_source(&paths, &source, &mut items).unwrap_err();
        assert!(
            matches!(err, MindError::DuplicateItem { .. }),
            "a distinct-path name collision must still error as DuplicateItem: {err}"
        );
    }

    #[test]
    fn overlapping_add_roots_dedup_keeps_first_occurrence_with_correct_metadata() {
        // spec: DSC-87 -- the same-path overlap dedup must not just drop down to
        // one entry; the surviving entry must be the genuine item (right kind,
        // bare name, on-disk path, and frontmatter-derived description), not a
        // corrupted or empty stand-in produced by the dedup bookkeeping.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: the real foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\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);
        // "." finds skills/foo via the skills/ container pass; "skills" finds the
        // same directory via the flat-skills pass. First occurrence (from ".")
        // must be the one kept.
        source.add_roots = Some(vec![".".to_string(), "skills".to_string()]);

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

        let foos: Vec<_> = items
            .iter()
            .filter(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .collect();
        assert_eq!(
            foos.len(),
            1,
            "expected exactly one deduped item: {items:?}"
        );
        let kept = foos[0];
        assert_eq!(kept.kind, ItemKind::Skill);
        assert_eq!(kept.name, "foo");
        let canon_kept = kept.path.canonicalize().unwrap();
        let canon_expected = clone.join("skills/foo").canonicalize().unwrap();
        assert_eq!(
            canon_kept, canon_expected,
            "the kept item's on-disk path must be the real skills/foo directory: {kept:?}"
        );
        assert_eq!(
            kept.description.as_deref(),
            Some("the real foo"),
            "the kept item must carry the real item's frontmatter description, not a \
             corrupted/empty stand-in: {kept:?}"
        );
    }

    #[test]
    fn three_add_roots_overlapping_same_canonical_path_dedup_to_one() {
        // spec: DSC-87 -- the dedup must hold for more than two overlapping
        // add-roots: three different roots that all resolve to the same on-disk
        // skill directory still collapse to a single catalog entry rather than
        // erroring on the third occurrence.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\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);
        // "." -> skills/ container pass finds skills/foo.
        // "skills" -> flat pass finds skills/foo directly.
        // "./skills" -> a lexically distinct root string that canonicalizes to
        // the very same directory as "skills", found again via the flat pass.
        source.add_roots = Some(vec![
            ".".to_string(),
            "skills".to_string(),
            "./skills".to_string(),
        ]);

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

        let foos: Vec<_> = items
            .iter()
            .filter(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .collect();
        assert_eq!(
            foos.len(),
            1,
            "three add-roots overlapping on the same canonical path must dedupe to \
             exactly one entry: {items:?}"
        );
    }

    #[test]
    fn symlinked_add_root_resolving_to_same_canonical_path_dedups() {
        // spec: DSC-87 -- two add-roots that reach the same on-disk item through
        // a symlink (rather than through a different scan mechanism, as in the
        // container-vs-flat case above) must still dedupe by canonical path.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        write_file(
            &clone.join("skills/foo/SKILL.md"),
            "---\ndescription: foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("guidelines/style.md"),
            "---\ndescription: style\n---\n# style\n",
        );
        write_file(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"rule\"\n",
                "name = \"style\"\n",
                "path = \"guidelines/style.md\"\n",
            ),
        );
        // "mirror" is a symlink to "skills", so `mirror/foo` and `skills/foo`
        // are the same file on disk once canonicalized.
        std::os::unix::fs::symlink(clone.join("skills"), clone.join("mirror")).unwrap();

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.add_roots = Some(vec!["skills".to_string(), "mirror".to_string()]);

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

        let foos: Vec<_> = items
            .iter()
            .filter(|i| i.kind == ItemKind::Skill && i.name == "foo")
            .collect();
        assert_eq!(
            foos.len(),
            1,
            "a symlinked add-root resolving to the same canonical path as another \
             add-root must dedupe to one entry, not error or double-count: {items:?}"
        );
    }

    #[test]
    fn add_root_item_colliding_with_authoritative_declared_item_at_distinct_path_errors() {
        // spec: DSC-85 -- an add-root item that collides on (kind, effective name)
        // with an item the AUTHORITATIVE mind.toml `[[items]]` layer declared (not
        // just a base convention-scanned item) at a genuinely distinct on-disk path
        // must still be a DuplicateItem error; only a same-canonical-path overlap
        // among add-root items themselves (DSC-87) de-duplicates.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        // Authoritative declaration: skill "foo" at declared/foo.
        write_file(
            &clone.join("declared/foo/SKILL.md"),
            "---\ndescription: declared foo\n---\n# foo\n",
        );
        write_file(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"skill\"\n",
                "name = \"foo\"\n",
                "path = \"declared/foo\"\n",
            ),
        );
        // Add-root item: a DISTINCT on-disk skill directory that also bares the
        // name "foo" via the skills/ container convention.
        write_file(
            &clone.join("extra/skills/foo/SKILL.md"),
            "---\ndescription: extra foo\n---\n# foo\n",
        );

        let paths = paths_for(base);
        let mut source = make_source_for(&clone);
        source.add_roots = Some(vec!["extra".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 == "foo"),
            "an add-root item colliding by name with an authoritative [[items]] \
             declaration at a distinct path must still error as DuplicateItem: {err}"
        );
    }

    #[test]
    fn missing_convention_directories_yield_no_items_not_an_error() {
        // spec: DSC-13
        // A repo with none of the convention directories (no `skills/`, `agents/`,
        // `rules/`, or `tools/`) scans without error and produces an empty catalog.
        // Each missing kind directory is silently treated as empty.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");
        // Create the repo root with no convention subdirectories.
        std::fs::create_dir_all(&clone).unwrap();
        write_file(&clone.join("README.md"), "# empty repo\n");

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        let result = scan_source(&paths, &source, &mut items);
        assert!(
            result.is_ok(),
            "scan_source must not error when convention directories are absent (DSC-13): {result:?}"
        );
        assert!(
            items.is_empty(),
            "no items must be discovered when convention directories are absent (DSC-13): {items:?}"
        );
    }

    #[test]
    fn missing_individual_convention_directories_yield_no_items_for_that_kind() {
        // spec: DSC-13
        // Only a subset of the convention directories is present; the missing ones
        // each yield no items (not an error) and the present ones are scanned normally.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/repo");

        // Only `agents/` exists; `skills/`, `rules/`, and `tools/` are absent.
        write_file(
            &clone.join("agents/helper.md"),
            "---\ndescription: helper\n---\n# helper\n",
        );

        let paths = paths_for(base);
        let source = make_source_for(&clone);
        let mut items = Vec::new();
        let result = scan_source(&paths, &source, &mut items);
        assert!(
            result.is_ok(),
            "scan_source must not error when only some convention directories exist (DSC-13): {result:?}"
        );
        let kinds: Vec<_> = items.iter().map(|i| i.kind).collect();
        assert_eq!(
            kinds,
            vec![ItemKind::Agent],
            "only the agent from the present agents/ dir must be discovered; \
             missing skill/rule/tool dirs must not cause an error (DSC-13): {items:?}"
        );
    }
}

/// 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,
            as_alias: None,
            pin: Pin::default(),
            roots: None,
            flat_skills: false,
            full_history: false,
            add_roots: None,
            item_path: None,
            item_kind: None,
            curated_by: None,
            origin: None,
            plugin_version: None,
            install_hooks: Vec::new(),
            items_hooks: Vec::new(),
            install_hook: None,
            install_hook_commit: None,
            profiles: None,
            profile_snapshot: None,
            whole_snapshot: None,
            auto_update: 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::Manifest { .. }),
            "malformed plugin.json must propagate as a Manifest error (MKT-9): {err:?}"
        );
    }

    // plugin_skipped_components counts the dirs with no mind equivalent (MKT-4),
    // and no longer counts a mapped commands/<name>.md, which now installs as
    // the command kind.
    #[test]
    fn plugin_skipped_components_counts_unsupported_dirs() {
        // spec: MKT-4 MKT-18
        let tmp = TmpDir::new();
        let plugin_root = tmp.path().join("my-plugin");

        write_file(
            &plugin_root.join("commands/review.md"),
            "---\ndescription: review\n---\n",
        );
        std::fs::create_dir_all(plugin_root.join("hooks")).unwrap();
        std::fs::write(plugin_root.join(".mcp.json"), "{}").unwrap();

        let skipped = plugin_skipped_components(&plugin_root);
        assert!(skipped.hooks > 0, "hooks/ dir must be counted as skipped");
        assert!(
            skipped.mcp_servers > 0,
            ".mcp.json must be counted as skipped"
        );
        assert_eq!(
            skipped.total(),
            2,
            "a mapped commands/<name>.md must NOT be counted as skipped: {skipped:?}"
        );
        assert!(
            !skipped.summary().unwrap().contains("command"),
            "the skipped summary must not name commands: {skipped:?}"
        );
    }

    // The other half of MKT-4 for commands: what the flat `.md` scan does not
    // map is still a drop, so it must be counted.
    #[test]
    fn plugin_skipped_components_counts_nested_and_non_md_commands() {
        // spec: MKT-4 MKT-18
        let tmp = TmpDir::new();
        let plugin_root = tmp.path().join("my-plugin");

        // Mapped: installed as command:review, never reported as skipped.
        write_file(
            &plugin_root.join("commands/review.md"),
            "---\ndescription: review\n---\n",
        );
        // Unmapped: a nested group directory (a layout the harness allows,
        // CMD-2) and a non-markdown file.
        write_file(
            &plugin_root.join("commands/frontend/component.md"),
            "---\ndescription: component\n---\n",
        );
        write_file(&plugin_root.join("commands/do.sh"), "#!/bin/sh\n");
        // Not a component anyone meant to publish, so not a reported drop.
        write_file(&plugin_root.join("commands/.gitkeep"), "");

        let skipped = plugin_skipped_components(&plugin_root);
        assert_eq!(
            skipped.commands, 2,
            "the nested dir and the .sh must both count; the .md and the \
             dotfile must not: {skipped:?}"
        );
        assert_eq!(
            skipped.total(),
            2,
            "nothing else is present to count: {skipped:?}"
        );
        let summary = skipped.summary().expect("a drop must be reported");
        assert!(
            summary.contains("2 unmapped commands/ entries"),
            "the summary must name what was left behind: {summary}"
        );
    }

    // `workflows/` is counted by the same rule as `commands/`: a mapped flat
    // `.js` installs and is never named, what the scan leaves is a reported
    // drop.
    #[test]
    fn plugin_skipped_components_counts_nested_and_non_js_workflows() {
        // spec: MKT-4 WF-40
        let tmp = TmpDir::new();
        let plugin_root = tmp.path().join("my-plugin");

        // Mapped: installed as workflow:deploy, never reported as skipped.
        write_file(
            &plugin_root.join("workflows/deploy.js"),
            "export const meta = { name: 'deploy', description: 'd' }\n",
        );
        // Unmapped: a nested directory and a file the `.js`-exact scan skips
        // (WF-3), which the harness would not load either.
        write_file(&plugin_root.join("workflows/nested/deep.js"), "");
        write_file(&plugin_root.join("workflows/deploy.ts"), "");
        write_file(&plugin_root.join("workflows/.gitkeep"), "");

        let skipped = plugin_skipped_components(&plugin_root);
        assert_eq!(
            skipped.workflows, 2,
            "the nested dir and the .ts must both count; the .js and the \
             dotfile must not: {skipped:?}"
        );
        assert_eq!(skipped.total(), 2, "nothing else is present: {skipped:?}");
        let summary = skipped.summary().expect("a drop must be reported");
        assert!(
            summary.contains("2 unmapped workflows/ entries"),
            "the summary must name what was left behind: {summary}"
        );
    }

    // A symlinked `workflows/<name>.js` is NOT mapped (DSC-108), so it has to be
    // counted as an unmapped entry. Otherwise the one message whose job is to
    // say what was dropped calls it installed, and the entry vanishes in
    // silence -- the failure mode MKT-4 exists to prevent.
    #[cfg(unix)]
    #[test]
    fn plugin_skipped_components_counts_a_symlinked_workflow_as_unmapped() {
        // spec: MKT-4 DSC-108
        let tmp = TmpDir::new();
        let base = tmp.path();
        let plugin_root = base.join("my-plugin");

        // A real `.js` OUTSIDE the plugin, linked to from inside it: following
        // the link would call this mapped while the scan drops it.
        write_file(
            &base.join("outside/private.js"),
            "export const meta = { name: 'private', description: 'd' }\n",
        );
        std::fs::create_dir_all(plugin_root.join("workflows")).unwrap();
        std::os::unix::fs::symlink(
            base.join("outside/private.js"),
            plugin_root.join("workflows/leak.js"),
        )
        .unwrap();

        let skipped = plugin_skipped_components(&plugin_root);
        assert_eq!(
            skipped.workflows, 1,
            "a symlinked workflow entry is not installed, so it must be reported \
             as an unmapped entry rather than counted as mapped: {skipped:?}"
        );

        // And the two halves agree: the scan does not offer it either.
        let source = make_plugin_source(&plugin_root);
        let mut items = Vec::new();
        scan_plugin_components(&plugin_root, &source, &None, &mut items).unwrap();
        assert!(
            items.is_empty(),
            "the symlinked entry must not be discovered: {items:?}"
        );
    }

    // A plugin whose whole `workflows/` folder is a symlink is never scanned
    // (the container is refused), so the report counts the folder as ONE
    // unmapped entry rather than listing the outside directory it points at.
    #[cfg(unix)]
    #[test]
    fn plugin_skipped_components_counts_a_symlinked_workflows_dir_once() {
        // spec: MKT-4 DSC-108
        let tmp = TmpDir::new();
        let base = tmp.path();
        let plugin_root = base.join("my-plugin");
        write_file(
            &base.join("outside/a.js"),
            "export const meta = { name: 'a', description: 'd' }\n",
        );
        write_file(
            &base.join("outside/b.js"),
            "export const meta = { name: 'b', description: 'd' }\n",
        );
        std::fs::create_dir_all(&plugin_root).unwrap();
        std::os::unix::fs::symlink(base.join("outside"), plugin_root.join("workflows")).unwrap();

        let skipped = plugin_skipped_components(&plugin_root);
        assert_eq!(
            skipped.workflows, 1,
            "a symlinked workflows/ folder is one unmapped entry, not a listing of \
             the directory it points at: {skipped:?}"
        );

        let source = make_plugin_source(&plugin_root);
        let mut items = Vec::new();
        scan_plugin_components(&plugin_root, &source, &None, &mut items).unwrap();
        assert!(
            !items.iter().any(|i| i.kind == ItemKind::Workflow),
            "no workflow may be discovered through a symlinked folder: {items:?}"
        );
    }

    // The plugin layout is not a second answer to "is a symlink an item": a
    // plugin's `skills/<name>/SKILL.md` and `agents/<name>.md` are classified
    // exactly as the convention scan's are.
    #[cfg(unix)]
    #[test]
    fn plugin_component_scan_classifies_symlinks_no_follow() {
        // spec: DSC-108 MKT-3
        let tmp = TmpDir::new();
        let base = tmp.path();
        let plugin_root = base.join("my-plugin");

        // Real components outside the plugin, reachable only by link.
        write_file(
            &base.join("outside/realskill/SKILL.md"),
            "---\ndescription: outside skill\n---\n",
        );
        write_file(
            &base.join("outside/agent.md"),
            "---\ndescription: outside agent\n---\n",
        );
        write_file(
            &base.join("outside/anchor.md"),
            "---\ndescription: outside anchor\n---\n",
        );
        // A linked skill DIRECTORY, a real skill dir with a linked ANCHOR, and a
        // linked agent file.
        std::fs::create_dir_all(plugin_root.join("skills/anchored")).unwrap();
        std::fs::create_dir_all(plugin_root.join("agents")).unwrap();
        std::os::unix::fs::symlink(
            base.join("outside/realskill"),
            plugin_root.join("skills/linked-dir"),
        )
        .unwrap();
        std::os::unix::fs::symlink(
            base.join("outside/anchor.md"),
            plugin_root.join("skills/anchored/SKILL.md"),
        )
        .unwrap();
        std::os::unix::fs::symlink(
            base.join("outside/agent.md"),
            plugin_root.join("agents/linked.md"),
        )
        .unwrap();
        // One genuine component, so an empty result cannot pass by accident.
        write_file(
            &plugin_root.join("skills/real/SKILL.md"),
            "---\ndescription: the plugin's own skill\n---\n",
        );

        let source = make_plugin_source(&plugin_root);
        let mut items = Vec::new();
        scan_plugin_components(&plugin_root, &source, &None, &mut items).unwrap();
        let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["real"],
            "only the plugin's own non-symlinked component may be discovered: {items:?}"
        );
        assert!(
            !items
                .iter()
                .any(|i| i.description.as_deref().unwrap_or("").contains("outside")),
            "no linked-to file's description may reach the catalog: {items:?}"
        );
    }

    // The marketplace in-repo route reaches the same shapes through a third
    // scan function, including the `skills` array that names leaf dirs
    // directly rather than reading a directory.
    #[cfg(unix)]
    #[test]
    fn marketplace_in_repo_scan_classifies_symlinks_no_follow() {
        // spec: DSC-108 MKT-14
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");
        write_file(
            &base.join("outside/realskill/SKILL.md"),
            "---\ndescription: outside skill\n---\n",
        );
        std::fs::create_dir_all(clone.join("plug/skills")).unwrap();
        // A linked leaf skill dir named by the entry's `skills` array...
        std::os::unix::fs::symlink(
            base.join("outside/realskill"),
            clone.join("plug/skills/listed"),
        )
        .unwrap();
        // ...and the same shape found by the conventional branch of the scan.
        write_file(
            &clone.join(".claude-plugin/marketplace.json"),
            r#"{
                "name": "Market",
                "plugins": [
                    {"name": "listedplug", "source": "./plug", "skills": ["./skills/listed"]},
                    {"name": "scannedplug", "source": "./plug"}
                ]
            }"#,
        );

        let paths = paths_for(base);
        let source = make_plugin_source(&clone);
        let mut items = Vec::new();
        scan_source(&paths, &source, &mut items).expect("the scan must not fail");
        assert!(
            items.is_empty(),
            "neither marketplace branch may discover a symlinked skill dir: {items:?}"
        );
    }

    #[test]
    fn plugin_with_no_commands_dir_reports_nothing_skipped() {
        // spec: MKT-4
        // The count is dir-based; an absent commands/ is not an error and not a
        // drop (DSC-13).
        let tmp = TmpDir::new();
        let plugin_root = tmp.path().join("my-plugin");
        write_file(
            &plugin_root.join("skills/greet/SKILL.md"),
            "---\ndescription: greet\n---\n",
        );
        let skipped = plugin_skipped_components(&plugin_root);
        assert_eq!(skipped.commands, 0, "no commands/ dir -> nothing unmapped");
        assert!(
            skipped.summary().is_none(),
            "a plugin with only supported components reports nothing: {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)"
        );
    }

    #[test]
    fn mkt15_mind_toml_roots_suppress_plugin_manifest_own_items() {
        // spec: MKT-15
        // A repo ships a `.claude-plugin/plugin.json` AND a mind.toml declaring a
        // `[source].roots` scan layout. The roots layout is an own-item directive:
        // it suppresses the plugin manifest's own-item layer, so convention
        // discovery under the root supplies the repo's items and the plugin's
        // components are NOT scanned.
        let tmp = TmpDir::new();
        let base = tmp.path();
        let clone = base.join("sources/local/test/plugin-repo");

        // The plugin manifest would (absent MKT-15) contribute skills/greet.
        write_file(
            &clone.join(".claude-plugin/plugin.json"),
            "{\n  \"name\": \"acme-tools\",\n  \"version\": \"1.0.0\"\n}\n",
        );
        write_file(
            &clone.join("skills/greet/SKILL.md"),
            "---\nname: greet\ndescription: plugin greet\n---\n# greet\n",
        );
        // The mind.toml relocates convention to pkg/, where the repo's own skill lives.
        write_file(&clone.join("mind.toml"), "[source]\nroots = [\"pkg\"]\n");
        write_file(
            &clone.join("pkg/skills/own/SKILL.md"),
            "---\nname: own\ndescription: convention own skill\n---\n# own\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 names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(
            names.contains(&"own"),
            "convention skill under the declared root must be discovered: {names:?}"
        );
        assert!(
            !names.contains(&"greet"),
            "the plugin manifest's own items must be suppressed by the roots layout (MKT-15): {names:?}"
        );
    }

    #[test]
    fn mkt15_mind_toml_flat_skills_suppress_marketplace_own_items() {
        // spec: MKT-15
        // A repo ships a `.claude-plugin/marketplace.json` (in-repo plugin) AND a
        // mind.toml declaring `[source].flat-skills`. The flat layout is an
        // own-item directive: it suppresses the marketplace's in-repo plugin scan,
        // and flat convention discovery supplies the repo's own skills instead.
        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": "Acme Market",
                "plugins": [
                    {"name": "acme", "source": "./plugins/alpha"}
                ]
            }"#,
        );
        // The in-repo plugin the marketplace would contribute (suppressed).
        write_file(
            &clone.join("plugins/alpha/skills/mkt/SKILL.md"),
            "---\nname: mkt\ndescription: marketplace skill\n---\n# mkt\n",
        );
        // Flat convention layout: a bare skill dir at the repo root.
        write_file(&clone.join("mind.toml"), "[source]\nflat-skills = true\n");
        write_file(
            &clone.join("own/SKILL.md"),
            "---\nname: own\ndescription: flat own skill\n---\n# own\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 names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect();
        assert!(
            names.contains(&"own"),
            "flat convention skill at the repo root must be discovered: {names:?}"
        );
        assert!(
            !names.contains(&"mkt"),
            "the marketplace's in-repo plugin items must be suppressed by the flat layout (MKT-15): {names:?}"
        );
    }

    #[test]
    fn mkt16_bare_discover_sources_does_not_suppress_marketplace_own_items() {
        // spec: MKT-16
        // A repo ships a `.claude-plugin/marketplace.json` (in-repo plugin) AND a
        // mind.toml whose only discovery content is `[discover].sources` (a curator
        // directive over OTHER repos, not an own-item directive). The marketplace
        // still defines the immediate source: its in-repo plugin items ARE
        // discovered. (The nested curator sources are melded at meld time in
        // commands.rs; this scan-level test asserts the compose, i.e. no
        // suppression of the manifest's own items.)
        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": "Acme Market",
                "plugins": [
                    {"name": "acme", "source": "./plugins/alpha"}
                ]
            }"#,
        );
        write_file(
            &clone.join("plugins/alpha/skills/mkt/SKILL.md"),
            "---\nname: mkt\ndescription: marketplace skill\n---\n# mkt\n",
        );
        // A bare [discover].sources list: curator only, not an own-item directive.
        write_file(
            &clone.join("mind.toml"),
            "[source]\ndescription = \"marketplace + curator\"\n\n[discover]\nsources = [{ source = \"owner/repo\" }]\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 mkt = items
            .iter()
            .find(|i| i.kind == ItemKind::Skill && i.name == "mkt")
            .expect("the marketplace's in-repo plugin skill must still be discovered (MKT-16)");
        assert_eq!(
            mkt.effective_name(),
            "acme:mkt",
            "the in-repo plugin skill keeps its marketplace-entry namespace (MKT-8)"
        );
    }
}

#[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,
            as_alias: None,
            pin: Pin::default(),
            roots: None,
            flat_skills: false,
            full_history: false,
            add_roots: None,
            item_path: None,
            item_kind: None,
            curated_by: None,
            origin: None,
            plugin_version: None,
            install_hooks: Vec::new(),
            items_hooks: Vec::new(),
            install_hook: None,
            install_hook_commit: None,
            profiles: None,
            profile_snapshot: None,
            whole_snapshot: None,
            auto_update: 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_hooks()[0].run, "echo set-up");
        assert_eq!(rule.uninstall_hooks()[0].run, "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_hooks()[0].run, "make setup");
        assert_eq!(tool.uninstall_hooks()[0].run, "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!(
            rule.install_hooks().is_empty(),
            "whitespace install must be absent"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn scalar_item_hooks_resolve_into_the_hook_list() {
        // spec: HOOK-86 HOOK-134
        // The scalar install/uninstall shorthand resolves into the item's hook
        // list, which is the single place every consumer reads hooks from.
        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();
        // One required install and 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();
        // 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, one required hook each. The list is the only representation;
        // there are no separate scalar fields on the item any more.
        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();
        // 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 convention_scan_finds_commands_flat_and_reads_their_description() {
        // spec: CMD-1 CMD-2 CMD-3 DSC-14
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("commands/review.md"),
            "---\ndescription: Review the diff\nargument-hint: [pr]\n---\n# review\n",
        );
        // Nested: NOT discovered by convention, which is flat (CMD-2).
        write(
            &clone.join("commands/frontend/component.md"),
            "---\ndescription: nested\n---\n# component\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 cmd = items
            .iter()
            .find(|i| i.kind == ItemKind::Command)
            .expect("the command must be discovered");
        assert_eq!(cmd.name, "review", "the name is the file stem");
        assert_eq!(cmd.description.as_deref(), Some("Review the diff"));
        assert_eq!(cmd.key().as_str(), "command:review");
        assert_eq!(
            items.iter().filter(|i| i.kind == ItemKind::Command).count(),
            1,
            "the convention scan must not descend into commands/ subdirectories"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn commands_are_declarable_by_items_and_by_discover_globs() {
        // spec: CMD-2 CMD-4
        // The two escapes that reach a nested command the flat convention scan
        // does not: an explicit `[[items]]` entry, and a `[discover].commands`
        // glob. Both also prove `kind = "command"` parses.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("commands/frontend/component.md"),
            "---\ndescription: component\n---\n# component\n",
        );
        write(
            &clone.join("packages/api/commands/deploy.md"),
            "---\ndescription: deploy\n---\n# deploy\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"command\"\n",
                "name = \"component\"\n",
                "path = \"commands/frontend/component.md\"\n",
                "link = \"commands/frontend/component.md\"\n",
                "\n",
                "[discover]\n",
                "commands = { include = [\"packages/*/commands/*.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 declared = items
            .iter()
            .find(|i| i.name == "component")
            .expect("the declared command must be offered");
        assert_eq!(declared.kind, ItemKind::Command);
        assert_eq!(
            declared.link_rel.as_deref(),
            Some("commands/frontend/component.md"),
            "a nested link target is confined to the commands/ kind directory"
        );
        let globbed = items
            .iter()
            .find(|i| i.name == "deploy")
            .expect("the globbed command must be offered");
        assert_eq!(globbed.kind, ItemKind::Command);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn skill_frontmatter_declares_its_own_lifecycle_hooks() {
        // spec: HOOK-130
        // The scalar lifecycle keys are read from ANY kind's meta file, so a
        // convention-discovered skill declares its own hooks in SKILL.md with no
        // root manifest at all.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/scanner/SKILL.md"),
            "---\ndescription: scanner\ninstall: setup.sh\nupdate: migrate.sh\nuninstall: teardown.sh\n---\n# scanner\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 == "scanner").unwrap();
        assert_eq!(skill.install_hooks()[0].run, "setup.sh");
        assert_eq!(skill.update_hooks()[0].run, "migrate.sh");
        assert_eq!(skill.uninstall_hooks()[0].run, "teardown.sh");
        assert!(
            !skill.install_hooks()[0].optional,
            "a frontmatter scalar is one required hook"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn agent_frontmatter_declares_its_own_lifecycle_hooks() {
        // spec: HOOK-130
        // Not only directory-backed kinds: a single-file agent reads the same
        // scalars from its own `.md`.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("agents/dev.md"),
            "---\ndescription: dev\ninstall: setup.sh\n---\n# dev\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 agent = items.iter().find(|i| i.name == "dev").unwrap();
        assert_eq!(agent.install_hooks()[0].run, "setup.sh");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn item_directory_manifest_declares_hooks_and_beats_frontmatter() {
        // spec: HOOK-131 HOOK-132
        // A skill's own `mind.toml` declares the full `[[hooks]]` form (named,
        // optional, any event), and REPLACES the frontmatter scalars rather than
        // merging with them.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/scanner/SKILL.md"),
            "---\ndescription: scanner\ninstall: frontmatter-install\n---\n# scanner\n",
        );
        write(
            &clone.join("skills/scanner/mind.toml"),
            "[[hooks]]\nrun = \"manifest-install\"\nname = \"Set up\"\noptional = true\n\n[[hooks]]\nrun = \"manifest-update\"\nevent = \"update\"\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 == "scanner").unwrap();
        assert_eq!(skill.hooks.len(), 2, "the two sites must not merge");
        let ih = skill.install_hooks();
        assert_eq!(ih.len(), 1);
        assert_eq!(ih[0].run, "manifest-install");
        assert!(ih[0].optional, "the manifest form carries `optional`");
        assert_eq!(ih[0].label(), "Set up");
        assert_eq!(skill.update_hooks()[0].run, "manifest-update");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn root_items_declaration_beats_the_item_directory_manifest() {
        // spec: HOOK-132
        // A `[[items]]` entry that declares any hook is authoritative for that
        // item; one that declares none leaves the item's own sites in effect.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/scanner/SKILL.md"),
            "---\ndescription: scanner\n---\n# scanner\n",
        );
        write(
            &clone.join("skills/scanner/mind.toml"),
            "[[hooks]]\nrun = \"manifest-install\"\n",
        );
        write(
            &clone.join("skills/quiet/SKILL.md"),
            "---\ndescription: quiet\n---\n# quiet\n",
        );
        write(
            &clone.join("skills/quiet/mind.toml"),
            "[[hooks]]\nrun = \"quiet-install\"\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"skill\"\n",
                "name = \"scanner\"\n",
                "path = \"skills/scanner\"\n",
                "install = \"root-install\"\n",
                "\n",
                "[[items]]\n",
                "kind = \"skill\"\n",
                "name = \"quiet\"\n",
                "path = \"skills/quiet\"\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 scanner = items.iter().find(|i| i.name == "scanner").unwrap();
        assert_eq!(scanner.hooks.len(), 1);
        assert_eq!(scanner.install_hooks()[0].run, "root-install");
        let quiet = items.iter().find(|i| i.name == "quiet").unwrap();
        assert_eq!(
            quiet.install_hooks()[0].run,
            "quiet-install",
            "a declaration silent about hooks must not suppress the item's own"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn source_root_mind_toml_is_not_read_as_an_item_manifest() {
        // spec: HOOK-131
        // An item may point AT the source root (`path = "."`), where the item
        // directory's `mind.toml` IS the source manifest. Reading it as an item
        // manifest would reject the source's own `[[items]]` as an unknown key.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("SKILL.md"),
            "---\ndescription: root skill\n---\n# root\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"skill\"\n",
                "name = \"root-skill\"\n",
                "path = \".\"\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).expect("the scan must succeed");
        let skill = items.iter().find(|i| i.name == "root-skill").unwrap();
        assert!(
            skill.hooks.is_empty(),
            "the source manifest must not contribute item hooks"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn item_directory_manifest_schema_error_drops_only_that_item() {
        // spec: HOOK-131 DSC-98
        // A malformed item manifest must not degrade to "this item declares no
        // hooks": it exists only to declare code that will run on the host. So
        // the item is dropped -- an item nobody is offered can run no hook --
        // while the rest of the source still scans. Both failure modes of the
        // item's own manifest behave alike: an unknown hook event and a key
        // outside `[[hooks]]`.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/scanner/SKILL.md"),
            "---\ndescription: scanner\ninstall: frontmatter-install\n---\n# scanner\n",
        );
        write(
            &clone.join("skills/scanner/mind.toml"),
            "[[hooks]]\nrun = \"setup.sh\"\nevent = \"whenever\"\n",
        );
        write(
            &clone.join("skills/pasted/SKILL.md"),
            "---\ndescription: pasted\n---\n# pasted\n",
        );
        write(
            &clone.join("skills/pasted/mind.toml"),
            "[source]\ndescription = \"a source manifest copied into an item dir\"\n",
        );
        write(
            &clone.join("skills/healthy/SKILL.md"),
            "---\ndescription: healthy\n---\n# healthy\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)
            .expect("one unreadable item manifest must not fail the scan");
        let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["healthy"],
            "both items with an unreadable manifest must be dropped, and only those: {names:?}"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn a_declared_item_with_an_unreadable_manifest_is_dropped_too() {
        // spec: DSC-98
        // The drop is not a convention-scan special case: an item declared in
        // an authoritative `[[items]]` entry that says nothing about hooks
        // still reads its own directory manifest, so it is dropped on the same
        // terms and the rest of the declared inventory survives.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/scanner/SKILL.md"),
            "---\ndescription: scanner\n---\n# scanner\n",
        );
        write(
            &clone.join("skills/scanner/mind.toml"),
            "[discover]\nskills = { include = [\"*/SKILL.md\"] }\n",
        );
        write(
            &clone.join("skills/other/SKILL.md"),
            "---\ndescription: other\n---\n# other\n",
        );
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"skill\"\n",
                "name = \"scanner\"\n",
                "path = \"skills/scanner\"\n",
                "\n",
                "[[items]]\n",
                "kind = \"skill\"\n",
                "name = \"other\"\n",
                "path = \"skills/other\"\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)
            .expect("the declared inventory must still scan");
        let names: Vec<&str> = items.iter().map(|i| i.name.as_str()).collect();
        assert_eq!(names, vec!["other"], "got: {names:?}");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn tool_directory_manifest_declares_hooks_and_beats_frontmatter() {
        // spec: HOOK-131 HOOK-132
        // HOOK-131 names a skill OR a tool. A tool needs no anchor file, so its
        // directory manifest is the one place a convention-discovered tool with
        // no TOOL.md can declare a hook at all -- and when it has both, the
        // manifest REPLACES the frontmatter scalars rather than merging.
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("tools/helper/TOOL.md"),
            "---\ndescription: helper\ninstall: frontmatter-install\nuninstall: frontmatter-uninstall\n---\n# helper\n",
        );
        write(&clone.join("tools/helper/helper"), "#!/bin/sh\n");
        write(
            &clone.join("tools/helper/mind.toml"),
            "[[hooks]]\nrun = \"manifest-build\"\nname = \"Build it\"\noptional = true\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.kind, ItemKind::Tool);
        assert_eq!(
            tool.hooks.len(),
            1,
            "the manifest replaces the TOOL.md scalars: {:?}",
            tool.hooks
        );
        assert_eq!(tool.install_hooks()[0].run, "manifest-build");
        assert!(tool.install_hooks()[0].optional);
        assert_eq!(tool.install_hooks()[0].label(), "Build it");
        assert!(
            tool.uninstall_hooks().is_empty(),
            "the frontmatter uninstall: must not survive the replacement"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn a_declared_tool_falls_through_to_its_tool_md_scalars() {
        // spec: HOOK-130 HOOK-132
        // A `[[items]]` entry silent about hooks does NOT suppress the item's
        // own sites, so a declared tool's TOOL.md `install:`/`uninstall:` are
        // real hooks that will be offered for execution. Before HOOK-130 they
        // populated display-only fields on such an item and never ran, so this
        // is the pin on that change of effect.
        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");
        write(
            &clone.join("mind.toml"),
            concat!(
                "[[items]]\n",
                "kind = \"tool\"\n",
                "name = \"helper\"\n",
                "path = \"tools/helper\"\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_hooks()[0].run, "make setup");
        assert_eq!(tool.uninstall_hooks()[0].run, "make cleanup");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn update_hooks_replace_install_hooks_only_on_a_reinstall() {
        // spec: HOOK-125
        let base = tmp();
        let clone = base.join("sources/local/test/repo");
        write(
            &clone.join("skills/scanner/SKILL.md"),
            "---\ndescription: scanner\ninstall: setup.sh\nupdate: migrate.sh\n---\n# scanner\n",
        );
        write(
            &clone.join("skills/plain/SKILL.md"),
            "---\ndescription: plain\ninstall: setup.sh\n---\n# plain\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 scanner = items.iter().find(|i| i.name == "scanner").unwrap();
        assert_eq!(scanner.install_time_hooks(false)[0].run, "setup.sh");
        assert_eq!(
            scanner.install_time_hooks(true)[0].run,
            "migrate.sh",
            "a re-install runs the update hook in place of the install hook"
        );

        let plain = items.iter().find(|i| i.name == "plain").unwrap();
        assert_eq!(
            plain.install_time_hooks(true)[0].run,
            "setup.sh",
            "an item with no update hook re-runs its install hook, unchanged"
        );
        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);
    }
}