mind-cli 0.48.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
//! Integration tests for `mind curate` (spec/curate.md, CUR-*): one pass that
//! reconciles the melded state with what the registered curators declare.
//!
//! Hermetic: local git repos in temp dirs, `MIND_HOME`/`CLAUDE_HOME` pointed at
//! temp dirs, no network. A curator melded by plain local path is a LINKED
//! source (CLI-27), so edits to its `mind.toml` are visible to the next command
//! with no fetch; the `--no-sync` test melds it pinned, which clones it, so
//! staleness becomes observable.

use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU32, Ordering};

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

struct Env {
    base: PathBuf,
    mind_home: PathBuf,
    claude_home: PathBuf,
}

struct Repo {
    path: PathBuf,
}

struct Run {
    stdout: String,
    stderr: String,
    success: bool,
}

impl Env {
    fn new() -> Env {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-cur-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        std::fs::create_dir_all(&base).unwrap();
        Env {
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
            base,
        }
    }

    fn mind(&self, args: &[&str]) -> Run {
        self.mind_env(args, &[], None)
    }

    /// `mind` with extra environment and optional scripted stdin. With
    /// `("MIND_TTY", "1")` (HOOK-109, the same seam `cli_hooks.rs` and
    /// `cli_install_items.rs` use) plus a reply, the CUR-9 confirmation prompt
    /// is drivable from a headless test: the child gets a pipe, not a
    /// terminal, so without the override `hook::is_tty()` is false and
    /// `should_apply` never asks. `stdin: None` gives the child `/dev/null`,
    /// whose EOF `read_confirm` reads as No.
    fn mind_env(&self, args: &[&str], envs: &[(&str, &str)], stdin: Option<&str>) -> Run {
        use std::io::Write;
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_mind"));
        cmd.args(args)
            .env("MIND_HOME", &self.mind_home)
            .env("CLAUDE_HOME", &self.claude_home)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(match stdin {
                Some(_) => Stdio::piped(),
                None => Stdio::null(),
            });
        for (k, v) in envs {
            cmd.env(k, v);
        }
        let mut child = cmd.spawn().expect("run mind");
        if let Some(text) = stdin {
            child
                .stdin
                .as_mut()
                .expect("piped stdin")
                .write_all(text.as_bytes())
                .expect("write stdin");
        }
        let out = child.wait_with_output().expect("wait for mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    }

    /// A new git repo under this env, with one commit.
    fn repo(&self, name: &str) -> Repo {
        let path = self.base.join(name);
        write(&path.join("README.md"), "# fixture\n");
        git(&path, &["-c", "init.defaultBranch=main", "init", "-q"]);
        git(&path, &["config", "user.email", "t@t"]);
        git(&path, &["config", "user.name", "t"]);
        git(&path, &["add", "-A"]);
        git(&path, &["commit", "-qm", "initial"]);
        Repo { path }
    }

    /// The identity a local repo registers under: `local/<base>/<name>`.
    fn ident(&self, name: &str) -> String {
        format!(
            "local/{}/{name}",
            self.base.file_name().unwrap().to_string_lossy()
        )
    }

    fn sources_json(&self) -> String {
        std::fs::read_to_string(self.mind_home.join("sources.json")).unwrap_or_default()
    }
}

impl Drop for Env {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.base);
    }
}

impl Repo {
    fn write_and_commit(&self, rel: &str, contents: &str) {
        write(&self.path.join(rel), contents);
        git(&self.path, &["add", "-A"]);
        git(&self.path, &["commit", "-qm", "fixture"]);
    }

    fn spec(&self) -> String {
        self.path.to_string_lossy().into_owned()
    }

    fn head(&self) -> String {
        let out = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&self.path)
            .output()
            .expect("git rev-parse");
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    /// A `[discover].sources` list naming `entries` verbatim.
    fn curate_list(&self, entries: &[String]) {
        self.write_and_commit(
            "mind.toml",
            &format!("[discover]\nsources = [\n{}\n]\n", entries.join(",\n")),
        );
    }
}

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

fn git(dir: &Path, args: &[&str]) {
    let status = Command::new("git")
        .args(args)
        .current_dir(dir)
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .expect("run git");
    assert!(status.success(), "git {args:?} failed in {dir:?}");
}

/// A library repo with one skill, and a curator that lists it with `install`.
fn lib_and_curator(env: &Env, entry_extra: &str) -> (Repo, Repo) {
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff\n---\n# review\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!("{{ source = \"{}\"{entry_extra} }}", lib.spec())]);
    (lib, curator)
}

#[test]
fn curate_reports_up_to_date_when_nothing_is_curated() {
    // spec: CUR-1
    // No curators registered at all is a clean report, not an error.
    let env = Env::new();
    let plain = env.repo("plain");
    plain.write_and_commit(
        "skills/solo/SKILL.md",
        "---\ndescription: solo\n---\n# solo\n",
    );
    let m = env.mind(&["meld", &plain.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let r = env.mind(&["curate"]);
    assert!(r.success, "curate failed: {} {}", r.stdout, r.stderr);
    assert!(
        r.stdout.contains("up to date"),
        "expected a clean report: {}",
        r.stdout
    );
}

#[test]
fn a_newly_listed_entry_is_registered_and_installed() {
    // spec: CUR-1 CUR-3 CUR-4
    // The gap `sync` leaves: it registers a newly listed entry but installs
    // nothing, even when the curator marked it `install = true`.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[source]\ndescription = \"curator\"\n");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff\n---\n# review\n",
    );
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate --check failed: {}", plan.stderr);
    assert!(
        plan.stdout.contains("register") && plan.stdout.contains(&env.ident("lib")),
        "the plan must name the unregistered entry: {}",
        plan.stdout
    );

    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "curate --yes failed: {}", applied.stderr);
    assert!(
        env.claude_home.join("skills/review").exists(),
        "the entry's declared items must install in the same run: {}",
        applied.stdout
    );
}

#[test]
fn check_changes_nothing() {
    // spec: CUR-9
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    // Register the curator only; the entry is listed but not yet registered.
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let before = env.sources_json();
    let r = env.mind(&["curate", "--check", "--yes"]);
    assert!(r.success, "curate --check failed: {}", r.stderr);
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "--check must install nothing"
    );
    assert_eq!(
        before,
        env.sources_json(),
        "--check must not touch the registry, even with --yes"
    );
}

#[test]
fn declared_items_that_are_not_installed_are_offered() {
    // spec: CUR-4 CUR-12
    // The entry is registered (a `sync` re-walk got there first) but its
    // declared items were never installed.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let s = env.mind(&["sync"]);
    assert!(s.success, "sync failed: {} {}", s.stdout, s.stderr);
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "sync registers the entry but installs nothing (DSC-57)"
    );

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.stdout.contains("install") && plan.stdout.contains("skill:review"),
        "the plan must name the uninstalled declared item: {}",
        plan.stdout
    );
    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "curate --yes failed: {}", applied.stderr);
    assert!(
        env.claude_home.join("skills/review").exists(),
        "applying must install it: {}",
        applied.stdout
    );
}

#[test]
fn a_register_only_entry_proposes_no_install() {
    // spec: CUR-4 CUR-12
    // An entry declaring neither `install` nor `install-items` is register-only
    // by the curator's choice; `curate` never installs from it.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, "");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let r = env.mind(&["curate", "--yes"]);
    assert!(r.success, "curate failed: {}", r.stderr);
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "a register-only entry installs nothing: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("up to date"),
        "and it is not reported as pending: {}",
        r.stdout
    );
}

#[test]
fn install_items_offers_only_the_declared_subset() {
    // spec: CUR-4
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    lib.write_and_commit(
        "skills/extra/SKILL.md",
        "---\ndescription: Extra\n---\n# extra\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install-items = [\"skill:review\"] }}",
        lib.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let r = env.mind(&["curate", "--yes"]);
    assert!(r.success, "curate failed: {}", r.stderr);
    assert!(
        env.claude_home.join("skills/review").exists(),
        "the declared item installs: {}",
        r.stdout
    );
    assert!(
        !env.claude_home.join("skills/extra").exists(),
        "an undeclared item must not: {}",
        r.stdout
    );
}

#[test]
fn a_changed_pin_directive_is_reported_and_applied() {
    // spec: CUR-5
    let env = Env::new();
    let (lib, curator) = lib_and_curator(&env, ", install = true");
    let first = lib.head();
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    // Upstream moves, and the curator pins the older commit.
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\nsecond\n",
    );
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, pin-ref = \"{first}\" }}",
        lib.spec()
    )]);

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.stdout.contains("repin"),
        "a changed pin directive must be reported: {}",
        plan.stdout
    );
    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "curate --yes failed: {}", applied.stderr);
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains(&first[..8]),
        "the source must be re-pinned to the curator's commit: {}",
        sources.stdout
    );
}

/// The recorded pin of the source registered as `identity`.
fn recorded_pin(env: &Env, identity: &str) -> serde_json::Value {
    let doc: serde_json::Value = serde_json::from_str(&env.sources_json()).unwrap();
    doc["sources"]
        .as_array()
        .unwrap()
        .iter()
        .find(|s| s["name"] == identity)
        .map(|s| s["pin"].clone())
        .unwrap_or_else(|| panic!("{identity} not registered: {doc}"))
}

#[test]
fn a_curator_pin_version_resolves_and_a_changed_range_is_re_pinned() {
    // spec: VER-110
    let env = Env::new();
    let lib = env.repo("lib");
    for (body, tag) in [
        ("one-zero", "v1.0.0"),
        ("one-one", "v1.1.0"),
        ("two", "v2.0.0"),
    ] {
        lib.write_and_commit(
            "skills/review/SKILL.md",
            &format!("---\ndescription: Review\n---\n# review\n{body}\n"),
        );
        git(&lib.path, &["tag", tag]);
    }
    let curator = env.repo("curator");
    let entry = |range: &str| {
        format!(
            "{{ source = \"{}\", install = true, pin-version = \"{range}\" }}",
            lib.spec()
        )
    };
    curator.curate_list(&[entry("^1")]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let pin = recorded_pin(&env, &env.ident("lib"));
    assert_eq!(pin["kind"], "version", "{pin}");
    assert_eq!(pin["value"]["range"], "^1", "{pin}");
    assert_eq!(pin["value"]["resolved"], "1.1.0", "{pin}");

    // An unchanged range is not a pin change, though a resolution is recorded.
    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "{}", plan.stderr);
    assert!(!plan.stdout.contains("repin"), "{}", plan.stdout);

    // A changed range is re-pinned like any other pin change.
    curator.curate_list(&[entry("^2")]);
    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.stdout.contains("repin"), "{}", plan.stdout);
    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "{} {}", applied.stdout, applied.stderr);
    let pin = recorded_pin(&env, &env.ident("lib"));
    assert_eq!(pin["value"]["range"], "^2", "{pin}");
    assert_eq!(pin["value"]["resolved"], "2.0.0", "{pin}");

    // A range that does not parse is skipped, not applied.
    curator.curate_list(&[entry("not-a-range")]);
    let plan = env.mind(&["curate", "--check", "--json"]);
    assert!(
        plan.stdout.contains("pin_directive_invalid"),
        "{}",
        plan.stdout
    );
}

#[test]
fn an_outdated_curated_source_is_reported_and_upgraded() {
    // spec: CUR-6
    let env = Env::new();
    let (lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());

    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\nupdated\n",
    );
    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.stdout.contains("upgrade"),
        "an out-of-date curated source must be reported: {}",
        plan.stdout
    );
    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "curate --yes failed: {}", applied.stderr);
    let installed =
        std::fs::read_to_string(env.claude_home.join("skills/review/SKILL.md")).expect("installed");
    assert!(
        installed.contains("updated"),
        "applying must land the new content: {installed}"
    );
}

#[test]
fn an_unlisted_source_is_reported_but_pruned_only_with_prune() {
    // spec: CUR-7
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());

    // The curator drops the entry.
    curator.write_and_commit("mind.toml", "[discover]\nsources = []\n");

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.stdout.contains("unlist") && plan.stdout.contains(&env.ident("lib")),
        "a dropped entry must be reported: {}",
        plan.stdout
    );

    let yes = env.mind(&["curate", "--yes"]);
    assert!(yes.success, "curate --yes failed: {}", yes.stderr);
    assert!(
        env.claude_home.join("skills/review").exists(),
        "--yes alone must not uninstall a dropped entry's items: {}",
        yes.stdout
    );

    let pruned = env.mind(&["curate", "--yes", "--prune"]);
    assert!(pruned.success, "curate --prune failed: {}", pruned.stderr);
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "--prune applies the unlist: {}",
        pruned.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        !sources.stdout.contains(&env.ident("lib")),
        "and drops the source: {}",
        sources.stdout
    );
}

#[test]
fn a_directly_melded_source_is_never_unlisted() {
    // spec: CUR-7 STO-82
    // Provenance is what separates "no longer listed" from "never curated": a
    // source melded by hand records no curator and is never proposed.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[discover]\nsources = []\n");
    for spec in [lib.spec(), curator.spec()] {
        let m = env.mind(&["meld", &spec, "--register-only"]);
        assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    }
    let json = env.sources_json();
    assert!(
        !json.contains("curated_by"),
        "a direct meld records no curator: {json}"
    );
    let r = env.mind(&["curate", "--check"]);
    assert!(
        !r.stdout.contains("unlist"),
        "a directly melded source must never be proposed for unlisting: {}",
        r.stdout
    );
}

#[test]
fn a_curated_meld_records_its_curator() {
    // spec: STO-82
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let json = env.sources_json();
    assert!(
        json.contains("\"curated_by\"") && json.contains(&env.ident("curator")),
        "the nested source must record the curator that listed it: {json}"
    );
}

#[test]
fn a_changed_namespace_is_advisory_only() {
    // spec: CUR-8
    let env = Env::new();
    let (lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, namespace = \"acme\" }}",
        lib.spec()
    )]);
    let r = env.mind(&["curate", "--yes"]);
    assert!(r.success, "curate failed: {}", r.stderr);
    assert!(
        r.stdout.contains("namespace") && r.stdout.contains("mind unmeld"),
        "the advisory must name the two-step adoption: {}",
        r.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        !sources.stdout.contains("@acme"),
        "an advisory change must never be applied: {}",
        sources.stdout
    );
}

#[test]
fn no_sync_plans_against_the_clone_on_disk() {
    // spec: CUR-2
    // A pinned local curator is cloned (CLI-27), so an edit upstream is
    // invisible until the fetch `curate` performs by default.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[discover]\nsources = []\n");
    let m = env.mind(&[
        "meld",
        &curator.spec(),
        "--pin",
        "branch=main",
        "--register-only",
    ]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);

    let stale = env.mind(&["curate", "--check", "--no-sync"]);
    assert!(stale.success, "curate --no-sync failed: {}", stale.stderr);
    assert!(
        stale.stdout.contains("up to date"),
        "--no-sync plans against the clone, which has not seen the new entry: {}",
        stale.stdout
    );

    let fresh = env.mind(&["curate", "--check"]);
    assert!(
        fresh.stdout.contains("register"),
        "the default fetch must pick the new entry up: {}",
        fresh.stdout
    );
}

#[test]
fn json_reports_the_plan_and_what_was_applied() {
    // spec: CUR-13 CUR-14
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let pending = env.mind(&["curate", "--json", "--check"]);
    assert!(
        pending.success,
        "pending changes must still exit 0 (CUR-14): {}",
        pending.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&pending.stdout).expect("json");
    assert_eq!(doc["schema"], 1);
    assert_eq!(doc["action"], "curate");
    assert_eq!(doc["outcome"], "pending");
    assert_eq!(doc["changes"][0]["kind"], "install");
    // spec: CUR-13 -- `applied` is always present, even empty, not omitted.
    assert_eq!(
        doc["applied"],
        serde_json::json!([]),
        "nothing applied under --check, but the key must still be an empty array: {}",
        pending.stdout
    );

    let applied = env.mind(&["curate", "--json", "--yes"]);
    assert!(applied.success, "apply failed: {}", applied.stderr);
    let doc: serde_json::Value = serde_json::from_str(&applied.stdout).expect("json");
    assert_eq!(doc["outcome"], "applied");
    assert!(
        doc["applied"][0]
            .as_str()
            .is_some_and(|s| s.starts_with("install:")),
        "the applied list names each change: {}",
        applied.stdout
    );
}

#[test]
fn changes_apply_in_a_fixed_order() {
    // spec: CUR-10
    // A plan with a register and an upgrade applies the register first, so a
    // newly listed entry's items are installed before the upgrade pass runs.
    let env = Env::new();
    let first = env.repo("first");
    first.write_and_commit("skills/one/SKILL.md", "---\ndescription: One\n---\n# one\n");
    let curator = env.repo("curator");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true }}",
        first.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    // `first` moves upstream (an upgrade), and a second entry appears (a register).
    first.write_and_commit(
        "skills/one/SKILL.md",
        "---\ndescription: One\n---\n# one\nupdated\n",
    );
    let second = env.repo("second");
    second.write_and_commit("skills/two/SKILL.md", "---\ndescription: Two\n---\n# two\n");
    curator.curate_list(&[
        format!("{{ source = \"{}\", install = true }}", first.spec()),
        format!("{{ source = \"{}\", install = true }}", second.spec()),
    ]);

    let r = env.mind(&["curate", "--json", "--yes"]);
    assert!(r.success, "curate failed: {}", r.stderr);
    let doc: serde_json::Value = serde_json::from_str(&r.stdout).expect("json");
    let applied: Vec<&str> = doc["applied"]
        .as_array()
        .expect("applied")
        .iter()
        .map(|v| v.as_str().unwrap_or_default())
        .collect();
    let register_at = applied
        .iter()
        .position(|a| a.starts_with("register:"))
        .expect("a register change must have applied");
    let upgrade_at = applied
        .iter()
        .position(|a| a.starts_with("upgrade:"))
        .expect("an upgrade change must have applied");
    assert!(
        register_at < upgrade_at,
        "register must apply before upgrade: {applied:?}"
    );
    assert!(
        env.claude_home.join("skills/two").exists(),
        "the newly listed entry's item installs"
    );
}

#[test]
fn hook_consent_passes_through_to_the_registrations_curate_applies() {
    // spec: CUR-11
    // `curate` adds no hook path of its own: a newly registered entry's source
    // install hook takes the ordinary consent route (skipped on a non-TTY run,
    // HOOK-22), and the skip flag passes through to it.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[discover]\nsources = []\n");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let marker = env.base.join("hook-ran");
    lib.write_and_commit(
        "mind.toml",
        &format!(
            "[[hooks]]\nname = \"setup\"\nrun = \"touch {}\"\nevent = \"install\"\n",
            marker.display()
        ),
    );
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);

    // No TTY and no skip flag: the hook is disclosed and skipped, not run.
    let guarded = env.mind(&["curate", "--yes"]);
    assert!(guarded.success, "curate failed: {}", guarded.stderr);
    assert!(
        !marker.exists(),
        "an unconsented hook must not run: {} {}",
        guarded.stdout,
        guarded.stderr
    );

    // With the skip flag it runs, on the same path any meld would take.
    let un = env.mind(&["unmeld", &env.ident("lib"), "--yes"]);
    assert!(un.success, "unmeld failed: {} {}", un.stdout, un.stderr);
    let skipped = env.mind(&["curate", "--yes", "--accept-hooks=install,update,uninstall"]);
    assert!(skipped.success, "curate failed: {}", skipped.stderr);
    assert!(
        marker.exists(),
        "the skip flag must reach the registration's hook: {} {}",
        skipped.stdout,
        skipped.stderr
    );
}

#[test]
fn a_marketplace_entry_still_listed_is_not_proposed_for_unlisting() {
    // spec: CUR-4 CUR-7
    // A marketplace catalog curates too (MKT-7): its entries declare no install
    // directive, so they propose nothing while they are listed, and drop out of
    // the listed set (an `unlist`) when the manifest stops naming them.
    let env = Env::new();
    let plugin = env.repo("plugin");
    plugin.write_and_commit("skills/kit/SKILL.md", "---\ndescription: Kit\n---\n# kit\n");
    let catalog = env.repo("catalog");
    // An external entry: a source object with a `url`, which for a hermetic
    // fixture is the plugin repo's local path.
    catalog.write_and_commit(
        ".claude-plugin/marketplace.json",
        &format!(
            r#"{{"name":"Cat","plugins":[{{"name":"kit","source":{{"url":"{}"}}}}]}}"#,
            plugin.spec()
        ),
    );
    let m = env.mind(&["meld", &catalog.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains("@kit"),
        "the external marketplace entry must register: {}",
        sources.stdout
    );

    let listed = env.mind(&["curate", "--check"]);
    assert!(listed.success, "curate failed: {}", listed.stderr);
    assert!(
        !listed.stdout.contains("unlist"),
        "an entry still in the manifest must not be proposed for unlisting: {}",
        listed.stdout
    );

    // The catalog drops the entry.
    catalog.write_and_commit(
        ".claude-plugin/marketplace.json",
        r#"{"name":"Cat","plugins":[]}"#,
    );
    let dropped = env.mind(&["curate", "--check"]);
    assert!(
        dropped.stdout.contains("unlist") && dropped.stdout.contains("@kit"),
        "a dropped catalog entry must be reported: {}",
        dropped.stdout
    );
}

#[test]
fn an_entry_naming_a_directly_melded_source_proposes_nothing_against_it() {
    // spec: CUR-4 CUR-5 CUR-12 CUR-16
    // A curator's entry can resolve to the same identity as a source the
    // consumer melded by hand (same repo, no alias). That entry must not be
    // able to install into or repin a source it does not own: CUR-12 says
    // `curate` never changes a directly-melded source, and that must hold
    // even when some OTHER curator's list happens to name it.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "a direct meld records no curator: {}",
        env.sources_json()
    );

    let curator = env.repo("curator");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, pin-ref = \"{}\" }}",
        lib.spec(),
        lib.head()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert!(
        !plan.stdout.contains("repin") && !plan.stdout.contains("install"),
        "an entry naming an identity it does not own must propose nothing: {}",
        plan.stdout
    );
    // spec: CUR-16
    assert!(
        plan.stdout.contains("adopt") && plan.stdout.contains("--adopt"),
        "the unowned identity must be reported as an adopt candidate: {}",
        plan.stdout
    );

    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "curate --yes failed: {}", applied.stderr);
    assert!(
        !env.sources_json().contains("\"kind\": \"ref\""),
        "the directly melded source's pin must not move off the default branch: {}",
        env.sources_json()
    );
}

#[test]
fn a_marketplace_entry_naming_a_directly_melded_source_proposes_no_upgrade() {
    // spec: CUR-6 CUR-12
    // The same ownership guard applies to the marketplace `market` loop as to
    // the `[discover].sources` entry loop: a catalog plugin that resolves to
    // an identity it does not itself own must not pull that source into the
    // CUR-6 upgrade sweep.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--namespace", "mine", "--yes"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "a direct meld records no curator: {}",
        env.sources_json()
    );

    let catalog = env.repo("catalog");
    catalog.write_and_commit(
        ".claude-plugin/marketplace.json",
        &format!(
            r#"{{"name":"Cat","plugins":[{{"name":"mine","source":{{"url":"{}"}}}}]}}"#,
            lib.spec()
        ),
    );
    let m = env.mind(&["meld", &catalog.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    // Upstream moves, so a source curate is willing to touch would be flagged.
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\nsecond\n",
    );

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert!(
        !plan.stdout.contains("upgrade"),
        "a marketplace entry naming an identity it does not own must propose nothing: {}",
        plan.stdout
    );
}

#[test]
fn a_source_cannot_shield_itself_from_unlisting_by_listing_itself() {
    // spec: CUR-17
    // Without the self-listing exclusion, a curated source could list its own
    // identity in its own mind.toml and stay in the CUR-7 "still listed" set
    // forever, even after the curator that actually registered it drops it.
    let env = Env::new();
    let (lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(
        env.claude_home.join("skills/review").exists(),
        "the curated item must install: {}",
        m.stdout
    );

    // The curated source lists itself.
    lib.write_and_commit(
        "mind.toml",
        &format!(
            "[discover]\nsources = [{{ source = \"{}\" }}]\n",
            lib.spec()
        ),
    );
    // The real curator drops it.
    curator.curate_list(&[]);

    let plan = env.mind(&["curate", "--check", "--prune"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert!(
        plan.stdout.contains("unlist") && plan.stdout.contains(&env.ident("lib")),
        "self-listing must not shield a source from unlisting once its real curator drops it: {}",
        plan.stdout
    );
}

#[test]
fn an_unreadable_curator_does_not_sweep_its_sources_into_unlist() {
    // spec: CUR-15
    // A curator's clone disappearing (moved, unmounted) must not read the
    // same as "this curator lists nothing now": that would propose `unlist`
    // for every source it legitimately owns.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());

    std::fs::rename(&curator.path, env.base.join("curator-moved")).unwrap();

    let plan = env.mind(&["curate", "--check", "--prune"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    assert!(
        !plan.stdout.contains("unlist"),
        "an unreadable curator must not sweep the sources it owns into unlist: {}",
        plan.stdout
    );
    assert!(
        plan.stdout.contains("skipped"),
        "the unreadable curator should be reported, not silently dropped: {}",
        plan.stdout
    );
}

#[test]
fn one_entrys_invalid_pin_directive_does_not_abort_the_whole_plan() {
    // spec: CUR-15
    let env = Env::new();
    let ok_lib = env.repo("ok-lib");
    ok_lib.write_and_commit("skills/ok/SKILL.md", "---\ndescription: Ok\n---\n# ok\n");
    let bad_lib = env.repo("bad-lib");
    bad_lib.write_and_commit("skills/bad/SKILL.md", "---\ndescription: Bad\n---\n# bad\n");

    let curator = env.repo("curator");
    curator.curate_list(&[
        format!("{{ source = \"{}\", install = true }}", ok_lib.spec()),
        format!("{{ source = \"{}\", install = true }}", bad_lib.spec()),
    ]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/ok").exists());
    assert!(env.claude_home.join("skills/bad").exists());

    // bad-lib's entry gains conflicting pin directives (DSC-41's one-of rule).
    curator.curate_list(&[
        format!("{{ source = \"{}\", install = true }}", ok_lib.spec()),
        format!(
            "{{ source = \"{}\", install = true, pin-ref = \"deadbeef\", follow-branch = \"main\" }}",
            bad_lib.spec()
        ),
    ]);
    // Upstream moves, so ok-lib shows an upgrade if the run reaches that far.
    ok_lib.write_and_commit(
        "skills/ok/SKILL.md",
        "---\ndescription: Ok\n---\n# ok\nsecond\n",
    );

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.success,
        "one entry's bad pin directive must not abort the whole plan: {} {}",
        plan.stdout, plan.stderr
    );
    assert!(
        plan.stdout.contains("upgrade") && plan.stdout.contains(&env.ident("ok-lib")),
        "the other entry must still be planned: {}",
        plan.stdout
    );
}

#[test]
fn curate_adopt_stamps_provenance_then_curate_manages_the_source_normally() {
    // spec: CUR-16
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );

    let curator = env.repo("curator");
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    let identity = env.ident("lib");
    assert!(
        plan.stdout.contains("adopt") && plan.stdout.contains(&identity),
        "an unowned identity a curator lists must be reported as adoptable: {}",
        plan.stdout
    );

    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        adopted.success,
        "curate --adopt failed: {} {}",
        adopted.stdout, adopted.stderr
    );
    assert!(
        env.sources_json().contains("\"curated_by\""),
        "adopt must stamp curated_by: {}",
        env.sources_json()
    );

    let after = env.mind(&["curate", "--check"]);
    assert!(after.success, "curate failed: {}", after.stderr);
    assert!(
        after.stdout.contains("install") && !after.stdout.contains("adopt"),
        "once adopted, curate must plan install/repin/upgrade for it normally: {}",
        after.stdout
    );
}

#[test]
fn adopting_an_identity_no_curator_lists_is_refused() {
    // spec: CUR-16
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let m = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let identity = env.ident("lib");
    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        !adopted.success,
        "adopting an identity no curator lists must fail, not silently do nothing: {}",
        adopted.stdout
    );
}

#[test]
fn ansi_in_a_curators_install_items_is_stripped_from_the_plan() {
    // spec: CUR-18
    // The register detail echoes a curator's raw install-items refs before
    // anything validates them against a real catalog, which is exactly why
    // that path (unlike the install detail's already-matched item keys) can
    // carry attacker-controlled text: the entry must still be unregistered
    // when `curate` reads it, so the curator is melded before the entry (with
    // its ANSI-laden ref) exists in its list, mirroring
    // `a_newly_listed_entry_is_registered_and_installed`.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[source]\ndescription = \"curator\"\n");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install-items = [\"skill:review\\u001b[31mHIDDEN\\u001b[0m\"] }}",
        lib.spec()
    )]);

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert!(
        !plan.stdout.contains('\u{1b}'),
        "curator-controlled text reaching the plan must have ANSI stripped: {:?}",
        plan.stdout
    );
}

#[test]
fn curate_sync_does_not_touch_a_source_that_is_neither_curator_nor_curated() {
    // spec: CUR-19
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let unrelated = env.repo("unrelated");
    unrelated.write_and_commit("skills/x/SKILL.md", "---\ndescription: X\n---\n# x\n");
    let u = env.mind(&[
        "meld",
        &unrelated.spec(),
        "--pin",
        "branch=main",
        "--register-only",
    ]);
    assert!(u.success, "meld failed: {} {}", u.stdout, u.stderr);
    let before = env.sources_json();

    // Upstream moves; a scoped sync must not notice, since `unrelated` is
    // neither a curator nor curated by one.
    unrelated.write_and_commit(
        "skills/x/SKILL.md",
        "---\ndescription: X\n---\n# x\nsecond\n",
    );

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert_eq!(
        before,
        env.sources_json(),
        "curate's refresh must not touch a source that is neither a curator nor curated"
    );
}

#[test]
fn json_clean_run_still_emits_empty_applied_and_skipped_arrays() {
    // spec: CUR-13
    // `applied` and `skipped` must always be present, as `[]` when there is
    // nothing to report, never omitted -- a caller should not have to
    // distinguish "key absent" from "key present but empty".
    let env = Env::new();
    let plain = env.repo("plain");
    plain.write_and_commit(
        "skills/solo/SKILL.md",
        "---\ndescription: solo\n---\n# solo\n",
    );
    let m = env.mind(&["meld", &plain.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let r = env.mind(&["curate", "--json"]);
    assert!(r.success, "curate failed: {} {}", r.stdout, r.stderr);
    let doc: serde_json::Value = serde_json::from_str(&r.stdout).expect("json");
    assert_eq!(doc["outcome"], "clean");
    assert_eq!(
        doc["changes"],
        serde_json::json!([]),
        "changes must be an empty array, not absent: {}",
        r.stdout
    );
    assert_eq!(
        doc["applied"],
        serde_json::json!([]),
        "applied must be an empty array, not absent: {}",
        r.stdout
    );
    assert_eq!(
        doc["skipped"],
        serde_json::json!([]),
        "skipped must be an empty array, not absent: {}",
        r.stdout
    );
}
#[test]
fn invisible_unicode_in_curator_and_source_identities_is_stripped_from_json() {
    // spec: CUR-18
    // Unlike a curator-controlled *value* embedded in `detail` (an
    // install-items ref, a pin directive), `curator` and `source` are
    // identity strings assembled from directory names. The identity
    // validator (`validate_identity_part` in source.rs) only rejects Rust's
    // narrow `char::is_control()` set, which blocks a raw ANSI escape (ESC is
    // a C0 control) but NOT the wider "blocked Unicode" set `strip_ansi` also
    // removes (a bidi override, a zero-width character). So a curator or
    // curated source whose local directory name carries one of those must
    // still have it stripped from `--json`'s `curator`/`source` fields, not
    // just from `detail`.
    let env = Env::new();
    let curator = env.repo("curator\u{202E}evil");
    curator.write_and_commit("mind.toml", "[source]\ndescription = \"curator\"\n");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib\u{200B}sneaky");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff\n---\n# review\n",
    );
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);

    let plan = env.mind(&["curate", "--check", "--json"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&plan.stdout).expect("json");
    let change = &doc["changes"][0];
    let curator_field = change["curator"].as_str().expect("curator field");
    let source_field = change["source"].as_str().expect("source field");
    assert!(
        !curator_field.contains('\u{202E}'),
        "the bidi override must be stripped from the curator field: {curator_field:?}"
    );
    assert!(
        !source_field.contains('\u{200B}'),
        "the zero-width space must be stripped from the source field: {source_field:?}"
    );
    assert!(
        curator_field.contains("curator"),
        "curator field must still name the curator: {curator_field:?}"
    );
    assert!(
        source_field.contains("lib"),
        "source field must still name the entry: {source_field:?}"
    );
}
#[test]
fn a_skipped_entry_strips_invisible_unicode_from_the_identity_it_names() {
    // spec: CUR-18 CUR-13
    // `Change` is not the only curator-controlled text `curate` prints: the
    // CUR-13 `skipped` array names identities too, and an identity is
    // assembled from directory names that `validate_identity_part` screens
    // only for C0/C1 controls -- a bidi override or a zero-width character
    // passes it (the same reasoning that made `Change::new` sanitize `curator`
    // and `source`). Text mode strips it on the way out; `--json` is the
    // surface that could still hand a reader an invisible character.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let curator = env.repo("curator\u{202E}evil");
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(
        env.sources_json().contains('\u{202E}'),
        "the fixture is only meaningful if the identity really carries the \
         bidi override: {}",
        env.sources_json()
    );

    // The curator's clone disappears: CUR-15 reports it as `curator_unreadable`,
    // naming the identity.
    std::fs::rename(&curator.path, env.base.join("curator-moved")).unwrap();

    let text = env.mind(&["curate", "--check"]);
    assert!(
        text.success,
        "curate failed: {} {}",
        text.stdout, text.stderr
    );
    assert!(
        !text.stdout.contains('\u{202E}'),
        "text mode must not print the bidi override: {:?}",
        text.stdout
    );

    let json = env.mind(&["curate", "--check", "--json"]);
    assert!(
        json.success,
        "curate --json failed: {} {}",
        json.stdout, json.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&json.stdout).expect("json");
    assert_eq!(
        doc["skipped"][0]["reason"], "curator_unreadable",
        "fixture must produce the skipped entry under test: {doc}"
    );
    let named = doc["skipped"][0]["source"]
        .as_str()
        .expect("skipped source");
    assert!(
        !named.contains('\u{202E}'),
        "the bidi override must be stripped from the skipped identity too: {named:?}"
    );
    assert!(
        named.contains("curator"),
        "while still naming the curator: {named:?}"
    );
}

#[test]
fn register_detail_names_the_resolved_url_or_path() {
    // spec: CUR-1 CUR-3
    // A `register` change's `detail` must name the entry's resolved URL/path
    // (from parsing its spec), not just the curator identity and the item
    // refs, so a reader sees what is about to be cloned.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[source]\ndescription = \"curator\"\n");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff\n---\n# review\n",
    );
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);

    let plan = env.mind(&["curate", "--check", "--json"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&plan.stdout).expect("json");
    let detail = doc["changes"][0]["detail"].as_str().expect("detail field");
    assert_eq!(doc["changes"][0]["kind"], "register");
    assert!(
        detail.contains(&lib.spec()),
        "the register detail must name the resolved path: {detail:?}"
    );

    // Also visible in the plain-text plan, not just `--json`.
    let text_plan = env.mind(&["curate", "--check"]);
    assert!(
        text_plan.stdout.contains(&lib.spec()),
        "the printed plan must also name the resolved path: {}",
        text_plan.stdout
    );
}

#[test]
fn a_prune_only_plan_still_prompts_and_applies_on_yes() {
    // spec: CUR-9 CUR-7 HOOK-109
    // The confirmation gate counted applicable changes with `prune = false`
    // while the apply used the real flag, so a plan of nothing but `unlist`
    // changes under `--prune` on a terminal short-circuited to "nothing
    // applicable": no prompt, no apply, no error, exit 0.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());

    // The curator drops the entry: the whole plan is now one `unlist`.
    curator.curate_list(&[]);

    let r = env.mind_env(&["curate", "--prune"], &[("MIND_TTY", "1")], Some("y\n"));
    assert!(
        r.success,
        "curate --prune failed: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        r.stdout.contains("apply these 1 change(s)"),
        "a prune-only plan must still reach the confirmation prompt: {}",
        r.stdout
    );
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "answering yes must apply the unlist: {}",
        r.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        !sources.stdout.contains(&env.ident("lib")),
        "and drop the source: {}",
        sources.stdout
    );
}

#[test]
fn a_prune_only_plan_answered_no_applies_nothing() {
    // spec: CUR-9 CUR-7 HOOK-109
    // The other side of the gate: reaching the prompt is not the same as
    // applying, so `n` must leave the source and its items in place.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    curator.curate_list(&[]);

    let r = env.mind_env(&["curate", "--prune"], &[("MIND_TTY", "1")], Some("n\n"));
    assert!(
        r.success,
        "curate --prune failed: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        env.claude_home.join("skills/review").exists(),
        "a declined prompt must uninstall nothing: {}",
        r.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains(&env.ident("lib")),
        "nor drop the source: {}",
        sources.stdout
    );
}

#[test]
fn a_mixed_prune_plan_names_the_destructive_changes_in_the_prompt() {
    // spec: CUR-9 CUR-7 HOOK-109
    // With `prune = false` hardcoded in the count, the prompt for this plan
    // read "apply these 1 change(s) now?" while answering yes ALSO uninstalled
    // and dropped a second source. The count must match what applies, and the
    // destructive part of it must be named.
    let env = Env::new();
    let a = env.repo("lib-a");
    a.write_and_commit("skills/a/SKILL.md", "---\ndescription: A\n---\n# a\n");
    let b = env.repo("lib-b");
    b.write_and_commit("skills/b/SKILL.md", "---\ndescription: B\n---\n# b\n");
    let curator = env.repo("curator");
    curator.curate_list(&[
        format!("{{ source = \"{}\", install = true }}", a.spec()),
        format!("{{ source = \"{}\", install = true }}", b.spec()),
    ]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/a").exists());
    assert!(env.claude_home.join("skills/b").exists());

    // One pending `install` (a declared item forgotten) ...
    let forget = env.mind(&["forget", "skill:a", "--yes"]);
    assert!(
        forget.success,
        "forget failed: {} {}",
        forget.stdout, forget.stderr
    );
    // ... and one pending `unlist` (lib-b dropped from the list).
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", a.spec())]);

    let r = env.mind_env(&["curate", "--prune"], &[("MIND_TTY", "1")], Some("y\n"));
    assert!(
        r.success,
        "curate --prune failed: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        r.stdout.contains("apply these 2 change(s)"),
        "the prompt must count every change this run would apply: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("1 `unlist`") && r.stdout.contains("uninstall"),
        "and say that one of them uninstalls a source: {}",
        r.stdout
    );
    assert!(
        env.claude_home.join("skills/a").exists(),
        "yes must apply the install: {}",
        r.stdout
    );
    assert!(
        !env.claude_home.join("skills/b").exists(),
        "and the unlist: {}",
        r.stdout
    );
}

#[test]
fn json_mode_applies_nothing_and_prompts_nobody_even_with_prune() {
    // spec: CUR-9 CUR-13
    // `should_apply` now reads the whole flag set, so the `--prune` count is
    // real; the json/non-TTY bail must still come FIRST. A `--json` run on a
    // terminal with an answer already waiting on stdin is the adversarial
    // shape: there is no prompt to answer, so the run must report and stop.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());
    curator.curate_list(&[]); // the whole plan is now one `unlist`

    let r = env.mind_env(
        &["curate", "--prune", "--json"],
        &[("MIND_TTY", "1")],
        Some("y\n"),
    );
    assert!(r.success, "curate failed: {} {}", r.stdout, r.stderr);
    let doc: serde_json::Value = serde_json::from_str(&r.stdout).expect("json");
    assert_eq!(doc["outcome"], "pending", "{doc}");
    assert_eq!(doc["changes"][0]["kind"], "unlist", "{doc}");
    assert_eq!(
        doc["applied"],
        serde_json::json!([]),
        "--json without --yes applies nothing, --prune or not: {doc}"
    );
    assert!(
        !r.stdout.contains("apply these"),
        "and never prompts: {}",
        r.stdout
    );
    assert!(
        env.claude_home.join("skills/review").exists(),
        "the source's items stay installed: {}",
        r.stdout
    );

    // The same plan in text mode on a non-TTY: reported, not applied, with the
    // note counting what `--prune` WOULD apply.
    let text = env.mind(&["curate", "--prune"]);
    assert!(
        text.success,
        "curate failed: {} {}",
        text.stdout, text.stderr
    );
    assert!(
        text.stdout.contains("nothing applied") && text.stdout.contains("1 change(s)"),
        "a non-TTY run says how to apply the change it counted: {}",
        text.stdout
    );
    assert!(
        env.claude_home.join("skills/review").exists(),
        "and applies nothing: {}",
        text.stdout
    );
}

#[test]
fn a_prune_run_whose_plan_has_no_unlist_prompts_without_the_destructive_wording() {
    // spec: CUR-9 CUR-7
    // The other end of the destructive-count wording: `--prune` given on a
    // plan that contains no `unlist` at all must read exactly as it does
    // without the flag. A prompt that warned about uninstalls on a plan that
    // performs none teaches the user to ignore the warning.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let forget = env.mind(&["forget", "skill:review", "--yes"]);
    assert!(
        forget.success,
        "forget failed: {} {}",
        forget.stdout, forget.stderr
    );

    let r = env.mind_env(&["curate", "--prune"], &[("MIND_TTY", "1")], Some("y\n"));
    assert!(r.success, "curate failed: {} {}", r.stdout, r.stderr);
    assert!(
        r.stdout.contains("apply these 1 change(s) now?"),
        "a prune run with no unlist must use the plain wording: {}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("unlist"),
        "nothing in the run mentions unlisting: {}",
        r.stdout
    );
    assert!(
        env.claude_home.join("skills/review").exists(),
        "and answering yes still applies the install: {}",
        r.stdout
    );
}

/// A library repo melded directly (so it is registered and unowned) plus a
/// curator that lists it: the shape every `--adopt` case starts from.
fn unowned_lib_and_claiming_curator(env: &Env, curator_name: &str) -> (Repo, Repo) {
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );
    let curator = env.repo(curator_name);
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    (lib, curator)
}

#[test]
fn check_outranks_adopt_and_writes_nothing() {
    // spec: CUR-9 CUR-16
    // `--check` reports and applies nothing, and that promise cannot depend on
    // which other flags accompany it. `--adopt` used to be dispatched before
    // `check` was consulted anywhere, so `curate --check --adopt <id>` stamped
    // `curated_by` and saved the registry: a "safe to paste" run that wrote.
    let env = Env::new();
    let (_lib, _curator) = unowned_lib_and_claiming_curator(&env, "curator");
    let identity = env.ident("lib");

    let before = env.sources_json();
    assert!(
        !before.contains("curated_by"),
        "the fixture must start unowned: {before}"
    );
    let checked = env.mind(&["curate", "--check", "--adopt", &identity]);
    assert!(
        checked.success,
        "curate --check --adopt failed: {} {}",
        checked.stdout, checked.stderr
    );
    assert_eq!(
        before,
        env.sources_json(),
        "--check --adopt must leave sources.json byte-identical"
    );
    assert!(
        checked.stdout.contains("would adopt")
            && checked.stdout.contains(&identity)
            && checked.stdout.contains(&env.ident("curator")),
        "--check --adopt must report the claim it would apply: {}",
        checked.stdout
    );

    // spec: CUR-13
    // The `--json` shape of the same run: `pending`, the same outcome word the
    // plan path uses for "a change exists and nothing was applied".
    let json = env.mind(&["curate", "--check", "--adopt", &identity, "--json"]);
    assert!(
        json.success,
        "curate --check --adopt --json failed: {} {}",
        json.stdout, json.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&json.stdout).expect("json");
    assert_eq!(doc["schema"], 1);
    assert_eq!(doc["action"], "curate-adopt");
    assert_eq!(doc["outcome"], "pending");
    assert_eq!(doc["source"], identity.as_str());
    assert_eq!(doc["curator"], env.ident("curator").as_str());
    assert_eq!(
        before,
        env.sources_json(),
        "--check --adopt --json must not write either"
    );

    // Without --check the same command writes, so the assertions above are
    // testing the flag and not a fixture that could never adopt anyway.
    let applied = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        applied.success,
        "curate --adopt failed: {} {}",
        applied.stdout, applied.stderr
    );
    assert!(
        env.sources_json().contains("curated_by"),
        "the same identity must be adoptable without --check: {}",
        env.sources_json()
    );
}

#[test]
fn check_adopt_of_an_identity_no_curator_lists_still_fails() {
    // spec: CUR-9 CUR-16
    // `--check` suppresses the write, never the validation: a stale or
    // mistyped identity must fail as loudly under `--check` as without it,
    // otherwise a `--check` run reports a claim a real run would refuse.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let m = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let checked = env.mind(&["curate", "--check", "--adopt", &env.ident("lib")]);
    assert!(
        !checked.success,
        "an unclaimed identity must fail under --check too: {} {}",
        checked.stdout, checked.stderr
    );
}

#[test]
fn two_curators_claiming_one_identity_refuse_adopt_and_both_appear_in_the_plan() {
    // spec: CUR-20
    // Ownership used to go to the first curator in registry order that listed
    // the identity, silently, with the losing claim never mentioned. Both
    // claims are the user's to see: the plan reports one `adopt` line per
    // curator, and `--adopt` refuses rather than choosing for them.
    let env = Env::new();
    let (lib, _curator_a) = unowned_lib_and_claiming_curator(&env, "curator-a");
    let curator_b = env.repo("curator-b");
    curator_b.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);
    let m = env.mind(&["meld", &curator_b.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert!(
        plan.stdout.contains("adopt")
            && plan.stdout.contains(&env.ident("curator-a"))
            && plan.stdout.contains(&env.ident("curator-b")),
        "both claims must be reported, one line each: {}",
        plan.stdout
    );

    let identity = env.ident("lib");
    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        !adopted.success,
        "an ambiguous claim must not silently pick a curator: {} {}",
        adopted.stdout, adopted.stderr
    );
    let said = format!("{}{}", adopted.stdout, adopted.stderr);
    assert!(
        said.contains(&env.ident("curator-a")) && said.contains(&env.ident("curator-b")),
        "the refusal must name both claimants: {said}"
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "a refused adopt must write nothing: {}",
        env.sources_json()
    );

    // spec: CUR-9
    // `--check` suppresses the write, never the validation: an ambiguous claim
    // must fail under it too, or a `--check` run would report a resolution the
    // real run refuses.
    let checked = env.mind(&["curate", "--check", "--adopt", &identity]);
    assert!(
        !checked.success,
        "--check --adopt must refuse an ambiguous claim as well: {} {}",
        checked.stdout, checked.stderr
    );
    assert!(
        !checked.stdout.contains("would adopt"),
        "and must not report a resolution it does not have: {}",
        checked.stdout
    );

    // spec: CLI-181 -- and the same refusal is one JSON error envelope.
    let refused = adopt_json_refusal(&env, &identity);
    assert!(
        refused.contains(&env.ident("curator-a")) && refused.contains(&env.ident("curator-b")),
        "the json refusal must name both claimants too: {refused}"
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "and still write nothing: {}",
        env.sources_json()
    );
}

#[test]
fn a_claim_resolving_to_a_different_path_is_refused_naming_both() {
    // spec: CUR-20
    // A local source's identity is `local/<parent>/<dir>`, only the last two
    // path segments, so a curator can list a directory it controls that
    // derives the SAME identity as a source the consumer melded from
    // somewhere else. Matching on identity alone let that claim take
    // ownership; the claim's resolved path must match the registered one.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );

    // A decoy repo whose parent directory is named like the env base, so it
    // derives the same `local/<base>/lib` identity from a different path.
    let base_name = env.base.file_name().unwrap().to_string_lossy().into_owned();
    let decoy = env.repo(&format!("decoy/{base_name}/lib"));
    decoy.write_and_commit(
        "skills/evil/SKILL.md",
        "---\ndescription: Evil\n---\n# evil\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true }}",
        decoy.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let identity = env.ident("lib");
    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        !adopted.success,
        "a claim pointing at a different path must not adopt the registered source: {} {}",
        adopted.stdout, adopted.stderr
    );
    let said = format!("{}{}", adopted.stdout, adopted.stderr);
    assert!(
        said.contains(&decoy.spec()) && said.contains(&lib.spec()),
        "the refusal must name the claimed path and the registered one: {said}"
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "a refused adopt must write nothing: {}",
        env.sources_json()
    );

    // spec: CUR-9
    // The CUR-20 upstream check runs under `--check` too: the flag decides
    // whether the claim is WRITTEN, never whether it is validated.
    let checked = env.mind(&["curate", "--check", "--adopt", &identity]);
    assert!(
        !checked.success,
        "--check --adopt must refuse a mismatched claim as well: {} {}",
        checked.stdout, checked.stderr
    );
    assert!(
        !checked.stdout.contains("would adopt"),
        "and must not report a resolution it does not have: {}",
        checked.stdout
    );

    // spec: CLI-181 -- and the same refusal is one JSON error envelope.
    let refused = adopt_json_refusal(&env, &identity);
    assert!(
        refused.contains(&decoy.spec()) && refused.contains(&lib.spec()),
        "the json refusal must name both paths too: {refused}"
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "and still write nothing: {}",
        env.sources_json()
    );
}

#[test]
fn a_marketplace_only_claim_is_reported_in_the_plan_and_can_be_adopted() {
    // spec: CUR-16 CUR-20
    // `--adopt` resolves ownership from a marketplace catalog's membership
    // (MKT-7) exactly as it does from a `[discover].sources` entry, but only
    // the entry loop emitted an `adopt` line: a catalog could take ownership
    // of a source the reviewed plan never mentioned.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    // Melded under the same namespace the catalog entry's name supplies
    // (MKT-8), so the catalog resolves to this already-registered identity.
    let direct = env.mind(&["meld", &lib.spec(), "--namespace", "kit", "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );
    assert!(
        !env.sources_json().contains("curated_by"),
        "a direct meld records no curator: {}",
        env.sources_json()
    );

    let catalog = env.repo("catalog");
    catalog.write_and_commit(
        ".claude-plugin/marketplace.json",
        &format!(
            r#"{{"name":"Cat","plugins":[{{"name":"kit","source":{{"url":"{}"}}}}]}}"#,
            lib.spec()
        ),
    );
    let m = env.mind(&["meld", &catalog.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let identity = format!("{}@kit", env.ident("lib"));
    let plan = env.mind(&["curate", "--check"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    assert!(
        plan.stdout.contains("adopt") && plan.stdout.contains(&identity),
        "a marketplace claim on an unowned source must appear in the plan: {}",
        plan.stdout
    );

    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        adopted.success,
        "curate --adopt failed: {} {}",
        adopted.stdout, adopted.stderr
    );
    assert!(
        env.sources_json().contains("curated_by"),
        "the marketplace claim must be adoptable: {}",
        env.sources_json()
    );
}

/// The `curated_by` recorded for `identity`, read straight from `sources.json`
/// rather than by substring: several fixtures below have more than one source
/// registered, so "the file mentions curated_by somewhere" proves nothing about
/// which source was stamped.
fn curated_by(env: &Env, identity: &str) -> Option<String> {
    let doc: serde_json::Value = serde_json::from_str(&env.sources_json()).expect("sources.json");
    let source = doc["sources"]
        .as_array()
        .expect("sources array")
        .iter()
        .find(|s| s["name"] == identity)?;
    source["curated_by"].as_str().map(str::to_string)
}

/// Run `curate --adopt <identity> --json`, require it to refuse, and return the
/// CLI-181 error envelope's `message`.
fn adopt_json_refusal(env: &Env, identity: &str) -> String {
    let r = env.mind(&["curate", "--adopt", identity, "--json"]);
    assert!(
        !r.success,
        "adopt of {identity} must be refused: {} {}",
        r.stdout, r.stderr
    );
    let doc: serde_json::Value =
        serde_json::from_str(&r.stdout).expect("one JSON error envelope on stdout");
    assert_eq!(doc["schema"], 1, "{doc}");
    assert_eq!(
        doc["error"]["kind"], "not-an-adopt-candidate",
        "the refusal must carry the structured kind, not just prose: {doc}"
    );
    doc["error"]["message"]
        .as_str()
        .expect("error message")
        .to_string()
}

#[test]
fn a_curator_claiming_through_both_an_entry_and_its_catalog_reports_one_adopt_line() {
    // spec: CUR-20
    // Both mechanisms are claims, and `entry_claims` yields every one of them.
    // A curator that lists a repo in `[discover].sources` AND ships a
    // marketplace catalog naming it makes two claims on one identity: the plan
    // must report that once (the pair, not the identity, is what is deduped),
    // and `--adopt` must read it as one curator, not as the CUR-20 ambiguity.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    // Melded under the namespace the catalog entry's name supplies (MKT-8), so
    // both claims resolve to this one already-registered identity.
    let direct = env.mind(&["meld", &lib.spec(), "--namespace", "kit", "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );

    let curator = env.repo("curator");
    curator.write_and_commit(
        ".claude-plugin/marketplace.json",
        &format!(
            r#"{{"name":"Cat","plugins":[{{"name":"kit","source":{{"url":"{}"}}}}]}}"#,
            lib.spec()
        ),
    );
    // A bare `[discover].sources` list is not an authoritative inventory
    // (MKT-2/MKT-16), so the catalog is still read alongside it.
    curator.curate_list(&[format!(
        "{{ source = \"{}\", namespace = \"kit\" }}",
        lib.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let identity = format!("{}@kit", env.ident("lib"));
    let plan = env.mind(&["curate", "--check", "--json"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&plan.stdout).expect("json");
    let adopts: Vec<&serde_json::Value> = doc["changes"]
        .as_array()
        .expect("changes array")
        .iter()
        .filter(|c| c["kind"] == "adopt")
        .collect();
    assert_eq!(
        adopts.len(),
        1,
        "one curator claiming one identity through both mechanisms reports once: {doc}"
    );
    assert_eq!(adopts[0]["source"], identity.as_str(), "{doc}");
    assert_eq!(adopts[0]["curator"], env.ident("curator").as_str(), "{doc}");

    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        adopted.success,
        "two claims from ONE curator are not an ambiguity: {} {}",
        adopted.stdout, adopted.stderr
    );
    assert_eq!(
        curated_by(&env, &identity),
        Some(env.ident("curator")),
        "and the source ends owned by that curator: {}",
        env.sources_json()
    );
}

#[test]
fn one_curator_listing_two_paths_for_one_identity_is_a_mismatch_not_an_ambiguity() {
    // spec: CUR-20
    // Two entries in ONE curator resolving to the same identity by DIFFERENT
    // paths: the claimant set has one member, so the ambiguity rule does not
    // fire and the upstream check is what must catch it. A curator whose list
    // contains a decoy path alongside the real one must not be able to launder
    // the decoy into ownership just by also naming the real repo.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );

    let base_name = env.base.file_name().unwrap().to_string_lossy().into_owned();
    let decoy = env.repo(&format!("decoy/{base_name}/lib"));
    decoy.write_and_commit(
        "skills/evil/SKILL.md",
        "---\ndescription: Evil\n---\n# evil\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[
        format!("{{ source = \"{}\" }}", lib.spec()),
        format!("{{ source = \"{}\" }}", decoy.spec()),
    ]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let identity = env.ident("lib");
    let plan = env.mind(&["curate", "--check", "--json"]);
    assert!(plan.success, "curate failed: {}", plan.stderr);
    let doc: serde_json::Value = serde_json::from_str(&plan.stdout).expect("json");
    let adopts = doc["changes"]
        .as_array()
        .expect("changes")
        .iter()
        .filter(|c| c["kind"] == "adopt")
        .count();
    assert_eq!(
        adopts, 1,
        "the (curator, identity) pair is deduped however many entries make it: {doc}"
    );

    let refused = adopt_json_refusal(&env, &identity);
    assert!(
        refused.contains(&decoy.spec()) && refused.contains(&lib.spec()),
        "the refusal must name the claim that does not match and the registered \
         upstream: {refused}"
    );
    assert!(
        !refused.contains("curators claim it"),
        "one curator listing an identity twice is not the multi-curator \
         ambiguity, and must not be reported as one: {refused}"
    );
    assert_eq!(
        curated_by(&env, &identity),
        None,
        "a refused adopt writes nothing: {}",
        env.sources_json()
    );
}

#[test]
fn every_adopt_refusal_is_one_json_error_envelope_that_writes_nothing() {
    // spec: CUR-16 CLI-181 CLI-217
    // The refusal paths were only ever exercised in text mode. Under `--json`
    // each must be exactly one error envelope on stdout with the structured
    // `kind` a caller branches on, and must leave `sources.json` untouched.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let plain = env.repo("plain");
    plain.write_and_commit(
        "skills/solo/SKILL.md",
        "---\ndescription: Solo\n---\n# solo\n",
    );
    let p = env.mind(&["meld", &plain.spec(), "--register-only"]);
    assert!(p.success, "meld failed: {} {}", p.stdout, p.stderr);
    let before = env.sources_json();
    assert_eq!(
        curated_by(&env, &env.ident("lib")),
        Some(env.ident("curator")),
        "the fixture must start with one owned and one unowned source: {before}"
    );

    // No source carries that identity at all.
    let missing = adopt_json_refusal(&env, "example.com/no/such");
    assert!(
        missing.contains("no melded source") && missing.contains("example.com/no/such"),
        "a mistyped identity must say it is not registered: {missing}"
    );
    // Registered, but a curator already owns it.
    let owned = adopt_json_refusal(&env, &env.ident("lib"));
    assert!(
        owned.contains("already curated by") && owned.contains(&env.ident("curator")),
        "an owned source must name its owner: {owned}"
    );
    // Registered and unowned, but no curator lists it.
    let unclaimed = adopt_json_refusal(&env, &env.ident("plain"));
    assert!(
        unclaimed.contains("no registered curator"),
        "an unclaimed source must say so: {unclaimed}"
    );
    assert_eq!(
        before,
        env.sources_json(),
        "no refusal path may write to the registry"
    );
}

#[test]
fn a_curator_that_lists_only_itself_offers_nothing_to_adopt() {
    // spec: CUR-17 CUR-16
    // CUR-17 excludes a self-listing entry from the plan; the same exclusion
    // has to hold in `--adopt`'s own claim resolution, or a source could list
    // itself, be adopted as its own curator, and become permanently immune to
    // CUR-7 unlisting -- exactly the self-shield CUR-17 exists to close.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true }}",
        curator.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let identity = env.ident("curator");

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    assert!(
        !plan.stdout.contains("adopt"),
        "a self-listed entry must not be reported as an adopt candidate: {}",
        plan.stdout
    );

    let refused = adopt_json_refusal(&env, &identity);
    assert!(
        refused.contains("no registered curator"),
        "and --adopt must refuse it as unlisted, not adopt it to itself: {refused}"
    );
    assert_eq!(
        curated_by(&env, &identity),
        None,
        "nothing may be written: {}",
        env.sources_json()
    );
}

#[test]
fn adopt_applies_no_other_change_even_with_prune_and_yes() {
    // spec: CUR-16
    // `--adopt` is a narrow sub-mode that returns before a plan is built, so
    // the destructive flags that would otherwise ride along on the same
    // command line must do nothing: an unattended `curate --adopt X --prune
    // --yes` must not also uninstall a source the plan lists for CUR-7
    // unlisting, nor install the adopted source's items.
    let env = Env::new();
    let dropped = env.repo("dropped");
    dropped.write_and_commit(
        "skills/dropped/SKILL.md",
        "---\ndescription: Dropped\n---\n# dropped\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true }}",
        dropped.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/dropped").exists());

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let direct = env.mind(&["meld", &lib.spec(), "--register-only"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );
    // The curator now drops `dropped` (a pending unlist) and claims `lib`.
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);

    let r = env.mind(&["curate", "--adopt", &env.ident("lib"), "--prune", "--yes"]);
    assert!(
        r.success,
        "curate --adopt failed: {} {}",
        r.stdout, r.stderr
    );
    assert_eq!(
        curated_by(&env, &env.ident("lib")),
        Some(env.ident("curator")),
        "the claim is applied: {}",
        env.sources_json()
    );
    assert!(
        env.claude_home.join("skills/dropped").exists(),
        "--prune alongside --adopt must apply no unlist: {}",
        r.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains(&env.ident("dropped")),
        "nor drop the source: {}",
        sources.stdout
    );
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "--yes alongside --adopt must install nothing either: {}",
        r.stdout
    );
}

/// Rewrite `identity`'s recorded pin in `sources.json` to `Pin::Ref(value)`.
///
/// Some registry states cannot be produced by any command this binary offers
/// (a pin `git clone` never fetches, a value a newer rule now refuses), yet a
/// registry written by an older binary can hold them. Writing the state
/// directly is the only hermetic way to plan against it.
fn set_recorded_pin(env: &Env, identity: &str, value: &str) {
    let path = env.mind_home.join("sources.json");
    let mut doc: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).expect("sources.json"))
            .expect("sources.json parses");
    let source = doc["sources"]
        .as_array_mut()
        .expect("sources array")
        .iter_mut()
        .find(|s| s["name"] == identity)
        .expect("the fixture must have registered that identity");
    source["pin"] = serde_json::json!({ "kind": "ref", "value": value });
    std::fs::write(&path, serde_json::to_string_pretty(&doc).unwrap()).expect("write sources.json");
}

#[test]
fn a_curator_pin_outside_refs_heads_or_tags_is_skipped_not_applied() {
    // spec: CUR-21 CUR-15
    // `refs/pull/<n>/head` is a well-formed ref that `validate_ref_value`
    // accepts, points at content anyone can push to a repo the consumer
    // otherwise trusts, and `curate` re-applies a curator's pin on every run.
    let env = Env::new();
    let (lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());

    // Control: an ordinary branch directive DOES propose a repin, so the
    // refusal below is the rule at work rather than a fixture that would have
    // proposed nothing either way.
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, follow-branch = \"main\" }}",
        lib.spec()
    )]);
    let ok = env.mind(&["curate", "--check"]);
    assert!(ok.success, "curate failed: {} {}", ok.stdout, ok.stderr);
    assert!(
        ok.stdout.contains("repin"),
        "a branch directive must propose a repin: {}",
        ok.stdout
    );

    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, follow-branch = \"refs/pull/9999/head\" }}",
        lib.spec()
    )]);
    let r = env.mind(&["curate", "--check"]);
    assert!(
        r.success,
        "one refused pin must not fail the run: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        !r.stdout.contains("repin"),
        "a refs/pull pin must propose no repin: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("skipped") && r.stdout.contains(&env.ident("lib")),
        "the refused directive must be reported as skipped: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("warning:") && r.stderr.contains("refs/pull/9999/head"),
        "and warned about by name: {}",
        r.stderr
    );

    let doc: serde_json::Value =
        serde_json::from_str(&env.mind(&["curate", "--json", "--check"]).stdout).expect("json");
    assert_eq!(
        doc["skipped"][0]["reason"], "pin_ref_not_allowed",
        "the CUR-13 skipped slug must name the cause: {doc}"
    );
    assert!(
        doc["changes"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["kind"] != "repin"),
        "and no repin change is emitted: {doc}"
    );
}

#[test]
fn a_curator_pin_outside_refs_heads_or_tags_blocks_registering_a_new_entry() {
    // spec: CUR-21 CUR-15
    // The repin-path test above covers an ALREADY-registered source. This
    // covers the other branch of `build_plan`: an entry no one has registered
    // yet. Left unchecked there, `curator_pin_allowed` would only ever run on
    // a repin, so a curator's `refs/pull/<n>/head` on a brand-new entry would
    // reach `meld_curated_entry` unexamined -- happening to fail only because
    // `git clone --branch` cannot resolve it, not because policy refused it.
    let env = Env::new();
    let curator = env.repo("curator");
    curator.write_and_commit("mind.toml", "[source]\ndescription = \"curator\"\n");
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review the diff\n---\n# review\n",
    );
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, follow-branch = \"refs/pull/9999/head\" }}",
        lib.spec()
    )]);

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.success,
        "one refused pin must not fail the run: {} {}",
        plan.stdout, plan.stderr
    );
    assert!(
        !plan.stdout.contains("register"),
        "a refs/pull pin must propose no register: {}",
        plan.stdout
    );
    assert!(
        plan.stdout.contains("skipped") && plan.stdout.contains(&env.ident("lib")),
        "the refused entry must be reported as skipped: {}",
        plan.stdout
    );
    assert!(
        plan.stderr.contains("warning:") && plan.stderr.contains("refs/pull/9999/head"),
        "and warned about by name: {}",
        plan.stderr
    );

    let doc: serde_json::Value =
        serde_json::from_str(&env.mind(&["curate", "--json", "--check"]).stdout).expect("json");
    assert_eq!(
        doc["skipped"][0]["reason"], "pin_ref_not_allowed",
        "the CUR-13 skipped slug must name the cause: {doc}"
    );
    assert!(
        doc["changes"]
            .as_array()
            .unwrap()
            .iter()
            .all(|c| c["kind"] != "register"),
        "and no register change is emitted: {doc}"
    );

    // Even with `--yes`, the entry must never be cloned/installed: a refused
    // register-path pin is not a "register with an unchecked pin", it is no
    // change at all for that entry.
    let applied = env.mind(&["curate", "--yes"]);
    assert!(applied.success, "curate --yes failed: {}", applied.stderr);
    assert!(
        !env.sources_json().contains(&env.ident("lib")),
        "the source must never be registered: {}",
        env.sources_json()
    );
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "and its items must never be installed: {}",
        applied.stdout
    );
}

#[test]
fn a_curator_pin_tag_or_pin_ref_outside_refs_heads_or_tags_is_skipped_too() {
    // spec: CUR-21 CUR-15
    // CUR-21 is a rule about the ref VALUE, so it must hold whichever
    // directive carries it. The stage's own integration test covered
    // `follow-branch` only; a curator that could smuggle
    // `refs/pull/<n>/head` in through `pin-ref` would have exactly the
    // standing substitution channel the rule exists to close.
    let env = Env::new();
    let (lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);

    // Control: `pin-tag` DOES reach the repin path with an ordinary value, so
    // the refusals below are the rule at work and not an inert directive.
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, pin-tag = \"v1.0\" }}",
        lib.spec()
    )]);
    let ok = env.mind(&["curate", "--check"]);
    assert!(ok.success, "curate failed: {} {}", ok.stdout, ok.stderr);
    assert!(
        ok.stdout.contains("repin"),
        "a plain tag directive must propose a repin: {}",
        ok.stdout
    );

    for (directive, value) in [
        ("pin-ref", "refs/pull/9999/head"),
        ("pin-tag", "refs/remotes/origin/main"),
    ] {
        curator.curate_list(&[format!(
            "{{ source = \"{}\", install = true, {directive} = \"{value}\" }}",
            lib.spec()
        )]);
        let r = env.mind(&["curate", "--check", "--json"]);
        assert!(
            r.success,
            "one refused pin must not fail the run ({directive}): {} {}",
            r.stdout, r.stderr
        );
        let doc: serde_json::Value = serde_json::from_str(&r.stdout).expect("json");
        assert!(
            doc["changes"]
                .as_array()
                .expect("changes")
                .iter()
                .all(|c| c["kind"] != "repin"),
            "{directive} = {value} must propose no repin: {doc}"
        );
        assert_eq!(
            doc["skipped"][0]["reason"], "pin_ref_not_allowed",
            "and be reported as skipped ({directive}): {doc}"
        );
    }
}

#[test]
fn a_refused_curator_pin_that_already_matches_the_recorded_pin_proposes_nothing() {
    // spec: CUR-21 CUR-5
    // CUR-21 is reached only through a `repin` CHANGE, and a directive equal
    // to the recorded pin is not a change: `curate` proposes nothing and
    // reports nothing, rather than warning on every run about a pin it is not
    // about to apply. The rule is about what `curate` would newly point a
    // clone at, not an audit of what the clone is already on.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    git(&lib.path, &["tag", "v1"]);
    let curator = env.repo("curator");
    // Pinned, so the source is CLONED rather than linked (`is_linked` is
    // "local AND unpinned"): the rewritten pin below must leave a readable
    // clone behind, or the run would report an unreadable source instead of
    // planning against it.
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, pin-tag = \"v1\" }}",
        lib.spec()
    )]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());

    // The recorded pin is already the ref the curator declares. A clone never
    // fetches `refs/pull/*`, so this state is only reachable from a registry
    // written earlier (a consumer's own pin, or a binary older than CUR-21);
    // it is written directly here rather than through a meld that cannot
    // produce it.
    set_recorded_pin(&env, &env.ident("lib"), "refs/pull/1/head");
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, pin-ref = \"refs/pull/1/head\" }}",
        lib.spec()
    )]);

    let r = env.mind(&["curate", "--check", "--no-sync"]);
    assert!(r.success, "curate failed: {} {}", r.stdout, r.stderr);
    assert!(
        !r.stdout.contains("repin"),
        "an unchanged pin is no change: {}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("skipped") && !r.stderr.contains("warning:"),
        "and nothing is reported about it: {} {}",
        r.stdout,
        r.stderr
    );

    // Control: the moment the curator declares a DIFFERENT out-of-namespace
    // ref, that IS a change, and CUR-21 refuses it.
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true, pin-ref = \"refs/pull/2/head\" }}",
        lib.spec()
    )]);
    let after = env.mind(&["curate", "--check", "--no-sync", "--json"]);
    assert!(
        after.success,
        "curate failed: {} {}",
        after.stdout, after.stderr
    );
    let doc: serde_json::Value = serde_json::from_str(&after.stdout).expect("json");
    assert_eq!(
        doc["skipped"][0]["reason"], "pin_ref_not_allowed",
        "a changed out-of-namespace pin is refused and reported: {doc}"
    );
}

#[test]
fn a_curated_item_link_source_is_refreshed_by_curate() {
    // spec: CUR-19 CUR-6 LNK-8
    // An item-link instance curates nothing (LNK-8), but it can perfectly well
    // BE curated. The CUR-19 scope excluded it from the refresh entirely, so
    // its clone (a link is pinned to its ref, hence cloned, never a linked
    // working tree) was never fetched by `curate`: the CUR-6 drift check read
    // permanently stale content and only a separate bare `mind sync` helped.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let link = format!(
        "file://{}/tree/main/skills/review",
        lib.path.to_string_lossy()
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!("{{ source = \"{link}\", install = true }}")]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(
        env.claude_home.join("skills/review").exists(),
        "the curated link's skill installs: {}",
        m.stdout
    );
    let identity = format!("{}#skills/review", env.ident("lib"));
    assert!(
        env.sources_json().contains(&identity),
        "the entry must register as a link instance: {}",
        env.sources_json()
    );

    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\nupdated\n",
    );

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    assert!(
        plan.stdout.contains("upgrade") && plan.stdout.contains(&identity),
        "curate must refresh the curated link's clone and see the drift, with \
         no separate `mind sync`: {}",
        plan.stdout
    );

    let applied = env.mind(&["curate", "--yes"]);
    assert!(
        applied.success,
        "curate --yes failed: {} {}",
        applied.stdout, applied.stderr
    );
    let installed =
        std::fs::read_to_string(env.claude_home.join("skills/review/SKILL.md")).expect("installed");
    assert!(
        installed.contains("updated"),
        "and land the new content: {installed}"
    );
}

#[test]
fn an_item_link_a_curator_lists_but_does_not_own_is_left_out_of_the_refresh() {
    // spec: CUR-19 CUR-16 LNK-8
    // The CUR-19 scope is "sources a curator OWNS, plus sources that carry a
    // curator file". An item link is excluded from the second half (LNK-8: it
    // exports one item and curates nothing), so a link a curator merely LISTS
    // is out of scope until `--adopt` stamps ownership. That is deliberate,
    // and it is the other side of the fix that put OWNED links back in scope,
    // so it gets a test of its own rather than an assumption.
    let env = Env::new();
    let lib = env.repo("lib");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let link = format!(
        "file://{}/tree/main/skills/review",
        lib.path.to_string_lossy()
    );
    let direct = env.mind(&["meld", &link, "--yes"]);
    assert!(
        direct.success,
        "meld failed: {} {}",
        direct.stdout, direct.stderr
    );
    assert!(env.claude_home.join("skills/review").exists());
    let identity = format!("{}#skills/review", env.ident("lib"));
    assert_eq!(
        curated_by(&env, &identity),
        None,
        "a direct meld leaves the link unowned: {}",
        env.sources_json()
    );

    let curator = env.repo("curator");
    curator.curate_list(&[format!("{{ source = \"{link}\", install = true }}")]);
    let m = env.mind(&["meld", &curator.spec(), "--register-only"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let before = env.sources_json();

    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\nupdated\n",
    );

    let plan = env.mind(&["curate", "--check"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    assert_eq!(
        before,
        env.sources_json(),
        "a listed-but-unowned link is not refreshed by curate"
    );
    assert!(
        plan.stdout.contains("adopt") && plan.stdout.contains(&identity),
        "it is reported as an adopt candidate instead: {}",
        plan.stdout
    );
    assert!(
        !plan.stdout.contains("upgrade"),
        "and proposes nothing against a source no curator owns: {}",
        plan.stdout
    );

    // Adopting it is what brings it into scope: the very next run refreshes
    // the clone and sees the drift.
    let adopted = env.mind(&["curate", "--adopt", &identity]);
    assert!(
        adopted.success,
        "curate --adopt failed: {} {}",
        adopted.stdout, adopted.stderr
    );
    let owned = env.mind(&["curate", "--check"]);
    assert!(
        owned.success,
        "curate failed: {} {}",
        owned.stdout, owned.stderr
    );
    assert!(
        owned.stdout.contains("upgrade") && owned.stdout.contains(&identity),
        "once owned, the same link IS refreshed and its drift seen: {}",
        owned.stdout
    );
}

#[test]
fn an_unparseable_entry_is_reported_and_never_prunes_its_source() {
    // spec: CUR-15 CUR-7
    // A `source` value edited into something unparseable was dropped in
    // silence, taking the identity it contributed to the "still listed" set
    // with it. The source it named then looked unlisted, and `--prune`
    // uninstalled it: a failure to READ a curator's list turning into the
    // strongest action `curate` can take.
    let env = Env::new();
    let (_lib, curator) = lib_and_curator(&env, ", install = true");
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/review").exists());
    assert!(
        env.sources_json().contains("curated_by"),
        "the source must be curated for CUR-7 to be able to unlist it: {}",
        env.sources_json()
    );

    // The entry is edited into a malformed spec (no owner/repo shape).
    curator.curate_list(&["{ source = \"not a repo spec\", install = true }".to_string()]);

    let r = env.mind(&["curate", "--check", "--prune"]);
    assert!(
        r.success,
        "one unparseable entry must not fail the run: {} {}",
        r.stdout, r.stderr
    );
    assert!(
        !r.stdout.contains("unlist"),
        "an entry that could not be read must not read as a dropped entry: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("skipped") && r.stdout.contains("not a repo spec"),
        "the unparseable entry must be reported: {}",
        r.stdout
    );
    assert!(
        r.stderr.contains("warning:"),
        "and warned about: {}",
        r.stderr
    );

    let doc: serde_json::Value =
        serde_json::from_str(&env.mind(&["curate", "--json", "--check", "--prune"]).stdout)
            .expect("json");
    assert_eq!(
        doc["skipped"][0]["reason"], "entry_spec_unparseable",
        "the CUR-13 skipped slug must name the cause: {doc}"
    );

    // And the apply path agrees with the plan: nothing is pruned.
    let pruned = env.mind(&["curate", "--yes", "--prune"]);
    assert!(
        pruned.success,
        "curate --prune failed: {} {}",
        pruned.stdout, pruned.stderr
    );
    assert!(
        env.claude_home.join("skills/review").exists(),
        "--prune must not uninstall the source an unreadable entry named: {}",
        pruned.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains(&env.ident("lib")),
        "nor drop it: {}",
        sources.stdout
    );
}

#[test]
fn one_unparseable_entry_shields_the_curators_other_dropped_entries_too() {
    // spec: CUR-15 CUR-7
    // The blast radius of the CUR-15 tolerance, pinned deliberately:
    // "incomplete" is per CURATOR, not per entry, so ONE entry that stopped
    // parsing suppresses the unlist pass for every source that curator owns,
    // including one it really did drop. That is the intended trade -- a list
    // read only in part is not evidence that anything was dropped from it, and
    // the alternative acts on that partial read with the most destructive
    // change `curate` has. The consumer still sees the drop on the next run,
    // once the curator's list parses again.
    let env = Env::new();
    let a = env.repo("lib-a");
    a.write_and_commit("skills/a/SKILL.md", "---\ndescription: A\n---\n# a\n");
    let b = env.repo("lib-b");
    b.write_and_commit("skills/b/SKILL.md", "---\ndescription: B\n---\n# b\n");
    let curator = env.repo("curator");
    curator.curate_list(&[
        format!("{{ source = \"{}\", install = true }}", a.spec()),
        format!("{{ source = \"{}\", install = true }}", b.spec()),
    ]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/a").exists());
    assert!(env.claude_home.join("skills/b").exists());

    // lib-a's entry stops parsing; lib-b's is dropped outright.
    curator.curate_list(&["{ source = \"not a repo spec\", install = true }".to_string()]);

    let plan = env.mind(&["curate", "--check", "--prune"]);
    assert!(
        plan.success,
        "curate failed: {} {}",
        plan.stdout, plan.stderr
    );
    assert!(
        !plan.stdout.contains("unlist"),
        "neither the unreadable entry's source nor the genuinely dropped one \
         may be proposed for unlisting: {}",
        plan.stdout
    );

    let pruned = env.mind(&["curate", "--yes", "--prune"]);
    assert!(
        pruned.success,
        "curate --prune failed: {} {}",
        pruned.stdout, pruned.stderr
    );
    assert!(
        env.claude_home.join("skills/a").exists() && env.claude_home.join("skills/b").exists(),
        "and --prune uninstalls neither: {}",
        pruned.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        sources.stdout.contains(&env.ident("lib-a"))
            && sources.stdout.contains(&env.ident("lib-b")),
        "nor drops either source: {}",
        sources.stdout
    );

    // Once the list parses again, the genuine drop is acted on: the shield is
    // for the run that could not read the list, not a permanent immunity.
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", a.spec())]);
    let again = env.mind(&["curate", "--yes", "--prune"]);
    assert!(
        again.success,
        "curate --prune failed: {} {}",
        again.stdout, again.stderr
    );
    assert!(
        env.claude_home.join("skills/a").exists(),
        "the still-listed source stays: {}",
        again.stdout
    );
    assert!(
        !env.claude_home.join("skills/b").exists(),
        "and the dropped one is finally pruned: {}",
        again.stdout
    );
}

#[test]
fn an_identity_with_glob_metacharacters_is_pruned_literally() {
    // spec: CUR-7 CLI-28
    // `unmeld`'s selector is glob-aware, so the raw identity `local/b/lib[x]`
    // was compiled as a PATTERN: it matched no source (a character class, not
    // the literal name), and `curate --prune --yes` failed with
    // `no melded source matches ...` instead of pruning. A repo directory may
    // legitimately carry `[`, and a link identity embeds the whole repo path
    // (LNK-4), so this is reachable from the source side.
    let env = Env::new();
    let lib = env.repo("lib[x]");
    lib.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", lib.spec())]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let identity = env.ident("lib[x]");
    assert!(
        env.sources_json().contains(&identity),
        "the fixture must register under a glob-metacharacter identity: {}",
        env.sources_json()
    );
    assert!(env.claude_home.join("skills/review").exists());

    curator.curate_list(&[]);
    let pruned = env.mind(&["curate", "--yes", "--prune"]);
    assert!(
        pruned.success,
        "prune must not read the identity as a glob pattern: {} {}",
        pruned.stdout, pruned.stderr
    );
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "the items must be uninstalled: {}",
        pruned.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        !sources.stdout.contains(&identity),
        "and the source dropped: {}",
        sources.stdout
    );
}

#[test]
fn a_star_in_an_identity_prunes_only_that_source() {
    // spec: CUR-7 CLI-28
    // The `[x]` case above proves an escaped identity still matches ITSELF.
    // This one proves the escape targets correctly: `*` is the metacharacter
    // that widens a pattern, so a sibling source the UNESCAPED identity would
    // also have matched must survive the prune. `unmeld` removes every source
    // a glob selector matches (CLI-28) and `curate` passes `yes = true`, so an
    // unescaped `local/<base>/lib*` would silently uninstall `libZ` as well --
    // a source no curator ever dropped.
    let env = Env::new();
    let star = env.repo("lib*");
    star.write_and_commit(
        "skills/star/SKILL.md",
        "---\ndescription: Star\n---\n# star\n",
    );
    let sibling = env.repo("libZ");
    sibling.write_and_commit("skills/zed/SKILL.md", "---\ndescription: Zed\n---\n# zed\n");
    let curator = env.repo("curator");
    curator.curate_list(&[
        format!("{{ source = \"{}\", install = true }}", star.spec()),
        format!("{{ source = \"{}\", install = true }}", sibling.spec()),
    ]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    assert!(env.claude_home.join("skills/star").exists());
    assert!(env.claude_home.join("skills/zed").exists());

    // Only the `*` entry is dropped.
    curator.curate_list(&[format!(
        "{{ source = \"{}\", install = true }}",
        sibling.spec()
    )]);
    let pruned = env.mind(&["curate", "--yes", "--prune"]);
    assert!(
        pruned.success,
        "curate --prune failed: {} {}",
        pruned.stdout, pruned.stderr
    );
    assert!(
        !env.claude_home.join("skills/star").exists(),
        "the unlisted source's items must go: {}",
        pruned.stdout
    );
    assert!(
        env.claude_home.join("skills/zed").exists(),
        "but a sibling the unescaped pattern would have matched must not: {}",
        pruned.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        !sources.stdout.contains(&env.ident("lib*")),
        "the unlisted source is dropped: {}",
        sources.stdout
    );
    assert!(
        sources.stdout.contains(&env.ident("libZ")),
        "and the sibling stays registered: {}",
        sources.stdout
    );
}

#[test]
fn an_unbalanced_bracket_in_an_identity_still_prunes() {
    // spec: CUR-7 CLI-28
    // `lib[x` is not a valid glob at all: compiled as a pattern it is
    // `InvalidPattern`, so an unescaped selector makes `curate --prune` fail
    // outright rather than merely mis-target. A balanced `[x]` compiles (it is
    // a character class), so it exercises a different half of the escape.
    let env = Env::new();
    let odd = env.repo("lib[x");
    odd.write_and_commit(
        "skills/review/SKILL.md",
        "---\ndescription: Review\n---\n# review\n",
    );
    let curator = env.repo("curator");
    curator.curate_list(&[format!("{{ source = \"{}\", install = true }}", odd.spec())]);
    let m = env.mind(&["meld", &curator.spec(), "--yes"]);
    assert!(m.success, "meld failed: {} {}", m.stdout, m.stderr);
    let identity = env.ident("lib[x");
    assert!(
        env.sources_json().contains(&identity),
        "the fixture must register under an unbalanced-bracket identity: {}",
        env.sources_json()
    );
    assert!(env.claude_home.join("skills/review").exists());

    curator.curate_list(&[]);
    let pruned = env.mind(&["curate", "--yes", "--prune"]);
    assert!(
        pruned.success,
        "an identity that is not a valid glob must still prune: {} {}",
        pruned.stdout, pruned.stderr
    );
    assert!(
        !env.claude_home.join("skills/review").exists(),
        "the items must be uninstalled: {}",
        pruned.stdout
    );
    let sources = env.mind(&["recall", "--sources"]);
    assert!(
        !sources.stdout.contains(&identity),
        "and the source dropped: {}",
        sources.stdout
    );
}