mind-cli 0.12.0

A manager for agent tooling (skills, agents, rules, tools) that melds arbitrary git repos and links items into your agent directories.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
//! Command implementations, one public function per CLI verb.

use std::collections::HashSet;
use std::io::Write;

use serde::Serialize;

use crate::catalog::{self, CatalogItem};
use crate::config::Config;
use crate::error::{ItemKind, MindError, Result};
use crate::git;
use crate::hash::hash_path;
use crate::install;
use crate::manifest::Manifest;
use crate::mindfile::AuthFailureAction;
use crate::mindfile::HookEvent;
use crate::mindfile::MindToml;
use crate::paths::Paths;
use crate::plugin_manifest;
use crate::policy::Policy;
use crate::resolve::{
    is_glob, parse_item_ref, resolve, select, select_by_bare_refs, select_installed,
    source_matches, source_matches_glob,
};
use crate::source::{ManifestOrigin, Pin, Registry, parse_spec};

/// `mind meld <repo> [--as <prefix>] [--root <dir>] [--follow-branch|--pin-tag|--pin-ref]`
/// — register and clone a source.
///
/// If the source's `mind.toml` lists nested `[discover].sources`, each is melded
/// too (recursively), so a repo can act as a curated super-source. Nested
/// sources are skipped if already registered, and cycles are guarded by URL.
///
/// Returns a `MeldSummary` with the data needed for the caller to emit a combined
/// JSON object (CLI-156): the dispatcher folds the post-meld install outcome into
/// ONE JSON result rather than letting each step emit separately.
#[allow(clippy::too_many_arguments)]
pub fn meld(
    paths: &Paths,
    repo: &str,
    alias: Option<String>,
    roots: Vec<String>,
    flat_skills: bool,
    follow_branch: Option<String>,
    pin_tag: Option<String>,
    pin_ref: Option<String>,
    install_hook: Option<String>,
    dangerously_skip_install_hook_check: bool,
) -> Result<MeldSummary> {
    // Resolve the consumer-supplied pin flags into a single Pin. The flags are
    // independent at the clap layer, so more than one surfaces here as the
    // structured `ConflictingPin` error (CLI-17) rather than a clap usage string.
    let consumer_pin = resolve_pin_flags(follow_branch, pin_tag, pin_ref)?;

    paths.ensure_layout()?;
    // POL-3: the managed policy is authoritative over user intent. Load it once
    // (Err = invalid policy, fail closed via `?`; None = unmanaged, inert).
    let policy = Policy::load()?;
    // CLI-19: prefer SSH for remotes when the user's config asks for it.
    let prefer_ssh = Config::load(paths)?.ssh;
    let mut registry = Registry::load(paths)?;
    let mut visited = HashSet::new();
    let source_name = parse_spec(repo)
        .map(|s| s.name)
        .unwrap_or_else(|_| repo.to_string());
    let mut meld_skipped: Vec<SkippedEntry> = Vec::new();
    let added = meld_recursive(
        paths,
        &mut registry,
        repo,
        alias,
        roots,
        flat_skills,
        consumer_pin,
        true,
        &mut visited,
        policy.as_ref(),
        install_hook,
        dangerously_skip_install_hook_check,
        prefer_ssh,
        false, // yes: top-level meld does not yet thread --yes (non-TTY always fires NS-45)
        None,  // a top-level meld has no curator-supplied configuration
        &mut meld_skipped,
    )?;
    registry.save(paths)?;
    // JSON emission is deferred to the dispatcher (main.rs) so the install
    // outcome can be folded into ONE object (CLI-156). Human output is still
    // printed here because it is unrelated to the install step.
    let out = crate::render::ctx();
    if !out.json && added > 1 {
        println!("melded {added} source(s)");
    }
    Ok(MeldSummary {
        source_name,
        added,
        skipped: meld_skipped,
    })
}

/// DSC-56: after melding a source that curates other sources (`[discover].sources`),
/// point the user at `mind probe` to browse what is now available. No-op for a
/// source with no nested sources, and silent under `--json`.
pub fn maybe_probe_hint(paths: &Paths, repo: &str) -> Result<()> {
    let out = crate::render::ctx();
    if out.json {
        return Ok(());
    }
    let Ok(name) = parse_spec(repo).map(|s| s.name) else {
        return Ok(());
    };
    let registry = Registry::load(paths)?;
    let Some(source) = registry.find(&name) else {
        return Ok(());
    };
    let clone_dir = source.clone_dir(paths);
    let curates = MindToml::load(&clone_dir)?
        .and_then(|m| m.discover)
        .is_some_and(|d| !d.sources.is_empty());
    // MKT-7: a marketplace source is also a curated super-source; fire the
    // probe hint so the user knows to browse what became available.
    let has_marketplace = plugin_manifest::find_marketplace_manifest(&clone_dir).is_some();
    if curates || has_marketplace {
        println!(
            "note: this source curates other sources; run `mind probe` to browse and search what is available"
        );
    }
    Ok(())
}

/// Parse the three optional pin CLI flags into a single `Option<Pin>`.
/// More than one set flag is a `ConflictingPin` error (CLI-17). The flags are
/// kept independent at the clap layer so this structured error is what the user
/// sees, rather than a clap usage string.
///
/// Each supplied value is validated with [`crate::git::validate_ref_value`] so
/// a leading-dash value like `--pin-tag=-x` is rejected with `InvalidRef`
/// before it can reach any git subprocess (DSC-66).
fn resolve_pin_flags(
    follow_branch: Option<String>,
    pin_tag: Option<String>,
    pin_ref: Option<String>,
) -> Result<Option<Pin>> {
    match (follow_branch, pin_tag, pin_ref) {
        (None, None, None) => Ok(None),
        (Some(b), None, None) => {
            crate::git::validate_ref_value(&b)?;
            Ok(Some(Pin::FollowBranch(b)))
        }
        (None, Some(t), None) => {
            crate::git::validate_ref_value(&t)?;
            Ok(Some(Pin::Tag(t)))
        }
        (None, None, Some(r)) => {
            crate::git::validate_ref_value(&r)?;
            Ok(Some(Pin::Ref(r)))
        }
        (b, t, r) => {
            // More than one is set; name the first two for the error.
            let mut names = Vec::new();
            if b.is_some() {
                names.push("--follow-branch");
            }
            if t.is_some() {
                names.push("--pin-tag");
            }
            if r.is_some() {
                names.push("--pin-ref");
            }
            Err(MindError::ConflictingPin {
                first: names[0].to_string(),
                second: names[1].to_string(),
            })
        }
    }
}

/// A short human description of a `Pin` for the hook disclosure (HOOK-20).
/// Shared by `meld_recursive` and `upgrade` so both render the pin the same way.
fn pin_description(pin: &Pin) -> String {
    match pin {
        Pin::DefaultBranch => "default branch".to_string(),
        Pin::FollowBranch(b) => format!("branch {b}"),
        Pin::Tag(t) => format!("tag {t}"),
        Pin::Ref(r) => format!("ref {r}"),
    }
}

/// Whether `upgrade` should re-offer a source's install hooks (HOOK-11, HOOK-55):
/// any recorded install hook whose `ran_at` differs from the source's current
/// commit (never ran, or the source advanced past the run commit).
fn hook_rerun_warranted(source: &crate::source::Source) -> bool {
    !source
        .pending_install_hooks(source.commit.as_deref())
        .is_empty()
}

/// Whether a recorded install hook has already run at `current` (a real commit).
fn hook_ran_at(source: &crate::source::Source, command: &str, current: Option<&str>) -> bool {
    current.is_some()
        && source
            .install_hooks
            .iter()
            .any(|r| r.command == command && r.ran_at.as_deref() == current)
}

/// Record (upsert) an install hook's run state on the source.
fn record_install_hook(source: &mut crate::source::Source, command: &str, ran_at: Option<String>) {
    if let Some(r) = source
        .install_hooks
        .iter_mut()
        .find(|r| r.command == command)
    {
        r.ran_at = ran_at;
    } else {
        source.install_hooks.push(crate::source::RecordedHook {
            command: command.to_string(),
            ran_at,
        });
    }
}

/// What the caller should do with the source after a hook batch.
enum HookOutcome {
    Proceed,
    Abort,
}

/// Run a source's install hooks (HOOK-50..60). Offers each install hook unless it
/// already ran at the source's current commit (offers all when `force_rerun`).
/// Prompts per the optional (run/skip) vs required (run/skip/abort) model, runs
/// chosen hooks in `clone_dir` printing a running indication (HOOK-60), and upserts
/// each into `source.install_hooks`. A required hook's Abort returns `Abort`; any
/// hook's non-zero exit propagates as `Err` (HOOK-53), leaving cleanup to the
/// caller (meld removes the clone; re-meld leaves the source). `install_override`
/// is the consumer `--install-hook` command (meld only).
#[allow(clippy::too_many_arguments)]
fn run_install_hooks(
    source: &mut crate::source::Source,
    clone_dir: &std::path::Path,
    mindfile: &Option<MindToml>,
    toml_path: &std::path::Path,
    install_override: Option<&str>,
    dangerously_skip: bool,
    force_rerun: bool,
    extra_hooks: Vec<crate::mindfile::ResolvedHook>,
) -> Result<HookOutcome> {
    let mut resolved = mindfile
        .as_ref()
        .map(|m| m.resolved_hooks(toml_path))
        .transpose()?
        .unwrap_or_default();
    // DSC-61: curator-supplied hooks (when applied) run after the source's own,
    // through the exact same override/disclosure/decide/run path below.
    resolved.extend(extra_hooks);
    let (hooks, replaced) = crate::hook::apply_install_override(resolved, install_override);

    let pin_desc = pin_description(&source.pin);
    let commit = source.commit.clone().unwrap_or_default();
    let current = source.commit.clone();
    let clone_path = clone_dir.display().to_string();
    let name = source.name.clone();

    for h in hooks.iter().filter(|h| h.event == HookEvent::Install) {
        // HOOK-60: by default re-offer only hooks not yet run at this commit;
        // `--force` (force_rerun) re-offers every install hook.
        if !force_rerun && hook_ran_at(source, &h.run, current.as_deref()) {
            continue;
        }

        // HOOK-56: show the loud override note on the hook the override produced.
        let declared_override: Option<String> = replaced.as_ref().and_then(|cmds| {
            if install_override.map(str::trim) == Some(h.run.as_str()) {
                Some(cmds.join("; "))
            } else {
                None
            }
        });
        let disclosure = crate::hook::hook_disclosure_text(
            h.label(),
            h.optional,
            &name,
            &pin_desc,
            &commit,
            &clone_path,
            &h.run,
            declared_override.as_deref(),
        );

        match crate::hook::decide(&disclosure, h.optional, dangerously_skip)? {
            crate::hook::HookAct::Run => {
                // HOOK-60: indicate the running hook.
                println!("running install hook '{}' for {}", h.label(), name);
                // HOOK-53: a non-zero exit (optional or required) is a hard stop.
                crate::hook::run_hook(&h.run, clone_dir, &name, h.label())?;
                record_install_hook(source, &h.run, current.clone());
            }
            crate::hook::HookAct::Skip => {
                println!(
                    "note: skipped install hook '{}' for {}; its items may not work until it runs",
                    h.label(),
                    name
                );
                record_install_hook(source, &h.run, None);
            }
            crate::hook::HookAct::Abort => return Ok(HookOutcome::Abort),
        }
    }
    Ok(HookOutcome::Proceed)
}

/// Curator-supplied configuration for a nested source, lifted from a parent
/// super-source's `[discover].sources` entry (DSC-59). Resolved by the parent
/// before recursing; the pin is always applied (DSC-65, authoritative); roots
/// and hooks are gated (DSC-60) and applied only when the nested source has no
/// `mind.toml` of its own.
struct CuratedConfig {
    /// The curator pin directive (follow-branch, pin-tag, or pin-ref), if set.
    /// Authoritative: applied whether or not the nested source has a mind.toml
    /// (DSC-65). NOT included in the DSC-60 gating/warning.
    pin: Option<Pin>,
    /// The curator `roots`, if set (an explicit empty list is preserved).
    /// Gated by DSC-60: only applied when the nested source has no mind.toml.
    roots: Option<Vec<String>>,
    /// The curator `flat-skills` (DSC-77). Gated by DSC-60: only applied when the
    /// nested source has no mind.toml of its own.
    flat_skills: bool,
    /// The curator `[[discover.sources.hooks]]`, resolved in declaration order.
    /// Gated by DSC-60: only applied when the nested source has no mind.toml.
    hooks: Vec<crate::mindfile::ResolvedHook>,
}

impl CuratedConfig {
    /// Whether any DSC-60-GATED values (roots or hooks) are present, so the
    /// "ignored" warning is warranted when the nested source has its own
    /// `mind.toml`. The pin is NOT gated (DSC-65) and does NOT participate.
    fn has_gated_values(&self) -> bool {
        self.roots.is_some() || self.flat_skills || !self.hooks.is_empty()
    }
}

/// Meld one source and then its nested sources. Returns how many sources were
/// newly added to the registry. `top_level` distinguishes the user's own meld
/// (errors on a duplicate) from a curated nested meld (skips a duplicate).
///
/// `consumer_pin` is the caller-supplied pin (CLI flags or None for a nested
/// source that inherits no pin override).
/// `roots` is the consumer `--root` override (empty => no override).
///
/// `curated` carries the curator-supplied configuration from a parent
/// super-source's `[discover].sources` entry (DSC-59): a follow-branch pin,
/// scan roots, and lifecycle hooks. These apply only when the nested source
/// ships no `mind.toml` of its own (DSC-60); when it does, they are ignored with
/// a warning. `None` for a top-level meld or a nested source with no curator
/// configuration.
/// `yes` mirrors the CLI `--yes` flag (NS-45): when true, non-interactive mode
/// is forced (the NS-43 collision prompt is skipped and hard-errors instead).
#[allow(clippy::too_many_arguments)]
fn meld_recursive(
    paths: &Paths,
    registry: &mut Registry,
    repo: &str,
    alias: Option<String>,
    roots: Vec<String>,
    flat_skills: bool,
    consumer_pin: Option<Pin>,
    top_level: bool,
    visited: &mut HashSet<String>,
    policy: Option<&Policy>,
    install_hook: Option<String>,
    dangerously_skip_hook_check: bool,
    prefer_ssh: bool,
    yes: bool,
    curated: Option<CuratedConfig>,
    skipped: &mut Vec<SkippedEntry>,
) -> Result<usize> {
    let out = crate::render::ctx();
    let mut source = parse_spec(repo)?;
    // NS-25: reject a reserved-kind-word prefix at the chokepoint where any alias
    // (top-level `--as`, or a nested source's `as =`) is applied. An empty alias
    // ("no prefix") is accepted by validate_prefix.
    if let Some(a) = &alias {
        crate::namespace::validate_prefix(a)?;
    }
    source.alias = alias;
    // CLI-19: rewrite an https remote to its SSH form when SSH is preferred, so
    // the clone uses the user's key (no https username/password prompt). Done
    // before the cycle guard so the recorded URL is the one we actually clone.
    source.prefer_ssh(prefer_ssh);

    // Cycle guard: don't process the same URL twice in one meld run.
    if !visited.insert(source.url.clone()) {
        return Ok(0);
    }

    if let Some(existing) = registry.find(&source.name) {
        if top_level {
            return Err(MindError::SourceExists {
                name: source.name.clone(),
                url: existing.url.clone(),
            });
        }
        if existing.url != source.url {
            eprintln!(
                "warning: source name '{}' already melded from {}; skipping {}",
                source.name, existing.url, source.url
            );
        }
        return Ok(0);
    }

    // `source.pin` is still the default here, so `clone_dir` resolves a local
    // source to its working tree. A consumer/directive pin (resolved below) can
    // still switch a local source to a cloned snapshot.
    let mut dir = source.clone_dir(paths);
    let is_local = source.is_local();

    if !out.json {
        println!(
            "{} melding {} from {}",
            out.bullet(),
            source.name,
            out.dim(&source.url)
        );
    }

    // A local source with no pin is read straight from its working tree (CLI-27):
    // no clone, and `mind` never touches the directory. Any other source is cloned
    // into the sources tree (default branch first so we can read mind.toml, then
    // re-cloned at the resolved pin if needed).
    if is_local {
        if !dir.is_dir() {
            return Err(MindError::NotADirectory {
                path: dir.display().to_string(),
            });
        }
    } else {
        if dir.exists() {
            std::fs::remove_dir_all(&dir).map_err(|e| MindError::io(&dir, e))?;
        }
        if let Some(parent) = dir.parent() {
            crate::paths::mkdir_p(parent)?;
        }
        git::clone(&source.url, &dir)?;
    }
    let mut mindfile = MindToml::load(&dir)?;
    source.description = mindfile.as_ref().and_then(|m| m.source.description.clone());

    // DSC-60: the curator-supplied roots and hooks apply only when the nested
    // source ships NO mind.toml of its own. The gate is whole-file: any nested
    // mind.toml (even one declaring none of the gated fields) suppresses roots
    // and hooks, since the source has onboarded. `as` (DSC-39) and `install`
    // (DSC-58) are not gated. DSC-65: the curator's pin directive is NOT gated
    // -- it is authoritative regardless of whether the nested source has a
    // mind.toml of its own.
    let curated = curated.unwrap_or(CuratedConfig {
        pin: None,
        roots: None,
        flat_skills: false,
        hooks: Vec::new(),
    });
    let apply_curated = mindfile.is_none();
    // The curator pin is always extracted (DSC-65: authoritative, not gated).
    let curated_pin = curated.pin.clone();
    if !apply_curated && curated.has_gated_values() {
        // spec: DSC-60 — warn only when gated fields (roots/hooks) are present
        // and suppressed. A pin-only entry must NOT trigger this warning.
        eprintln!(
            "warning: {} ships its own mind.toml; curator-supplied roots/flat-skills/hooks are ignored",
            source.name
        );
    }
    let curated_hooks = if apply_curated {
        curated.hooks.clone()
    } else {
        Vec::new()
    };

    // Step 2: resolve the effective pin (CLI-17, DSC-41, DSC-65):
    //   consumer flag > curator pin (DSC-65, authoritative) >
    //   [source] directive > DefaultBranch.
    let toml_path = dir.join("mind.toml");
    let directive_pin = mindfile
        .as_ref()
        .map(|m| m.source.pin_directive(&toml_path))
        .transpose()?
        .flatten();
    let effective_pin = consumer_pin
        .or(curated_pin)
        .or(directive_pin)
        .unwrap_or(Pin::DefaultBranch);

    // Managed-policy enforcement (POL-3 authoritative). The identity is known and
    // the effective pin is resolved, but nothing is registered yet and the only
    // thing on disk is the throwaway default-branch clone (removed on refusal), so
    // a refusal here leaves nothing behind.
    if let Some(policy) = policy {
        let identity = source.name.clone();
        let allowed = policy.allow_matches(&identity);
        if policy.lock() && !allowed {
            // POL-11: locked allowlist refuses a non-matching source outright.
            if !is_local {
                let _ = std::fs::remove_dir_all(&dir);
            }
            return Err(MindError::SourceNotAllowed { identity });
        }
        if !policy.lock() && !allowed {
            // POL-13: with lock off, allow is advisory; warn but proceed.
            eprintln!(
                "warning: source '{identity}' is not in the managed policy's allowlist (advisory; not enforced because [sources].lock is false)"
            );
        }
        if policy.pinned() && matches!(effective_pin, Pin::DefaultBranch | Pin::FollowBranch(_)) {
            // POL-20: pinned policy forbids a floating branch (default branch or
            // --follow-branch); only a tag/ref pin is permitted.
            if !is_local {
                let _ = std::fs::remove_dir_all(&dir);
            }
            return Err(MindError::UnpinnedSourceForbidden { identity });
        }
    }

    // Step 3: if the effective pin is not DefaultBranch, the source is a clone at
    // that point -- including a *pinned local* source, which is snapshotted into
    // the sources tree (so pinning still works) WITHOUT touching the working tree.
    // A pin that does not resolve is a `Git` error that must leave nothing behind
    // (CLI-18); the clone target is always under the sources tree, never the user's
    // working tree.
    if effective_pin != Pin::DefaultBranch {
        // Setting the pin makes `clone_dir` resolve to the sources-tree path even
        // for a local source.
        source.pin = effective_pin.clone();
        let target = source.clone_dir(paths);
        if target.exists() {
            std::fs::remove_dir_all(&target).map_err(|e| MindError::io(&target, e))?;
        }
        if let Some(parent) = target.parent() {
            crate::paths::mkdir_p(parent)?;
        }
        if let Err(e) = git::clone_at(&source.url, &target, &effective_pin) {
            let _ = std::fs::remove_dir_all(&target);
            return Err(e);
        }
        dir = target;
        // The pin may land on a different mind.toml than the working tree / default
        // branch. Reload it so downstream in-memory reads see the pinned content.
        mindfile = MindToml::load(&dir)?;
        source.description = mindfile.as_ref().and_then(|m| m.source.description.clone());
    }

    source.pin = effective_pin;
    // A linked (no-pin) local source records its working-tree HEAD (best-effort; a
    // non-git local dir simply records no commit). Everything else records the
    // cloned commit.
    source.commit = if source.is_linked() {
        git::head_commit(&source.url, &dir).ok()
    } else {
        Some(git::head_commit(&source.url, &dir)?)
    };

    // Persist the consumer's --root override (STO-17, DSC-51).
    // DSC-52: if --root is given for an authoritative source, print a note.
    let is_authoritative = mindfile.as_ref().is_some_and(|m| m.is_authoritative());

    // MKT-2/MKT-15: when an own-item source-discovery directive is in effect, the
    // plugin-manifest's own-item layer is suppressed. Emit an advisory note so the
    // user is not surprised to find the manifest ignored. Both plugin.json and
    // marketplace.json trigger the note; catalog.rs stays quiet and leaves
    // reporting here. Three distinct cases:
    //   - authoritative `[[items]]`/`[discover]` globs (MKT-2): the manifest is
    //     wholly ignored (its external curator entries are not walked either).
    //   - a mind.toml `[source].roots`/`flat-skills` scan layout (MKT-15): only the
    //     manifest's own-item layer is ignored; convention discovery supplies the
    //     repo's items and any marketplace external entries still compose.
    //   - a consumer `--root`/`--flat-skills` override (MKT-15, DSC-51/DSC-75):
    //     same as the scan-layout case, so the flag is not a silent no-op on a
    //     manifest source.
    // A bare `[discover].sources` list is NOT an own-item directive and prints no
    // note: the manifest still defines the immediate source (MKT-16).
    let declares_scan_layout = mindfile.as_ref().is_some_and(|m| m.declares_scan_layout());
    let consumer_scan_layout = !roots.is_empty() || flat_skills;
    if !out.json && (is_authoritative || declares_scan_layout || consumer_scan_layout) {
        let has_plugin = plugin_manifest::find_plugin_manifest(&dir).is_some();
        let has_marketplace = plugin_manifest::find_marketplace_manifest(&dir).is_some();
        if has_plugin || has_marketplace {
            if is_authoritative {
                println!(
                    "note: {} uses an authoritative mind.toml; its .claude-plugin/ manifest is ignored",
                    source.name
                );
            } else {
                // spec: MKT-15 — the manifest's own-item layer is suppressed; name
                // where the convention layout came from (consumer flag vs mind.toml).
                let via = if declares_scan_layout {
                    "mind.toml [source].roots/flat-skills"
                } else {
                    "--root/--flat-skills"
                };
                println!(
                    "note: {} discovers its own items by convention ({via}); \
                     the .claude-plugin/ manifest's plugin components are ignored",
                    source.name
                );
            }
        }
    }

    if !roots.is_empty() {
        if is_authoritative {
            // spec: DSC-52
            if !out.json {
                println!(
                    "note: {} uses an authoritative mind.toml; --root is ignored",
                    source.name
                );
            }
        } else {
            source.roots = Some(roots);
        }
    } else if apply_curated && curated.roots.is_some() {
        // DSC-61: with no consumer --root override, curator-supplied roots govern
        // convention discovery just like a source's own [source].roots (DSC-50).
        // A gated source has no mind.toml, so it cannot be authoritative.
        source.roots = curated.roots.clone();
    }

    // Persist the consumer's --flat-skills override (STO-44, DSC-75), mirroring
    // the --root handling above.
    // DSC-76: if --flat-skills is given for an authoritative source, print a note
    // (it affects convention discovery only).
    if flat_skills {
        if is_authoritative {
            // spec: DSC-76
            if !out.json {
                println!(
                    "note: {} uses an authoritative mind.toml; --flat-skills is ignored",
                    source.name
                );
            }
        } else {
            source.flat_skills = true;
        }
    } else if apply_curated && curated.flat_skills {
        // spec: DSC-77 / DSC-60 — with no consumer override, curator-supplied
        // flat-skills governs convention discovery, applied only because the gated
        // source has no mind.toml of its own (so it cannot be authoritative).
        source.flat_skills = true;
    }

    // Scan before registering. If the source is rejected here (e.g. the
    // version gate, DSC-40), remove the clone so no orphan is left on disk.
    // Use `!source.is_linked()` (not `!is_local`) so that a pinned-local clone
    // (which is NOT a linked working tree) is also cleaned up on failure (CLI-18,
    // CLI-27).
    let mut items = match catalog::scan(paths, &single(&source)) {
        Ok(items) => items,
        Err(e) => {
            if !source.is_linked() {
                let _ = std::fs::remove_dir_all(&dir);
            }
            return Err(e);
        }
    };

    // CLI-24: a source that declares `[source].prefix` and was not melded with an
    // explicit `--as` prefix prompts (interactively) whether to namespace its
    // items under that prefix. The items were scanned with no alias, so their
    // effective names already reflect the declared prefix; show them so the choice
    // is concrete (the names the items will install as). The choice becomes the
    // source alias; if it differs from the declared prefix, re-scan so the recorded
    // names, the warning, and the count match. Non-interactive runs accept the
    // declared prefix as-is (alias stays None).
    if top_level
        && source.alias.is_none()
        && crate::hook::is_tty()
        && let Some(declared) = mindfile.as_ref().and_then(|m| m.source.prefix.clone())
        && !declared.is_empty()
    {
        let preview = if items.is_empty() {
            String::new()
        } else {
            let names: Vec<String> = items.iter().map(|it| it.key()).collect();
            format!("\n  items would install as: {}", names.join(", "))
        };
        let answer = prompt_line(&format!(
            "{} suggests the prefix '{declared}'.{preview}\n  use it? [Y]es / type a different prefix / [n]o prefix: ",
            source.name
        ))?;
        let chosen = crate::namespace::prefix_choice(&answer);
        // NS-25: a custom prefix typed at the prompt is held to the same rule.
        if let Some(c) = &chosen {
            crate::namespace::validate_prefix(c)?;
        }
        if chosen != source.alias {
            source.alias = chosen;
            items = match catalog::scan(paths, &single(&source)) {
                Ok(items) => items,
                Err(e) => {
                    if !source.is_linked() {
                        let _ = std::fs::remove_dir_all(&dir);
                    }
                    return Err(e);
                }
            };
        }
    }

    // NS-43: Cross-source skill/rule/tool collision check. Only runs for a
    // top-level `meld` (not for curated nested sources which the caller controls).
    if top_level {
        let manifest = crate::manifest::Manifest::load(paths)?;
        let mut conflicts: Vec<(String, String, String)> = Vec::new();
        for entry in manifest.items.values() {
            // Agents are handled separately by NS-41.
            if entry.kind == crate::error::ItemKind::Agent {
                continue;
            }
            // Skip items from the same source (re-meld / upgrade).
            if entry.source == source.name {
                continue;
            }
            // Collision: same (kind, effective_name) pair from a different source.
            let eff_name = entry.name.as_str();
            if items
                .iter()
                .any(|it| it.kind == entry.kind && it.effective_name() == eff_name)
            {
                conflicts.push((
                    entry.kind.as_str().to_string(),
                    eff_name.to_string(),
                    entry.source.clone(),
                ));
            }
        }
        if !conflicts.is_empty() {
            let suggested = suggested_namespace(&source.url);
            // spec: NS-44 NS-45 — interactive only on a real TTY AND without --yes.
            if crate::hook::is_tty() && !yes {
                // NS-44: interactive TTY path — prompt for a namespace prefix.
                // spec: NS-44
                let answer = prompt_line(&format!(
                    "name collision detected -- the following items conflict with \
                     already-installed items:\n{}\n\
                     enter a namespace prefix [{suggested}] (. to abort): ",
                    format_conflicts_display(&conflicts),
                ))?;
                // spec: NS-44 — parse the collision answer:
                //   empty  → accept the suggested prefix
                //   "."    → abort (SkillCollision, same as non-interactive)
                //   other  → use as custom prefix
                match parse_collision_answer(&answer, &suggested) {
                    CollisionAnswer::Abort => {
                        if !source.is_linked() {
                            let _ = std::fs::remove_dir_all(&dir);
                        }
                        return Err(MindError::SkillCollision {
                            conflicts,
                            suggested,
                        });
                    }
                    CollisionAnswer::Prefix(chosen_str) => {
                        let chosen = if chosen_str.is_empty() {
                            None
                        } else {
                            Some(chosen_str)
                        };
                        if let Some(c) = &chosen {
                            crate::namespace::validate_prefix(c)?;
                        }
                        if chosen != source.alias {
                            source.alias = chosen;
                            items = match catalog::scan(paths, &single(&source)) {
                                Ok(items) => items,
                                Err(e) => {
                                    if !source.is_linked() {
                                        let _ = std::fs::remove_dir_all(&dir);
                                    }
                                    return Err(e);
                                }
                            };
                        }
                    }
                }
            } else {
                // spec: NS-43 NS-45 — non-interactive (no TTY or --yes): hard error.
                if !source.is_linked() {
                    let _ = std::fs::remove_dir_all(&dir);
                }
                return Err(MindError::SkillCollision {
                    conflicts,
                    suggested,
                });
            }
        }
    }

    warn_unguarded_references(&items);
    warn_agent_collisions(paths, &items); // spec: NS-41 advisory
    if !out.json {
        println!(
            "{} melded {} ({} item(s))",
            out.ok(),
            source.name,
            items.len()
        );
    }

    // MKT-4: for a single-plugin source, report any unsupported component kinds
    // (hooks, mcp servers, etc.) that were silently dropped. This is advisory and
    // never a silent drop: the user sees a count so they are not misled into
    // thinking the plugin is fully represented. Only for plugin.json sources
    // (not marketplace catalogs, not convention-discovered sources).
    if !is_authoritative && !out.json && plugin_manifest::find_plugin_manifest(&dir).is_some() {
        let skipped_comps = catalog::plugin_skipped_components(&dir);
        if let Some(summary) = skipped_comps.summary() {
            println!("note: {summary}");
        }
    }

    // Install hooks (HOOK-50..60): the working tree is now checked out at the
    // resolved pin, so hooks run in the right tree. A fresh meld runs every
    // (as-yet-unrun) install hook.
    match run_install_hooks(
        &mut source,
        &dir,
        &mindfile,
        &toml_path,
        install_hook.as_deref(),
        dangerously_skip_hook_check,
        false,
        // DSC-61: curator-supplied hooks (when applied) run through the same
        // disclosure/safety-prompt/non-TTY-skip path as a source's own hooks.
        curated_hooks,
    ) {
        Ok(HookOutcome::Proceed) => {}
        Ok(HookOutcome::Abort) => {
            // HOOK-21: aborting installs nothing; the source is not registered.
            // Use `!source.is_linked()` so a pinned-local clone is removed on
            // abort, while a linked working tree is never touched (CLI-27).
            if !source.is_linked() {
                let _ = std::fs::remove_dir_all(&dir);
            }
            println!("aborted; nothing installed");
            return Ok(0);
        }
        Err(e) => {
            // HOOK-30/HOOK-53: a hook failure fails the meld; remove the clone.
            // Same guard: remove a pinned-local clone but not the working tree.
            if !source.is_linked() {
                let _ = std::fs::remove_dir_all(&dir);
            }
            return Err(e);
        }
    }

    // MKT-6/MKT-10: record plugin/marketplace provenance and metadata when the
    // source came from a Claude plugin manifest (not suppressed by an authoritative
    // mind.toml). The description from plugin.json fills in only when mind.toml
    // [source].description has not already set it (DSC-32 precedence). Strings
    // from the manifest are passed through strip_ansi to prevent terminal injection
    // (MKT-9/DSC-69).
    if !is_authoritative {
        if let Some(plugin_path) = plugin_manifest::find_plugin_manifest(&dir) {
            source.origin = Some(ManifestOrigin::ClaudePlugin);
            if let Ok(pm) = plugin_manifest::load_plugin_manifest(&plugin_path) {
                source.plugin_version = pm.version;
                if source.description.is_none() {
                    source.description = pm.description.map(|d| strip_ansi(&d));
                }
            }
        } else if plugin_manifest::find_marketplace_manifest(&dir).is_some() {
            // The marketplace-level origin; per-entry origins are set below (Section C)
            // after each sub-source is recursively melded.
            source.origin = Some(ManifestOrigin::ClaudeMarketplace);
        }
    }

    // Capture the super-source name before moving `source` into the registry,
    // so DSC-63 error messages can reference it.
    let super_source_name = source.name.clone();
    registry.sources.push(source);

    let mut added = 1;
    // DSC-80: count nested entries that failed to register for a non-auth reason,
    // so the curator-empty guard below can distinguish "curator with all nested
    // sources gone" from an ordinary curator that simply has nothing nested.
    let mut nested_clone_failures = 0usize;
    if let Some(nested) = mindfile
        .as_ref()
        .and_then(|m| m.discover.as_ref())
        .map(|d| &d.sources)
    {
        for entry in nested {
            // DSC-64: install = true and a non-empty install-items list are
            // mutually exclusive; error before we register anything.
            entry.validate(&toml_path)?;

            // DSC-59 DSC-65: lift this entry's curator-supplied configuration.
            // The pin directive is authoritative (DSC-65). Hooks and roots are
            // gated (DSC-60). All are resolved here against the super-source's
            // mind.toml path; the gate lives in the recursive call.
            let curated = CuratedConfig {
                pin: entry.pin_directive(&toml_path)?,
                roots: entry.roots.clone(),
                flat_skills: entry.flat_skills,
                hooks: entry.resolved_hooks(&toml_path)?,
            };
            // Nested sources from a curated super-source get no consumer pin or
            // root override; the curator config (when applied) supplies them.
            match meld_recursive(
                paths,
                registry,
                &entry.source,
                entry.effective_alias(), // spec: DSC-78 — prefer `namespace`, fall back to `as`
                vec![],                  // no consumer roots for nested sources
                false, // no consumer --flat-skills for nested sources (curator config supplies it)
                None,  // no consumer pin for nested sources
                false,
                visited,
                policy,
                None, // no consumer install hook for nested sources
                dangerously_skip_hook_check,
                prefer_ssh, // nested sources inherit the SSH preference
                false,      // nested sources inherit non-interactive mode but not --yes
                Some(curated),
                skipped,
            ) {
                Ok(n) => added += n,
                // DSC-68/DSC-69: an auth failure is governed by on-auth-failure
                // when present; without it, it stays a generic git error.
                Err(e) if git::is_auth_failure(&e) => {
                    let entry_name = parse_spec(&entry.source)
                        .map(|s| s.name)
                        .unwrap_or_else(|_| entry.source.clone());
                    // spec: DSC-70 -- on-auth-failure only covers the entry's own
                    // clone failure. If the entry is already in the registry, it
                    // cloned successfully and the failure came from a descendant;
                    // propagate it unchanged so it is not misattributed to this entry.
                    if registry.find(&entry_name).is_some() {
                        return Err(e);
                    }
                    let Some(cfg) = &entry.on_auth_failure else {
                        return Err(e);
                    };
                    // spec: DSC-69 -- always warn to stderr regardless of --json mode;
                    // --json controls the outer result format, not warning visibility.
                    for line in auth_failure_lines(&entry_name, cfg) {
                        eprintln!("{line}");
                    }
                    if cfg.action == AuthFailureAction::Skip {
                        skipped.push(SkippedEntry {
                            source: entry_name,
                            reason: "auth_failure".into(),
                        });
                        // The source is not registered; its transitive chain is
                        // unreachable and therefore also skipped.
                        continue;
                    }
                    return Err(e);
                }
                // spec: DSC-79 -- a non-auth clone failure (network error,
                // not-found, etc.) of a nested entry is skipped with a warning
                // rather than hard-failing the whole meld.
                Err(e) => {
                    let entry_name = parse_spec(&entry.source)
                        .map(|s| s.name)
                        .unwrap_or_else(|_| entry.source.clone());
                    // spec: DSC-79/DSC-70 -- if the entry is already registered it
                    // cloned fine and the error came from a descendant; propagate
                    // it unchanged rather than misattributing it to this entry.
                    // The primary's own clone failure exits before this loop is
                    // reached (parse/clone of the primary happens in the top-level
                    // meld_recursive call), so this arm only sees nested failures.
                    if registry.find(&entry_name).is_some() {
                        return Err(e);
                    }
                    for line in clone_failure_lines(&entry_name, &e) {
                        eprintln!("{line}");
                    }
                    skipped.push(SkippedEntry {
                        source: entry_name,
                        reason: "clone_failure".into(),
                    });
                    nested_clone_failures += 1;
                    continue;
                }
            }

            // DSC-63: validate each install_items ref against the nested source's
            // offered bare names. A ref that names a non-existent item is an error
            // at meld, not a silent skip.
            if let Some(refs) = &entry.install_items
                && !refs.is_empty()
                && let Ok(spec) = parse_spec(&entry.source)
                && let Some(nested_src) = registry.find(&spec.name)
            {
                let nested_items = catalog::scan(paths, &single(nested_src))?;
                for item_ref in refs {
                    // Each ref must be a bare kind:name (DSC-63).
                    let parsed = crate::resolve::parse_item_ref(item_ref).map_err(|_| {
                        MindError::BadReference {
                            item: format!("install-items in '{super_source_name}'"),
                            referent: item_ref.clone(),
                            in_source: spec.name.clone(),
                        }
                    })?;
                    // The ref must name an item the nested source offers
                    // (by bare name, not effective/prefixed name).
                    let found = nested_items.iter().any(|it| {
                        parsed.kind.is_none_or(|k| it.kind == k) && it.name == parsed.name
                    });
                    if !found {
                        return Err(MindError::BadReference {
                            item: format!("install-items in '{super_source_name}'"),
                            referent: item_ref.clone(),
                            in_source: spec.name.clone(),
                        });
                    }
                }
            }
        }
    }

    // MKT-7/MKT-8: marketplace catalog as a curated super-source. When the
    // melded source has a .claude-plugin/marketplace.json (and no authoritative
    // mind.toml), iterate its entries and meld each as a sub-source, reusing the
    // same [discover].sources machinery. This is an additive pass that runs after
    // the mind.toml nested-source loop above.
    if !is_authoritative
        && let Some(marketplace_path) = plugin_manifest::find_marketplace_manifest(&dir)
    {
        match plugin_manifest::load_marketplace_manifest(&marketplace_path) {
            Ok(manifest) => {
                for entry in manifest.into_entries() {
                    // MKT-14: in-repo plugins are catalog items of the parent source
                    // (handled by catalog::scan_source_at); only external entries
                    // need a recursive sub-meld here.
                    if matches!(entry.source, plugin_manifest::PluginSource::InRepo { .. }) {
                        continue; // spec: MKT-14
                    }
                    // belt-and-suspenders: into_entries() already validates
                    // in-repo paths, so this is a redundant safety check.
                    if let plugin_manifest::PluginSource::InRepo { ref path } = entry.source
                        && !plugin_manifest::is_safe_manifest_path(path)
                    {
                        return Err(MindError::MindToml {
                            path: marketplace_path.clone(),
                            msg: format!(
                                "marketplace.json: in-repo plugin path {:?} is unsafe",
                                path
                            ),
                        });
                    }
                    let repo_spec = marketplace_entry_spec(&entry, &dir);
                    let entry_name = entry.name.clone();
                    let entry_version = entry.version;
                    let entry_description = entry.description;
                    // Recurse exactly like [discover].sources: cycle-safe
                    // via visited, no consumer pin or roots, no install hook.
                    match meld_recursive(
                        paths,
                        registry,
                        &repo_spec,
                        Some(entry_name.clone()),
                        vec![],
                        false,
                        None,  // no consumer pin
                        false, // nested, not top-level
                        visited,
                        policy,
                        None, // no install hook override
                        dangerously_skip_hook_check,
                        prefer_ssh,
                        false, // marketplace nested sources inherit non-interactive
                        None,  // no curator config
                        skipped,
                    ) {
                        Ok(n) => {
                            added += n;
                            // MKT-8: marketplace entry fields are authoritative
                            // over the sub-source's own plugin.json. After the
                            // recursive meld, find the just-registered sub-source
                            // by its computed name and overwrite any fields the
                            // entry supplies (entry wins when both supply a value).
                            if let Ok(sub_spec) = parse_spec(&repo_spec)
                                && let Some(sub) = registry
                                    .sources
                                    .iter_mut()
                                    .find(|s| s.name == sub_spec.name)
                            {
                                // Always tag as ClaudeMarketplace regardless of
                                // what the sub-source's own plugin.json says.
                                sub.origin = Some(ManifestOrigin::ClaudeMarketplace);
                                if entry_version.is_some() {
                                    sub.plugin_version = entry_version;
                                }
                                if entry_description.is_some() {
                                    sub.description = entry_description.map(|d| strip_ansi(&d));
                                }
                            }
                        }
                        Err(e) if git::is_auth_failure(&e) => {
                            // No on_auth_failure is defined for marketplace
                            // entries (no curator config); an auth failure
                            // propagates as a generic error.
                            return Err(e);
                        }
                        // spec: DSC-79 -- a non-auth clone failure of a marketplace
                        // sub-source is skipped with a warning, mirroring the
                        // [discover].sources loop above.
                        Err(e) => {
                            let sub_name = parse_spec(&repo_spec)
                                .map(|s| s.name)
                                .unwrap_or_else(|_| entry_name.clone());
                            // spec: DSC-79/DSC-70 -- a failure after the sub-source is
                            // already registered originates from a descendant; propagate.
                            if registry.find(&sub_name).is_some() {
                                return Err(e);
                            }
                            for line in clone_failure_lines(&sub_name, &e) {
                                eprintln!("{line}");
                            }
                            skipped.push(SkippedEntry {
                                source: sub_name,
                                reason: "clone_failure".into(),
                            });
                            nested_clone_failures += 1;
                            continue;
                        }
                    }
                }
            }
            Err(e) => return Err(e),
        }
    }

    // spec: DSC-80 -- when the primary source is exclusively a curator (a catalog
    // scan of its own directory yields zero items) and every nested source failed
    // to register, registering a source with no discoverable items is not useful;
    // hard-fail. Only relevant when at least one nested source failed to clone; a
    // primary with its own items, or with any nested source that registered
    // (added > 1), succeeds. The primary/top-level source's own clone failure is a
    // separate hard error handled before the nested loop.
    if nested_clone_failures > 0
        && added == 1
        && let Some(primary) = registry.find(&super_source_name)
        && catalog::scan(paths, &single(primary))?.is_empty()
    {
        return Err(MindError::CuratorAllNestedFailed {
            super_source: super_source_name.to_string(),
        });
    }

    Ok(added)
}

/// Strip ANSI CSI escape sequences and control characters from `s`.
/// CSI sequences (`ESC [` params final-byte) are removed in full; C0
/// Strip ANSI/VT escape sequences and terminal-dangerous Unicode from `s`.
/// `strip-ansi-escapes` handles the full escape grammar (CSI, OSC, DCS, etc.).
/// A second pass drops C0/DEL/C1 controls and Unicode bidi-override/separator
/// code points that are not escape sequences but can still corrupt terminal output.
/// Printable non-ASCII (U+00A0 and above, minus the blocked ranges) is preserved
/// so non-English curator messages are not corrupted.
fn strip_ansi(s: &str) -> String {
    let bytes = strip_ansi_escapes::strip(s);
    // Input is valid UTF-8, so output is too; lossy conversion is a no-op in practice.
    String::from_utf8_lossy(&bytes)
        .chars()
        .filter(|&c| {
            (('\x20'..='\x7e').contains(&c) || c > '\u{009f}')
                && !matches!(
                    c,
                    // Bidi-override code points: phishing/spoofing vectors.
                    '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}'
                    // Line separator and paragraph separator.
                    | '\u{2028}' | '\u{2029}'
                )
        })
        .collect()
}

/// Derive a suggested namespace prefix from a source URL or local path.
///
/// Takes the last `/`-separated component and strips any `.git` suffix, so
/// `"https://github.com/foo/bar"` → `"bar"` and `"local/x/y"` → `"y"`.
fn suggested_namespace(url: &str) -> String {
    let base = url.split('/').next_back().unwrap_or(url);
    base.strip_suffix(".git").unwrap_or(base).to_string()
}

/// Format a conflict list for the interactive collision prompt (NS-44).
///
/// Each tuple is `(kind, effective_name, existing_source)`. Produces the same
/// bullet style as the `SkillCollision` error for consistency. Item name and
/// source name are stripped of ANSI escapes so a malicious source cannot inject
/// terminal control sequences into the prompt (spec: NS-44).
fn format_conflicts_display(conflicts: &[(String, String, String)]) -> String {
    conflicts
        .iter()
        .map(|(k, n, s)| {
            let safe_n = strip_ansi(n);
            let safe_s = strip_ansi(s);
            format!("  {k}:{safe_n} (already installed from '{safe_s}')")
        })
        .collect::<Vec<_>>()
        .join("\n")
}

/// The parsed outcome of a user's response to the NS-44 collision prompt.
enum CollisionAnswer {
    /// Accept the given prefix (empty string = no prefix, non-empty = custom prefix).
    Prefix(String),
    /// User chose to abort; stop the meld with SkillCollision.
    Abort,
}

/// Parse the user's raw answer to the NS-44 collision prompt (spec: NS-44).
///
/// - Empty (Enter) → accept the pre-populated suggested prefix.
/// - `.` → abort (same outcome as the non-interactive non-TTY path).
/// - Anything else → use as a custom prefix (caller must validate it).
fn parse_collision_answer(answer: &str, suggested: &str) -> CollisionAnswer {
    let trimmed = answer.trim();
    if trimmed.is_empty() {
        // spec: NS-44 — accepting the suggestion continues under that prefix.
        CollisionAnswer::Prefix(suggested.to_string())
    } else if trimmed == "." {
        // spec: NS-44 — aborting stops meld with a non-zero exit.
        CollisionAnswer::Abort
    } else {
        CollisionAnswer::Prefix(trimmed.to_string())
    }
}

/// Return the display token for a source's manifest origin (MKT-10).
///
/// The token is prepended with a space so it can be concatenated directly into
/// the bracketed metadata string `[commit ns hook origin]`. Returns an empty
/// string when the source has no recorded origin (convention / mind.toml source).
fn origin_label(origin: Option<ManifestOrigin>) -> String {
    match origin {
        None => String::new(),
        Some(ManifestOrigin::ClaudePlugin) => " origin:claude-plugin".to_string(),
        Some(ManifestOrigin::ClaudeMarketplace) => " origin:claude-marketplace".to_string(),
    }
}

/// Resolve a [`plugin_manifest::MarketplaceEntry`] to the repo spec string
/// needed by `meld_recursive`.
///
/// - `External { spec }`: the spec is used verbatim (passed to `parse_spec`).
/// - `InRepo { path }`: the path is joined onto `clone_dir` to produce an
///   absolute local path, which `parse_spec` recognises as a local source.
fn marketplace_entry_spec(
    entry: &plugin_manifest::MarketplaceEntry,
    clone_dir: &std::path::Path,
) -> String {
    match &entry.source {
        plugin_manifest::PluginSource::External { spec } => spec.clone(),
        plugin_manifest::PluginSource::InRepo { path } => {
            clone_dir.join(path).to_string_lossy().into_owned()
        }
    }
}

/// Build the human-readable lines for an auth failure of a nested source, per
/// DSC-69. The first line is always the standard auth-failure line, with
/// `" (skipping)"` appended under the `"skip"` action. When `message` is set it
/// is the second line, shown immediately after.
fn auth_failure_lines(entry_name: &str, cfg: &crate::mindfile::OnAuthFailure) -> Vec<String> {
    // spec: DSC-69
    let is_skip = cfg.action == AuthFailureAction::Skip;
    let safe_name = strip_ansi(entry_name);
    let mut lines = vec![format!(
        "unable to meld source {} due to authentication failure{}",
        safe_name,
        if is_skip { " (skipping)" } else { "" }
    )];
    if let Some(msg) = &cfg.message {
        // spec: DSC-69 -- strip ANSI escape sequences and non-printable bytes so
        // a malicious curator message cannot corrupt the terminal.
        let safe_msg = strip_ansi(msg);
        lines.push(safe_msg);
    }
    lines
}

/// Build the human-readable warning lines for a non-auth clone failure of a
/// nested source, per DSC-79. The entry name and the underlying error are both
/// passed through `strip_ansi` so a malicious remote (via error text) or entry
/// name cannot corrupt the terminal.
fn clone_failure_lines(entry_name: &str, err: &MindError) -> Vec<String> {
    // spec: DSC-79
    let safe_name = strip_ansi(entry_name);
    let safe_err = strip_ansi(&err.to_string());
    vec![format!(
        "  warning: skipping '{safe_name}': clone failed ({safe_err}), source unavailable"
    )]
}

/// Warn when a namespaced source references siblings in bare prose, which
/// prefixing will break unless rewritten as `{{ns:name}}` tokens. Scans every
/// text file of each item (the whole skill directory, or the agent/rule file),
/// matching the breadth of install-time `{{ns:}}` expansion.
fn warn_unguarded_references(items: &[CatalogItem]) {
    // spec: CLI-162 -- advisory only emitted under --verbose.
    if !crate::render::ctx().verbose {
        return;
    }
    // Only meaningful once a prefix is in effect.
    if !items.iter().any(|it| it.prefix.is_some()) {
        return;
    }
    // spec: NS-42 -- exclude pure-agent names from the warning scan: a bare prose
    // reference to a sibling agent resolves correctly even under a prefix (because
    // agents link under their bare harness name, NS-40). Flagging agent references
    // would be a false positive. The cross-kind shadow rule: if a name is both an
    // agent AND a non-agent sibling, it is NOT excluded (it does get prefixed for
    // the non-agent kind, so the warning is still meaningful).
    let agent_names: std::collections::HashSet<String> = items
        .iter()
        .filter(|it| it.kind == ItemKind::Agent)
        .map(|it| it.name.clone())
        .collect();
    let non_agent_names: std::collections::HashSet<String> = items
        .iter()
        .filter(|it| it.kind != ItemKind::Agent)
        .map(|it| it.name.clone())
        .collect();
    // The scanning set: all names except pure-agent-only ones.
    let siblings: std::collections::HashSet<String> = items
        .iter()
        .map(|it| it.name.clone())
        .filter(|name| {
            // Keep the name if it is not an agent, OR if it is also a non-agent
            // sibling (the shadow case).
            !agent_names.contains(name) || non_agent_names.contains(name)
        })
        .collect();
    for item in items {
        let mut refs: Vec<String> = Vec::new();
        for file in crate::review::item_files(item) {
            let Ok(content) = std::fs::read_to_string(&file) else {
                continue; // skip non-UTF-8 / unreadable files
            };
            for r in crate::namespace::unguarded_refs(&content, &siblings) {
                // Self-mentions are fine; dedup across files.
                if r != item.name && !refs.contains(&r) {
                    refs.push(r);
                }
            }
        }
        if !refs.is_empty() {
            eprintln!(
                "warning: {} references sibling(s) in prose: {}; prefixing may break them at runtime (use {{{{ns:name}}}})",
                item.key(),
                refs.join(", ")
            );
        }
    }
}

/// Warn when melding a source whose agents would collide with already-installed
/// agents from a different source (NS-41 advisory). Does not fail meld; the
/// actual enforcement is at `learn` time with `AgentCollision`.
fn warn_agent_collisions(paths: &Paths, items: &[CatalogItem]) {
    // spec: NS-41
    let manifest = match Manifest::load(paths) {
        Ok(m) => m,
        Err(_) => return, // manifest unavailable; skip advisory rather than propagate
    };
    let agent_homes = match paths.agent_homes() {
        Ok(h) => h,
        Err(_) => return,
    };
    for item in items {
        if item.kind != ItemKind::Agent {
            continue;
        }
        let harness_name = item
            .agent_harness_name()
            .unwrap_or_else(|| item.name.clone());
        let link_rel = item
            .link_rel
            .clone()
            .or_else(|| paths.default_link_rel(ItemKind::Agent, &harness_name));
        let Some(rel) = link_rel else { continue };
        let planned: Vec<std::path::PathBuf> = agent_homes
            .iter()
            .filter(|h| h.admits(ItemKind::Agent))
            .map(|h| h.path.join(&rel))
            .collect();
        for entry in manifest.items.values() {
            if entry.kind != ItemKind::Agent {
                continue;
            }
            // Same item (re-meld of the same source): not a collision.
            if entry.source == item.source && entry.bare_name == item.name {
                continue;
            }
            let collides = entry.links.iter().any(|link| {
                planned
                    .iter()
                    .any(|p| p.as_path() == std::path::Path::new(link.as_str()))
            });
            if collides {
                eprintln!(
                    "warning: agent '{harness_name}' from '{}' would collide with the installed \
                     agent from '{}' at agents/{harness_name}.md -- run `mind forget {}` to \
                     remove it first",
                    item.source,
                    entry.source,
                    entry.key(),
                );
            }
        }
    }
}

/// NS-41: if `target` is an agent whose bare harness link would collide with an
/// already-installed agent from a *different* source, return the `AgentCollision`
/// error to raise. Returns `Ok(None)` for a non-agent, no collision, or a
/// same-identity re-install/upgrade (matched by stable identity
/// `(source, bare_name)`). The planned links mirror what `install` will create,
/// so an explicit `mind.toml` `link` is honored the same way.
fn agent_collision(
    paths: &Paths,
    manifest: &Manifest,
    target: &CatalogItem,
) -> Result<Option<MindError>> {
    // spec: NS-41
    if target.kind != ItemKind::Agent {
        return Ok(None);
    }
    let harness_name = target
        .agent_harness_name()
        .unwrap_or_else(|| target.name.clone());
    let Some(rel) = target
        .link_rel
        .clone()
        .or_else(|| paths.default_link_rel(ItemKind::Agent, &harness_name))
    else {
        return Ok(None);
    };
    let planned: Vec<std::path::PathBuf> = paths
        .agent_homes()?
        .iter()
        .filter(|h| h.admits(ItemKind::Agent))
        .map(|h| h.path.join(&rel))
        .collect();
    for entry in manifest.items.values() {
        if entry.kind != ItemKind::Agent {
            continue;
        }
        // Same item from the same source (upgrade / re-install): not a collision.
        if entry.source == target.source && entry.bare_name == target.name {
            continue;
        }
        let collides = entry.links.iter().any(|link| {
            planned
                .iter()
                .any(|p| p.as_path() == std::path::Path::new(link.as_str()))
        });
        if collides {
            return Ok(Some(MindError::AgentCollision {
                name: harness_name,
                existing: entry.source.clone(),
                incoming: target.source.clone(),
            }));
        }
    }
    Ok(None)
}

/// The set of bare item names belonging to a source, for reference validation.
/// Every catalog item belonging to `source`, used to validate and expand an
/// item's reference tokens at install (the `{{ns:}}` names plus the `{{self}}` /
/// `{{tools:}}` / `{{path:}}` path tokens, which need each sibling's kind/bin).
fn siblings_of(items: &[CatalogItem], source: &str) -> Vec<CatalogItem> {
    items
        .iter()
        .filter(|it| it.source == source)
        .cloned()
        .collect()
}

/// `mind init-source [path] [--template]` — maintainer scaffolding. Discovers the
/// repo's items, reports the intra-source reference graph, scaffolds a `mind.toml`
/// if absent, and (with `--template`) rewrites bare sibling references into
/// `{{ns:}}` tokens. With `--marketplace` generates `.claude-plugin/marketplace.json`.
/// Operates only on the target directory: no store, no agent home, no network (INIT-6).
// spec: INIT-1 INIT-2 INIT-3 INIT-4 INIT-6 INIT-9 INIT-10 INIT-11 INIT-12
pub fn init_source(
    dir: Option<&str>,
    template: bool,
    marketplace: bool,
    flat_skills_flag: bool,
    namespace: Option<String>,
) -> Result<()> {
    let dir = dir.unwrap_or(".");
    let path = std::path::Path::new(dir);
    if !path.is_dir() {
        return Err(MindError::NotADirectory {
            path: dir.to_string(),
        });
    }
    let root = path.canonicalize().map_err(|e| MindError::io(path, e))?;

    let toml_path = root.join("mind.toml");

    // Read the pre-existing mind.toml content (if any) for the scaffold patching
    // step and for extracting description/prefix for the marketplace manifest.
    let pre_toml = if toml_path.exists() {
        Some(std::fs::read_to_string(&toml_path).map_err(|e| MindError::io(&toml_path, e))?)
    } else {
        None
    };

    // Discover items exactly as melding would (INIT-2): build a local Source for
    // the directory and scan it (honors convention + mind.toml + min-mind-version).
    // Set flat_skills on the source struct before scanning so flat layout is used
    // even before mind.toml is written (INIT-12, DSC-74).
    let mut source = parse_spec(&root.to_string_lossy())?;
    if flat_skills_flag {
        source.flat_skills = true;
    }
    let mut items: Vec<CatalogItem> = Vec::new();
    catalog::scan_source_at(&root, &source, &mut items)?;

    println!("init-source: {}", root.display());
    if items.is_empty() {
        println!("  no items found (skills/<name>/SKILL.md, agents/<name>.md, rules/<name>.md)");
    } else {
        println!("  {} item(s):", items.len());
        for it in &items {
            println!("    {} {}", it.kind, it.name);
        }
    }

    // Reference graph (INIT-4): per item, the siblings it references via tokens
    // (informational) and the ones it mentions in bare prose. The bare mentions
    // are reported as `unguarded-reference` advisories in the same format as
    // `review` (CLI-131), so review and init-source read identically.
    let siblings: std::collections::HashSet<String> =
        items.iter().map(|it| it.name.clone()).collect();
    // INIT-9: the bare-prose `unguarded-reference` advisory fires only when an
    // effective prefix is in force (matching `meld` NS-23 and `review` CLI-133):
    // absent a prefix, bare references resolve as written. The `{{ns:}}`-token
    // graph and the `--template` rewrite below are unaffected by this gate.
    let prefix_in_force = items.iter().any(|it| it.prefix.is_some());
    let mut findings: Vec<crate::review::Finding> = Vec::new();
    for it in &items {
        let content = read_item_text(it);
        let tokens: Vec<String> = crate::namespace::referenced_names(&content)
            .into_iter()
            .filter(|n| n != &it.name)
            .collect();
        let bare: Vec<String> = crate::namespace::unguarded_refs(&content, &siblings)
            .into_iter()
            .filter(|n| n != &it.name)
            .collect();
        if !tokens.is_empty() {
            println!(
                "  {} {} -> {} (tokenized)",
                it.kind,
                it.name,
                tokens.join(", ")
            );
        }
        if prefix_in_force && !bare.is_empty() {
            findings.push(crate::review::Finding::advisory(
                "unguarded-reference",
                format!(
                    "{}: references sibling(s) in prose: {}; prefixing may break them at runtime (use {{{{ns:name}}}})",
                    it.key(),
                    bare.join(", ")
                ),
            ));
        }
    }
    // The `--template` hint applies only to bare prose references; duplicate
    // tooling is structural and not something templating fixes.
    let has_unguarded = findings.iter().any(|f| f.kind == "unguarded-reference");
    // INIT-7: surface the same duplicate-tooling advisories `review` reports
    // (CLI-144), so the two commands read identically here too.
    findings.extend(crate::review::duplicate_tooling_findings(&items));
    crate::review::print_findings(&[], &findings);
    if has_unguarded && !template {
        println!(
            "run `mind init-source {dir} --template` to wrap the bare references as {{{{ns:name}}}}"
        );
    }

    // mind.toml handling: INIT-3 (create if absent) + INIT-12 (patch when flags
    // require it). When flat_skills_flag or namespace is set, always write (patch
    // existing or create with scaffold); otherwise keep the create-if-absent logic.
    if flat_skills_flag || namespace.is_some() {
        let patched = crate::scaffold::patch_source_meta(
            pre_toml.as_deref(),
            flat_skills_flag,
            namespace.as_deref(),
        );
        std::fs::write(&toml_path, &patched).map_err(|e| MindError::io(&toml_path, e))?;
        println!("  wrote mind.toml");
    } else if toml_path.exists() {
        println!("  mind.toml already exists; left unchanged");
    } else {
        std::fs::write(&toml_path, crate::scaffold::SCAFFOLD)
            .map_err(|e| MindError::io(&toml_path, e))?;
        println!("  wrote mind.toml");
    }

    // Marketplace manifest (INIT-10): generate .claude-plugin/marketplace.json
    // when --marketplace is passed, unless one already exists.
    if marketplace {
        if plugin_manifest::find_marketplace_manifest(&root).is_some() {
            println!("  .claude-plugin/marketplace.json already exists; left unchanged");
        } else {
            // INIT-11: name priority: --namespace > mind.toml prefix > dir basename.
            let dir_basename = root
                .file_name()
                .map(|n| n.to_string_lossy().into_owned())
                .unwrap_or_default();
            // Read the current mind.toml (after any writes) for the prefix.
            let mindfile_prefix =
                crate::mindfile::MindToml::load(&root)?.and_then(|mt| mt.source.prefix);
            let name = crate::scaffold::plugin_name(
                &dir_basename,
                mindfile_prefix.as_deref(),
                namespace.as_deref(),
            );

            // Description: from [source].description in the pre-existing mind.toml
            // (preserved through patch), else placeholder.
            let description = crate::mindfile::MindToml::load(&root)
                .ok()
                .flatten()
                .and_then(|mt| mt.source.description)
                .filter(|d| !d.trim().is_empty())
                .unwrap_or_else(|| "TODO: describe this plugin".to_string());

            // Skills array only when --flat-skills is also in effect (INIT-10).
            let skills: Option<Vec<String>> = if flat_skills_flag {
                let mut paths: Vec<String> = items
                    .iter()
                    .filter(|it| it.kind == ItemKind::Skill)
                    .filter_map(|it| {
                        it.path
                            .strip_prefix(&root)
                            .ok()
                            .map(|rel| rel.to_string_lossy().into_owned())
                    })
                    .collect();
                paths.sort();
                Some(paths)
            } else {
                None
            };

            let plugin_dir = root.join(".claude-plugin");
            std::fs::create_dir_all(&plugin_dir).map_err(|e| MindError::io(&plugin_dir, e))?;
            let json_path = plugin_manifest::marketplace_manifest_path(&root);
            let json =
                crate::scaffold::render_marketplace_json(&name, &description, skills.as_deref());
            std::fs::write(&json_path, &json).map_err(|e| MindError::io(&json_path, e))?;
            println!("  wrote .claude-plugin/marketplace.json");
        }
    }

    // Templating (INIT-5): rewrite bare sibling mentions to tokens, per file.
    if template {
        let mut total = 0usize;
        for it in &items {
            // Exclude the item's own name so a self-mention is not wrapped.
            let mut sibs = siblings.clone();
            sibs.remove(&it.name);
            for file in crate::review::item_files(it) {
                // {{ns:}} is a prose reference (NS-24); only markdown carries
                // prose. Never templatize scripts/data, where every word is code.
                if file.extension().and_then(|e| e.to_str()) != Some("md") {
                    continue;
                }
                let Ok(content) = std::fs::read_to_string(&file) else {
                    continue; // skip non-UTF-8 / unreadable files
                };
                let (rewritten, n) = crate::namespace::templatize(&content, &sibs);
                if n > 0 {
                    std::fs::write(&file, &rewritten).map_err(|e| MindError::io(&file, e))?;
                    println!("  templated {n} reference(s) in {}", file.display());
                    total += n;
                }
            }
        }
        if total == 0 {
            println!("  no bare references to template");
        }
    }
    Ok(())
}

/// Read all of an item's text files into one buffer, for reference detection.
fn read_item_text(item: &CatalogItem) -> String {
    let mut buf = String::new();
    for file in crate::review::item_files(item) {
        if let Ok(content) = std::fs::read_to_string(&file) {
            buf.push_str(&content);
            buf.push('\n');
        }
    }
    buf
}

/// Run the uninstall hooks declared by the source at `idx` in `registry`.
/// Extracted so both the `--unlink-only` and the default `unmeld` paths can call
/// it without duplicating the logic.
///
/// Returns `Ok(true)` if all hooks were handled (run or skipped) and the caller
/// should proceed with the unmeld. Returns `Ok(false)` if the user chose Abort
/// (the source should be left in place). Returns `Err` on a hook failure
/// (HOOK-53), which also leaves the source in place.
fn run_uninstall_hooks(
    paths: &Paths,
    registry: &Registry,
    idx: usize,
    source_name: &str,
    uninstall_hook: Option<&str>,
    dangerously_skip_hook_check: bool,
) -> Result<bool> {
    let clone_dir = registry.sources[idx].clone_dir(paths);
    let source_pin = registry.sources[idx].pin.clone();
    let source_commit = registry.sources[idx].commit.clone();

    let mindfile = MindToml::load(&clone_dir).unwrap_or_default();
    let toml_path = clone_dir.join("mind.toml");
    let resolved = mindfile
        .as_ref()
        .map(|m| m.resolved_hooks(&toml_path))
        .transpose()?
        .unwrap_or_default();

    // HOOK-59: `--uninstall-hook <cmd>` replaces the source's declared
    // uninstall hooks with one required uninstall hook, shown loudly.
    let (resolved, replaced) =
        crate::hook::apply_hook_override(resolved, uninstall_hook, HookEvent::Uninstall);
    let override_cmd = uninstall_hook.map(str::trim).filter(|s| !s.is_empty());
    let replaced_note = replaced.map(|cmds| cmds.join("; "));

    let pin_desc = pin_description(&source_pin);
    let commit = source_commit.unwrap_or_default();
    let clone_path = clone_dir.display().to_string();

    for h in resolved.iter().filter(|h| h.event == HookEvent::Uninstall) {
        // Show the loud override note on the hook that replaced declared ones.
        let declared_override = match (&replaced_note, override_cmd) {
            (Some(note), Some(cmd)) if h.run == cmd => Some(note.as_str()),
            _ => None,
        };
        let disclosure = crate::hook::hook_disclosure_text(
            h.label(),
            h.optional,
            source_name,
            &pin_desc,
            &commit,
            &clone_path,
            &h.run,
            declared_override,
        );

        match crate::hook::decide(&disclosure, h.optional, dangerously_skip_hook_check)? {
            crate::hook::HookAct::Run => {
                // HOOK-60: indicate the running hook.
                println!("running uninstall hook '{}' for {}", h.label(), source_name);
                // HOOK-53: any failure (optional or required) is a hard stop;
                // the unmeld stops and the source remains.
                crate::hook::run_hook(&h.run, &clone_dir, source_name, h.label())?;
            }
            crate::hook::HookAct::Skip => {
                println!(
                    "note: skipped uninstall hook '{}' for {}",
                    h.label(),
                    source_name
                );
            }
            crate::hook::HookAct::Abort => {
                println!("aborted; source left in place");
                return Ok(false);
            }
        }
    }
    Ok(true)
}

/// `mind unmeld <name> [--unlink-only] [--yes] [--dangerously-skip-install-hook-check]`
/// — drop a source. `name` may be the full `owner/repo`, an unambiguous repo
/// basename, or a glob (`*`, `?`, `[`) matched against each source's identity and
/// its trailing-suffix forms (CLI-28); a glob removes every source it matches,
/// listing them and confirming first when it matches more than one. By default
/// every item installed from a matched source is uninstalled (via its file
/// registry) before the source is removed (CLI-21); `--unlink-only` keeps the
/// items and only removes the source (CLI-22). Runs the source's declared
/// uninstall hooks (HOOK-54) before removal; `dangerously_skip_hook_check`
/// bypasses the prompt. `yes` skips the removal confirmations (CLI-42).
pub fn unmeld(
    paths: &Paths,
    name: &str,
    unlink_only: bool,
    yes: bool,
    dangerously_skip_hook_check: bool,
    uninstall_hook: Option<String>,
) -> Result<()> {
    let out = crate::render::ctx();
    let registry = Registry::load(paths)?;

    // CLI-28: a glob selector permits a multi-source match; every matching source
    // is unmelded. A non-glob selector keeps the exact/unambiguous-suffix
    // semantics of CLI-20 (an ambiguous suffix is still `AmbiguousSource`). A
    // malformed glob (`[bad`) reports `InvalidPattern` here rather than silently
    // matching nothing and surfacing as `SourceNotFound`.
    crate::resolve::validate_source_selector(name)?;
    let matched: Vec<usize> = if is_glob(name) {
        registry
            .sources
            .iter()
            .enumerate()
            .filter(|(_, s)| source_matches_glob(&s.name, name))
            .map(|(i, _)| i)
            .collect()
    } else {
        let exact: Vec<usize> = registry
            .sources
            .iter()
            .enumerate()
            .filter(|(_, s)| source_matches(&s.name, name))
            .map(|(i, _)| i)
            .collect();
        match exact.as_slice() {
            [] => {
                return Err(MindError::SourceNotFound {
                    name: name.to_string(),
                });
            }
            [only] => vec![*only],
            many => {
                return Err(MindError::AmbiguousSource {
                    query: name.to_string(),
                    candidates: many
                        .iter()
                        .map(|i| registry.sources[*i].name.clone())
                        .collect(),
                });
            }
        }
    };

    if matched.is_empty() {
        return Err(MindError::SourceNotFound {
            name: name.to_string(),
        });
    }

    // CLI-28: when a glob matches more than one source, list the matched sources
    // and confirm before removing them (CLI-42's multi-item confirmation, applied
    // at source granularity). `--yes` skips it; a non-TTY run without `--yes`
    // refuses rather than removing silently.
    if matched.len() > 1 && !yes {
        // `--json` is treated as non-interactive: both the human-readable listing
        // and the `confirm(...)` prompt below are gated on `!out.json`, so a JSON
        // run never blocks on a prompt. A non-TTY JSON run without `--yes` still
        // returns ConfirmationRequired (the is_tty check below applies regardless
        // of json), so nothing is removed without an explicit `--yes`; the prompt
        // is intentionally skipped only when an interactive terminal is also JSON.
        if !out.json {
            println!("unmeld would remove {} source(s):", matched.len());
            for i in &matched {
                println!("  {} {}", out.warn(), registry.sources[*i].name);
            }
        }
        if !crate::hook::is_tty() {
            return Err(MindError::ConfirmationRequired {
                action: format!("unmelding {} sources", matched.len()),
            });
        }
        if !out.json && !confirm("remove these source(s)?")? {
            println!("cancelled; nothing removed");
            return Ok(());
        }
    }

    // Removing a source mutates `registry.sources` indices, so resolve each
    // matched source by its name up front and unmeld them one at a time. When the
    // glob matched several sources we already confirmed above at source
    // granularity, so the per-source item-count confirmation is suppressed (`yes`);
    // a single match still gets its own item-count confirmation (CLI-21).
    let multi = matched.len() > 1;
    let names: Vec<String> = matched
        .iter()
        .map(|i| registry.sources[*i].name.clone())
        .collect();
    drop(registry);
    for source_name in names {
        unmeld_one(
            paths,
            &source_name,
            unlink_only,
            yes || multi,
            dangerously_skip_hook_check,
            uninstall_hook.as_deref(),
        )?;
    }
    Ok(())
}

/// Tear down a single melded source by its full identity, the per-source body
/// shared by `unmeld` (CLI-21/CLI-22). It removes the source's installed items
/// (each via its file registry) before the source itself, preserving the HOOK-87
/// order (item uninstall hooks before the source's). The multi-source/multi-item
/// confirmation (CLI-42) is the caller's responsibility; this body does not
/// re-prompt for the item count.
fn unmeld_one(
    paths: &Paths,
    source_name: &str,
    unlink_only: bool,
    yes: bool,
    dangerously_skip_hook_check: bool,
    uninstall_hook: Option<&str>,
) -> Result<()> {
    let out = crate::render::ctx();
    let mut registry = Registry::load(paths)?;
    let idx = match registry.sources.iter().position(|s| s.name == source_name) {
        Some(i) => i,
        None => {
            return Err(MindError::SourceNotFound {
                name: source_name.to_string(),
            });
        }
    };
    let source_name = source_name.to_string();

    // The items installed from this source (effective-name keys).
    let mut manifest = Manifest::load(paths)?;
    let item_keys: Vec<String> = manifest
        .items
        .values()
        .filter(|it| it.source == source_name)
        .map(|it| it.key())
        .collect();

    // CLI-22: `--unlink-only` removes only the source, leaving its items in place,
    // and lists them with the command to remove them later. Uninstall hooks still
    // run on this path (before the source is removed), since the unlink-only path
    // has no multi-item confirmation to worry about.
    if unlink_only {
        let proceed = run_uninstall_hooks(
            paths,
            &registry,
            idx,
            &source_name,
            uninstall_hook,
            dangerously_skip_hook_check,
        )?;
        if !proceed {
            // User aborted the unmeld via the hook prompt; source stays.
            return Ok(());
        }

        let source = registry.sources.remove(idx);
        // A local source's directory is the user's working tree -- never delete it.
        let dir = source.clone_dir(paths);
        if !source.is_linked() && dir.exists() {
            std::fs::remove_dir_all(&dir).map_err(|e| MindError::io(&dir, e))?;
        }
        registry.save(paths)?;
        if out.json {
            let mut result = MutationResult::new("unmeld", &source_name, "unlinked");
            result.count = Some(item_keys.len());
            return print_json(&result);
        }
        if item_keys.is_empty() {
            println!("{} unmelded {source_name}", out.ok());
        } else {
            println!(
                "{} unmelded {source_name}; {} item(s) remain installed:",
                out.ok(),
                item_keys.len()
            );
            for k in &item_keys {
                println!("  {} {k}", out.bullet());
            }
            println!("run `mind forget '{source_name}#*'` to remove them");
        }
        return Ok(());
    }

    // CLI-21: default -- uninstall every item from this source, then remove it.
    // The multi-item confirmation (CLI-42) happens BEFORE uninstall hooks run, so
    // a user who declines does not trigger destructive cleanup (HOOK-54).
    // `--yes` skips the confirmation; a non-TTY run without `--yes` refuses.
    if item_keys.len() > 1 && !yes {
        if !out.json {
            println!(
                "unmelding {source_name} will remove {} installed item(s):",
                item_keys.len()
            );
            for k in &item_keys {
                println!("  {} {k}", out.warn());
            }
        }
        if !crate::hook::is_tty() {
            return Err(MindError::ConfirmationRequired {
                action: format!(
                    "unmelding {source_name} (removing {} items)",
                    item_keys.len()
                ),
            });
        }
        if !out.json && !confirm("remove these item(s) and unmeld the source?")? {
            println!("cancelled; nothing removed");
            return Ok(());
        }
    }

    // HOOK-87: teardown reverses install -- each item's uninstall hooks run
    // BEFORE the source's uninstall hooks. The end-to-end order is
    //   confirm (CLI-42, above) -> item.uninstall* -> source.uninstall -> remove.
    // The source stays in the registry through both hook phases so the clone
    // (and its catalog) remain available; it is removed only after both succeed.
    //
    // HOOK-82: each removed item's uninstall hooks (when declared) run before its
    // files are removed. The clone still exists here, so its catalog supplies the
    // commands. A hook failure leaves the source melded (mirroring HOOK-54).
    let source_ref = &registry.sources[idx];
    let mut item_catalog: Vec<CatalogItem> = Vec::new();
    let _ = catalog::scan_source(paths, source_ref, &mut item_catalog);
    let commit = source_ref.commit.clone().unwrap_or_default();
    let mut forgotten = 0;
    for key in &item_keys {
        if let Some(item) = manifest.items.remove(key) {
            let uninstall_hooks: Vec<&crate::mindfile::ResolvedHook> =
                item_catalog_match(&item_catalog, &item)
                    .map(|c| c.uninstall_hooks())
                    .unwrap_or_default();
            if let Err(e) = uninstall_item(
                paths,
                &item,
                &uninstall_hooks,
                &commit,
                dangerously_skip_hook_check,
            ) {
                // A hook failed: persist what was removed and the surviving item,
                // and stop (the source itself stays melded, mirroring HOOK-54).
                manifest.items.insert(key.clone(), item);
                manifest.save(paths)?;
                registry.save(paths)?;
                return Err(e);
            }
            forgotten += 1;
        }
    }
    manifest.save(paths)?;

    // HOOK-54/87: the source's uninstall hooks run AFTER every item has been
    // removed, still in the clone, before the clone and registry entry are
    // dropped. Non-TTY: skip with a note; dangerously_skip_hook_check runs them
    // unattended. An abort or required-hook failure leaves the source melded.
    let proceed = run_uninstall_hooks(
        paths,
        &registry,
        idx,
        &source_name,
        uninstall_hook,
        dangerously_skip_hook_check,
    )?;
    if !proceed {
        // User aborted the source uninstall hook; source stays (items already
        // removed are kept removed, mirroring a partial teardown).
        registry.save(paths)?;
        return Ok(());
    }

    let source = registry.sources.remove(idx);
    // A local source's directory is the user's working tree -- never delete it.
    let dir = source.clone_dir(paths);
    if !source.is_linked() && dir.exists() {
        std::fs::remove_dir_all(&dir).map_err(|e| MindError::io(&dir, e))?;
    }
    registry.save(paths)?;
    if out.json {
        let mut result = MutationResult::new("unmeld", &source_name, "removed");
        result.count = Some(forgotten);
        return print_json(&result);
    }
    println!(
        "{} unmelded {source_name} ({forgotten} installed item(s) removed)",
        out.ok()
    );
    Ok(())
}

/// The dependency-aware plan for a `learn` selection: the rendered dependency
/// tree, whether the closure adds items beyond the explicit selection, and how
/// many items would actually be installed (the install-order length, which
/// excludes already-installed items per DEP-23).
///
/// Computed without installing, so the CLI and the interactive TUI confirm step
/// share one resolution (DEP-21): the TUI calls [`learn_preview`] for its tree.
// Consumed by the interactive TUI confirm step (DEP-40), which lands in a
// sibling change; allow until that wiring uses it.
#[allow(dead_code)]
pub struct LearnPlan {
    pub tree: String,
    pub adds_dependencies: bool,
    pub install_count: usize,
}

/// Resolve a `learn` selection (loading the registry, scanning the catalog, and
/// running the dependency closure) without installing anything. Returns the
/// catalog, the registry, and the [`crate::deps::Resolution`] so both `learn`
/// and `learn_preview` share one computation.
fn resolve_learn(
    paths: &Paths,
    item_ref: &str,
) -> Result<(Registry, Vec<CatalogItem>, crate::deps::Resolution)> {
    let registry = Registry::load(paths)?;
    let items = catalog::scan(paths, &registry)?;
    let parsed = parse_item_ref(item_ref)?;

    // A glob selects every match; an exact ref must resolve to exactly one.
    let targets: Vec<&CatalogItem> = if is_glob(&parsed.name) {
        let matches = select(&items, &parsed);
        if matches.is_empty() {
            return Err(MindError::ItemNotFound {
                query: parsed.name.clone(),
                sources: registry.sources.len(),
            });
        }
        matches
    } else {
        vec![resolve(&items, &parsed, registry.sources.len())?]
    };

    // Map the explicitly selected items back to indices into `items` (by
    // identity: a CatalogItem is a unique (source, kind, name)).
    let selected_idx: Vec<usize> = targets
        .iter()
        .filter_map(|t| {
            items
                .iter()
                .position(|c| c.kind == t.kind && c.name == t.name && c.source == t.source)
        })
        .collect();

    // What is already installed (manifest keys are `CatalogItem::key()` form).
    let manifest = Manifest::load(paths)?;
    let installed: HashSet<String> = manifest.items.keys().cloned().collect();

    // The `read` closure feeds each item's concatenated UTF-8 text to the
    // resolver so it can scan for `{{ns:}}` tokens (DEP-1).
    let read = |item: &CatalogItem| -> String {
        let mut parts: Vec<String> = Vec::new();
        for file in crate::review::item_files(item) {
            if let Ok(content) = std::fs::read_to_string(&file) {
                parts.push(content);
            }
        }
        parts.join("\n")
    };

    let resolution = crate::deps::resolve(&items, &selected_idx, &installed, read);
    Ok((registry, items, resolution))
}

/// Resolve a `learn` selection's dependency closure without installing it
/// (DEP-21). Used by the CLI dry-run/prompt path and by the interactive TUI's
/// confirm step so both compute identical trees.
// Consumed by the interactive TUI confirm step (DEP-40); allow until wired.
#[allow(dead_code)]
pub fn learn_preview(paths: &Paths, item_ref: &str) -> Result<LearnPlan> {
    let (_registry, items, resolution) = resolve_learn(paths, item_ref)?;
    Ok(LearnPlan {
        tree: resolution.render_tree(&items),
        adds_dependencies: resolution.adds_dependencies(),
        install_count: resolution.install_order().len(),
    })
}

/// `mind learn <item> [--dry-run] [--yes]` — install one item, its
/// intra-source dependency closure (DEP-30), or many via a glob.
/// How to handle a link target that already exists and is not mind's own
/// (the clobber guard, LIFE-41), encountered during install.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Clobber {
    /// Refuse and surface `LinkOccupied` (the default; used by the TUI, which
    /// shows the error in the UI rather than reading a terminal prompt).
    Error,
    /// On a TTY, prompt to overwrite the conflicting target; otherwise refuse.
    Prompt,
    /// Overwrite the conflicting target without asking (`--force`).
    Force,
}

/// The install-time options that travel together through the learn/meld chain:
/// whether to skip confirmation (`yes`), how to treat an occupied link target
/// (`clobber`), and whether to run install hooks unattended (`dangerously_skip`).
#[derive(Clone, Copy)]
pub struct InstallFlow {
    pub yes: bool,
    pub clobber: Clobber,
    pub dangerously_skip: bool,
}

pub fn learn(paths: &Paths, item_ref: &str, dry_run: bool, flow: InstallFlow) -> Result<()> {
    let InstallFlow {
        yes,
        clobber,
        dangerously_skip,
    } = flow;
    // POL-3: load the managed policy once (fail closed on Err; None = inert).
    let policy = Policy::load()?;
    let out = crate::render::ctx();
    let (registry, items, resolution) = resolve_learn(paths, item_ref)?;

    // The full closure to install, dependency-first (DEP-21, DEP-30), excluding
    // already-installed items (DEP-23).
    let order = resolution.install_order();
    let closure: Vec<&CatalogItem> = order.iter().map(|&i| &items[i]).collect();

    // CLI-157: empty closure means every requested item is already installed.
    // Treat as a distinct no-op rather than being silent or claiming "installed".
    if closure.is_empty() && !dry_run {
        if out.json {
            return print_json(&MutationResult::new("learn", item_ref, "up-to-date"));
        }
        println!("already installed; nothing to do");
        return Ok(());
    }

    // DEP-30: the collision check (CLI-33) runs over the FULL closure, not just
    // the explicit selection, so two items that would clobber each other abort
    // before anything is installed.
    if let Some((key, sources)) = colliding_install(&closure) {
        return Err(MindError::AmbiguousItem {
            query: key,
            candidates: sources,
        });
    }

    // DEP-32: --dry-run renders the dependency tree (when deps were added) and
    // lists the full closure, installing nothing.
    if dry_run {
        if out.json {
            let mut result = MutationResult::new("learn", item_ref, "dry-run");
            result.installed = closure.iter().map(|t| t.key()).collect();
            return print_json(&result);
        }
        if resolution.adds_dependencies() {
            print!("{}", resolution.render_tree(&items));
        }
        println!("would learn {} item(s):", closure.len());
        let rows = closure
            .iter()
            .map(|t| vec![t.key(), t.source.clone()])
            .collect::<Vec<_>>();
        out.print_rows(&rows);
        return Ok(());
    }

    // DEP-31: when the closure adds items beyond the explicit selection, show the
    // tree and prompt; proceed only on a yes (or `--yes`). When it adds nothing,
    // install directly with no prompt and no tree (CLI-30 behavior unchanged).
    if resolution.adds_dependencies() && !yes && !out.json {
        print!("{}", resolution.render_tree(&items));
        if !confirm("install this dependency closure?")? {
            println!("cancelled; nothing installed");
            return Ok(());
        }
    }

    // Install each item in dependency-first order. If one fails mid-batch, stop
    // but still persist the items already installed, so the manifest always
    // matches what is on disk.
    let mut manifest = Manifest::load(paths)?;
    let mut failure = None;
    let mut installed_keys: Vec<String> = Vec::new();
    for target in &closure {
        // POL-12: with the allowlist locked, skip (and report) any item whose
        // source identity is no longer allowed; install from the rest.
        if let Some(policy) = policy.as_ref()
            && policy.lock()
            && !policy.allow_matches(&target.source)
        {
            if !out.json {
                println!(
                    "{} skipping {} from {}: source not permitted by the managed policy's allowlist",
                    out.warn(),
                    target.key(),
                    target.source
                );
            }
            continue;
        }
        let commit = match registry.find(&target.source) {
            Some(s) => s.commit.clone().unwrap_or_default(),
            None => {
                failure = Some(MindError::SourceNotFound {
                    name: target.source.clone(),
                });
                break;
            }
        };
        // spec: NS-41 -- refuse to install an agent whose bare harness name
        // already maps to an installed agent from a different source.
        if let Some(err) = agent_collision(paths, &manifest, target)? {
            failure = Some(err);
            break;
        }
        let siblings = siblings_of(&items, &target.source);
        let force = clobber == Clobber::Force;
        let mut result = install_item(paths, target, &commit, &siblings, force, dangerously_skip);
        // CLI-34: a conflicting (non-mind) target refuses by default. With
        // `Prompt` (the default `learn`), offer to overwrite it on a TTY; on a
        // yes, retry forced. `install` aborts before touching anything on a
        // clobber, so the retry is safe.
        if let Err(MindError::LinkOccupied { path }) = &result
            && clobber == Clobber::Prompt
            && crate::hook::is_tty()
            && !out.json
        {
            let path = path.clone();
            result = if confirm(&format!(
                "{path} exists and is not managed by mind; overwrite it?"
            ))? {
                install_item(paths, target, &commit, &siblings, true, dangerously_skip)
            } else {
                Err(MindError::LinkOccupied { path })
            };
        }
        match result {
            Ok(installed) => {
                installed_keys.push(installed.key());
                if !out.json {
                    // Keep the line starting with "learned <key>" (tests assert the
                    // prefix); the commit is greened (no-op when color is off).
                    println!(
                        "learned {} from {} ({})",
                        installed.key(),
                        installed.source,
                        out.green(&short(&installed.commit))
                    );
                }
                manifest.insert(installed);
            }
            Err(e) => {
                failure = Some(e);
                break;
            }
        }
    }
    manifest.save(paths)?;
    match failure {
        Some(e) => Err(e),
        None => {
            if out.json {
                let mut result = MutationResult::new("learn", item_ref, "installed");
                result.installed = installed_keys;
                return print_json(&result);
            }
            Ok(())
        }
    }
}

/// Like `learn()` but installs silently and returns the installed keys instead
/// of emitting a JSON result. Used by `install_source_items_for_json` so the
/// meld dispatcher can fold the install outcome into ONE combined JSON object
/// (CLI-156) rather than letting `learn` emit its own separate result.
///
/// Differences from `learn()`:
/// - `dry_run` is never true (callers always want the real install).
/// - No JSON is emitted at the end; the caller receives the keys.
/// - The dep-prompt is skipped (callers always pass `yes=true` here).
fn learn_collecting(paths: &Paths, item_ref: &str, flow: InstallFlow) -> Result<Vec<String>> {
    let InstallFlow {
        clobber,
        dangerously_skip,
        ..
    } = flow;
    let policy = Policy::load()?;
    let (registry, items, resolution) = resolve_learn(paths, item_ref)?;

    let order = resolution.install_order();
    let closure: Vec<&CatalogItem> = order.iter().map(|&i| &items[i]).collect();

    // Already all installed: nothing to collect.
    if closure.is_empty() {
        return Ok(vec![]);
    }

    if let Some((key, sources)) = colliding_install(&closure) {
        return Err(MindError::AmbiguousItem {
            query: key,
            candidates: sources,
        });
    }

    let mut manifest = Manifest::load(paths)?;
    let mut failure = None;
    let mut installed_keys: Vec<String> = Vec::new();
    for target in &closure {
        if let Some(policy) = policy.as_ref()
            && policy.lock()
            && !policy.allow_matches(&target.source)
        {
            continue; // policy-blocked items are silently skipped in collect mode
        }
        let commit = match registry.find(&target.source) {
            Some(s) => s.commit.clone().unwrap_or_default(),
            None => {
                failure = Some(MindError::SourceNotFound {
                    name: target.source.clone(),
                });
                break;
            }
        };
        // spec: NS-41 -- refuse to install a colliding agent (same check as learn).
        if let Some(err) = agent_collision(paths, &manifest, target)? {
            failure = Some(err);
            break;
        }
        let siblings = siblings_of(&items, &target.source);
        let force = clobber == Clobber::Force;
        let result = install_item(paths, target, &commit, &siblings, force, dangerously_skip);
        match result {
            Ok(installed) => {
                installed_keys.push(installed.key());
                manifest.insert(installed);
            }
            Err(e) => {
                failure = Some(e);
                break;
            }
        }
    }
    manifest.save(paths)?;
    match failure {
        Some(e) => Err(e),
        None => Ok(installed_keys),
    }
}

/// After a `meld`, offer to install the newly melded source's items (CLI-23).
/// This is the interactive form of `learn '<source>#*'`: it previews the items
/// that would be installed and prompts, then installs the whole source on a yes.
/// `--link-only` skips this entirely (the caller does not invoke it). A source
/// with no installable items (e.g. a curated super-source) is a no-op.
///
/// With `yes`, it installs without prompting (and in a non-TTY context). Without
/// `yes` in a non-TTY context it installs nothing and prints how to install
/// later, mirroring the install-hook non-TTY behavior (HOOK-22): a scripted meld
/// stays register-only unless `--yes` is given.
// spec: CLI-23
pub fn install_melded_source(paths: &Paths, repo: &str, flow: InstallFlow) -> Result<()> {
    install_source_items(paths, &parse_spec(repo)?.name, flow)
}

/// Run the post-meld auto-install flow (CLI-23) for one registered source by its
/// name: preview and prompt to install its items (`<source>#*`), or install
/// directly under `--yes`. Used for the top-level source and, via
/// `install_curated_sources`, for nested sources installed with `--recursive`
/// (DSC-55) or a curator `install = true` (DSC-58).
pub fn install_source_items(paths: &Paths, source_name: &str, flow: InstallFlow) -> Result<()> {
    let item_ref = format!("{source_name}#*");

    // Resolve what would install (excludes already-installed items, DEP-23). A
    // source that offers nothing matching is an ItemNotFound here; treat it as
    // "nothing to install" rather than an error.
    let plan = match learn_preview(paths, &item_ref) {
        Ok(plan) => plan,
        Err(MindError::ItemNotFound { .. }) => return Ok(()),
        Err(e) => return Err(e),
    };
    if plan.install_count == 0 {
        return Ok(());
    }

    if flow.yes {
        return learn(paths, &item_ref, false, flow);
    }
    if !crate::hook::is_tty() {
        if !json_mode() {
            println!(
                "note: {source_name} has {} item(s) to install; run `mind learn '{item_ref}'` (or re-meld with --yes)",
                plan.install_count
            );
        }
        return Ok(());
    }

    // Interactive: show the install preview (the dry-run list), then prompt.
    learn(paths, &item_ref, true, flow)?;
    if confirm_default_yes(&format!(
        "install these {} item(s) now?",
        plan.install_count
    ))? {
        learn(paths, &item_ref, false, InstallFlow { yes: true, ..flow })
    } else {
        println!("skipped; run `mind learn '{item_ref}'` to install later");
        Ok(())
    }
}

/// Run the post-meld install flow (CLI-23) for a named subset of a registered
/// source's items (DSC-62). Only the items named by `bare_refs` (bare `kind:name`
/// strings in source truth) are offered; the source's other items remain
/// registered and available. The same preview-and-prompt path as
/// `install_source_items` is used, so `--yes` and `--link-only` behave
/// identically (CLI-23). An empty `bare_refs` slice installs nothing.
pub fn install_source_items_subset(
    paths: &Paths,
    source_name: &str,
    bare_refs: &[String],
    flow: InstallFlow,
) -> Result<()> {
    if bare_refs.is_empty() {
        return Ok(());
    }

    // Scan only the named source to get its items.
    let registry = Registry::load(paths)?;
    let Some(source) = registry.find(source_name) else {
        return Ok(());
    };
    let source_items = catalog::scan(paths, &single(source))?;

    // Filter to only the listed bare refs.
    let subset: Vec<&CatalogItem> = select_by_bare_refs(&source_items, bare_refs);
    if subset.is_empty() {
        return Ok(());
    }

    // Build a manifest of already-installed keys to exclude them (DEP-23).
    let manifest = crate::manifest::Manifest::load(paths)?;
    let installed_keys: std::collections::HashSet<String> =
        manifest.items.keys().cloned().collect();

    // Filter to not-yet-installed items only.
    let to_install: Vec<&CatalogItem> = subset
        .into_iter()
        .filter(|it| !installed_keys.contains(&it.key()))
        .collect();

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

    // Build a ref string that installs exactly the subset. We install each
    // item individually using the source-qualified effective name, reusing the
    // same preview-and-prompt gate that `install_source_items` uses.
    //
    // Collect effective names so the prompt message is accurate.
    let count = to_install.len();
    let refs: Vec<String> = to_install
        .iter()
        .map(|it| format!("{source_name}#{}", it.key()))
        .collect();

    if flow.yes {
        for item_ref in &refs {
            learn(paths, item_ref, false, flow)?;
        }
        return Ok(());
    }

    if !crate::hook::is_tty() {
        let ref_list = refs.join(", ");
        if !json_mode() {
            println!(
                "note: {source_name} has {count} item(s) to install; run `mind learn '{}'` (or re-meld with --yes)",
                if refs.len() == 1 {
                    refs[0].clone()
                } else {
                    format!("{source_name}#*")
                }
            );
            let _ = ref_list; // suppress unused warning
        }
        return Ok(());
    }

    // Interactive: preview, then prompt.
    for item_ref in &refs {
        learn(paths, item_ref, true, flow)?;
    }
    if confirm_default_yes(&format!("install these {count} item(s) now?"))? {
        for item_ref in &refs {
            learn(paths, item_ref, false, InstallFlow { yes: true, ..flow })?;
        }
    } else {
        println!("skipped; run `mind learn '{source_name}#*'` to install later");
    }
    Ok(())
}

/// True when the repo spec resolves to an already-registered source.
pub fn is_melded(paths: &Paths, repo: &str) -> Result<bool> {
    let name = parse_spec(repo)?.name;
    Ok(Registry::load(paths)?.find(&name).is_some())
}

/// Re-melding an already-melded source (CLI-12). It does not re-clone or
/// re-register: it ensures the source's items are installed, installing any that
/// are missing just as a fresh meld does (CLI-23), and otherwise (or with
/// `--link-only`) prints a status of the source's items and the commit each is
/// installed at.
// spec: CLI-12
pub fn remeld(
    paths: &Paths,
    repo: &str,
    alias: Option<String>,
    link_only: bool,
    flow: InstallFlow,
    recursive: bool,
) -> Result<()> {
    // `yes` rides inside `flow` for the install calls; remeld itself only needs
    // the clobber (hook force-rerun) and the dangerously-skip flag.
    let InstallFlow {
        clobber,
        dangerously_skip: dangerously_skip_hook_check,
        ..
    } = flow;
    let out = crate::render::ctx();
    let source_name = parse_spec(repo)?.name;
    if !out.json {
        println!("{} {source_name} is already melded", out.bullet());
    }

    // CLI-161/NS-30: an explicit `--namespace` (or deprecated `--as`) on a
    // re-meld sets the source's namespace, but only while no items are
    // installed. If items are installed and the alias differs, return an error
    // naming them and directing the user to `forget` them first.
    if alias.is_some() {
        set_source_namespace(paths, &source_name, alias)?;
        if !out.json {
            println!("prefix updated; no installed items to rename");
        }
    }

    // HOOK-60: re-offer the source's install hooks that have not run at the
    // current commit (a hook skipped at an earlier meld, or added since); `--force`
    // re-offers every install hook. Runs in the existing clone before installing.
    {
        let mut registry = Registry::load(paths)?;
        if let Some(idx) = registry.sources.iter().position(|s| s.name == source_name) {
            let clone_dir = registry.sources[idx].clone_dir(paths);
            let mindfile = MindToml::load(&clone_dir).unwrap_or_default();
            let toml_path = clone_dir.join("mind.toml");
            let force_rerun = clobber == Clobber::Force;
            match run_install_hooks(
                &mut registry.sources[idx],
                &clone_dir,
                &mindfile,
                &toml_path,
                None,
                dangerously_skip_hook_check,
                force_rerun,
                Vec::new(),
            ) {
                Ok(HookOutcome::Proceed) => registry.save(paths)?,
                Ok(HookOutcome::Abort) => {
                    registry.save(paths)?; // persist any hook that did run
                    if !out.json {
                        println!("aborted; source left in place");
                    }
                    return Ok(());
                }
                Err(e) => return Err(e), // a hook failed; leave the source melded
            }
        }
    }

    if !link_only {
        let item_ref = format!("{source_name}#*");
        let to_install = match learn_preview(paths, &item_ref) {
            Ok(plan) => plan.install_count,
            Err(MindError::ItemNotFound { .. }) => 0,
            Err(e) => return Err(e),
        };
        if to_install > 0 {
            install_melded_source(paths, repo, flow)?;
            // Install the curated chain: every nested source with `--recursive`
            // (DSC-55), or just the curator's `install = true` entries (DSC-58).
            // The nested sources are already registered, so nothing re-registers.
            install_curated_sources(paths, &source_name, recursive, flow)?;
            return Ok(());
        }
        // A pure super-source has no own items; still install the curated chain
        // (all of it with --recursive, else the `install = true` entries).
        install_curated_sources(paths, &source_name, recursive, flow)?;
        if recursive {
            return Ok(());
        }
    }
    if out.json {
        return print_json(&MutationResult::new("meld", &source_name, "already-melded"));
    }
    source_status(paths, &source_name)
}

/// Install the items of the registered sources a super-source curates, walking
/// its transitive `[discover].sources` chain. The whole chain is always traversed
/// (so a deeper `install = true` or `install-items` is reached), but a given
/// nested source's items are offered for install only when:
///
/// - `all` is set (`meld --recursive`, DSC-55): install everything, or
/// - the entry has `install-items = [...]` (DSC-62): install exactly that subset, or
/// - the entry has `install = true` (DSC-58): install all of the nested source.
///
/// When `install-items` is present it governs; when absent `install` governs.
/// Reads each source's clone `mind.toml`; cycle-safe via a visited set; only
/// touches registered sources.
pub fn install_curated_sources(
    paths: &Paths,
    super_name: &str,
    all: bool,
    flow: InstallFlow,
) -> Result<()> {
    let registry = Registry::load(paths)?;
    let mut visited: HashSet<String> = HashSet::from([super_name.to_string()]);
    let mut queue: Vec<String> = vec![super_name.to_string()];
    while let Some(name) = queue.pop() {
        let Some(source) = registry.find(&name) else {
            continue;
        };
        let nested = MindToml::load(&source.clone_dir(paths))?
            .and_then(|m| m.discover)
            .map(|d| d.sources)
            .unwrap_or_default();
        for ns in nested {
            let Ok(spec) = parse_spec(&ns.source) else {
                continue;
            };
            if !visited.insert(spec.name.clone()) {
                continue; // already seen (cycle guard / diamond dedup)
            }
            if registry.find(&spec.name).is_some() {
                // Traverse every nested source, but install according to the
                // directive in effect (DSC-55 > DSC-62 > DSC-58):
                // - `all` (--recursive): install everything
                // - `install_items` Some(list): install exactly that subset
                //   (empty list = install nothing, like install = false)
                // - `install = true`: install all of the nested source
                if all {
                    install_source_items(paths, &spec.name, flow)?;
                } else if let Some(refs) = &ns.install_items {
                    // DSC-62: install_items governs; refs is the subset to offer.
                    install_source_items_subset(paths, &spec.name, refs, flow)?;
                } else if ns.install {
                    // DSC-58: install all of this nested source.
                    install_source_items(paths, &spec.name, flow)?;
                }
                queue.push(spec.name);
            }
        }
        // MKT-7: a marketplace catalog is a curated super-source too. Its in-repo
        // plugins are offered for install on meld like the catalog's own items
        // (CLI-23); its external plugins are register-only unless `all`
        // (--recursive, DSC-55), mirroring the DSC-54 default for nested sources.
        for (spec, in_repo) in marketplace_subsources(paths, source)? {
            if !visited.insert(spec.name.clone()) {
                continue;
            }
            if registry.find(&spec.name).is_some() {
                if all || in_repo {
                    install_source_items(paths, &spec.name, flow)?;
                }
                queue.push(spec.name);
            }
        }
    }
    Ok(())
}

/// Resolve the marketplace sub-sources a source curates (MKT-7): each
/// `.claude-plugin/marketplace.json` entry mapped to `(parsed source spec,
/// is_in_repo)`. Empty when the source has no marketplace manifest or an
/// authoritative `mind.toml` suppresses it (MKT-2). In-repo entries install by
/// default; external entries are register-only unless `--recursive`.
fn marketplace_subsources(
    paths: &Paths,
    source: &crate::source::Source,
) -> Result<Vec<(crate::source::Source, bool)>> {
    let clone = source.clone_dir(paths);
    if MindToml::load(&clone)?.is_some_and(|m| m.is_authoritative()) {
        return Ok(Vec::new());
    }
    let Some(mp) = plugin_manifest::find_marketplace_manifest(&clone) else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for entry in plugin_manifest::load_marketplace_manifest(&mp)?.into_entries() {
        let in_repo = matches!(entry.source, plugin_manifest::PluginSource::InRepo { .. });
        if let Ok(spec) = parse_spec(&marketplace_entry_spec(&entry, &clone)) {
            out.push((spec, in_repo));
        }
    }
    Ok(out)
}

/// Install `source_name`'s items silently (no JSON emitted by `learn`) and
/// return `(installed_keys, pending_count)`. Used in `--json` mode so the
/// meld dispatcher can emit ONE combined JSON object (CLI-156).
///
/// - `flow.yes = true`: installs everything, returns `(keys, 0)`.
/// - `flow.yes = false`: returns `([], N)` where N is the pending item count
///   without prompting (json mode is always non-interactive).
pub(crate) fn install_source_items_for_json(
    paths: &Paths,
    source_name: &str,
    flow: InstallFlow,
) -> Result<(Vec<String>, usize)> {
    let item_ref = format!("{source_name}#*");
    let plan = match learn_preview(paths, &item_ref) {
        Ok(plan) => plan,
        Err(MindError::ItemNotFound { .. }) => return Ok((vec![], 0)),
        Err(e) => return Err(e),
    };
    if plan.install_count == 0 {
        return Ok((vec![], 0));
    }
    if flow.yes {
        let keys = learn_collecting(paths, &item_ref, flow)?;
        return Ok((keys, 0));
    }
    // No --yes in json mode: report the pending count without prompting.
    Ok((vec![], plan.install_count))
}

/// Walk the curated source chain and install each nested source's items
/// silently, returning all installed keys. Mirrors `install_curated_sources`
/// but collects keys instead of printing JSON results, so the meld dispatcher
/// can fold them into ONE combined JSON object (CLI-156).
pub(crate) fn install_curated_sources_for_json(
    paths: &Paths,
    super_name: &str,
    all: bool,
    flow: InstallFlow,
) -> Result<Vec<String>> {
    let registry = Registry::load(paths)?;
    let mut visited: HashSet<String> = HashSet::from([super_name.to_string()]);
    let mut queue: Vec<String> = vec![super_name.to_string()];
    let mut all_keys: Vec<String> = Vec::new();
    while let Some(name) = queue.pop() {
        let Some(source) = registry.find(&name) else {
            continue;
        };
        let nested = MindToml::load(&source.clone_dir(paths))?
            .and_then(|m| m.discover)
            .map(|d| d.sources)
            .unwrap_or_default();
        for ns in nested {
            let Ok(spec) = parse_spec(&ns.source) else {
                continue;
            };
            if !visited.insert(spec.name.clone()) {
                continue;
            }
            if registry.find(&spec.name).is_some() {
                if all {
                    let (keys, _) = install_source_items_for_json(paths, &spec.name, flow)?;
                    all_keys.extend(keys);
                } else if let Some(refs) = &ns.install_items {
                    if !refs.is_empty() && flow.yes {
                        for item_ref in refs {
                            let qualified = format!("{}#{}", spec.name, item_ref);
                            let keys = learn_collecting(paths, &qualified, flow)?;
                            all_keys.extend(keys);
                        }
                    }
                } else if ns.install {
                    let (keys, _) = install_source_items_for_json(paths, &spec.name, flow)?;
                    all_keys.extend(keys);
                }
                queue.push(spec.name);
            }
        }
        // MKT-7: marketplace sub-sources (in-repo install by default, external
        // only under `--recursive`). Mirrors `install_curated_sources`.
        for (spec, in_repo) in marketplace_subsources(paths, source)? {
            if !visited.insert(spec.name.clone()) {
                continue;
            }
            if registry.find(&spec.name).is_some() {
                if all || in_repo {
                    let (keys, _) = install_source_items_for_json(paths, &spec.name, flow)?;
                    all_keys.extend(keys);
                }
                queue.push(spec.name);
            }
        }
    }
    Ok(all_keys)
}

/// Build and emit the single meld JSON result (CLI-153, CLI-156).
///
/// Called by the dispatcher in `main.rs` after both the registration step
/// (`meld()`) and the post-meld install step (`install_source_items_for_json`)
/// have completed, so ONE object covers both outcomes.
///
/// `installed` contains the effective keys installed in this call.
/// `pending` is non-zero when `--yes` was absent and items remain to install.
// spec: CLI-153 CLI-156
pub(crate) fn emit_meld_json_result(
    summary: MeldSummary,
    installed: Vec<String>,
    pending: usize,
) -> Result<()> {
    let mut result = MutationResult::new("meld", &summary.source_name, "melded");
    result.count = Some(summary.added);
    result.skipped = summary.skipped;
    result.installed = installed;
    if pending > 0 {
        result.pending_items = Some(pending);
    }
    print_json(&result)
}

/// Print every item the source offers with its install state and the source
/// commit it was installed from, noting items whose commit lags the source
/// (CLI-12). Items are matched to the manifest by stable identity (source, kind,
/// bare name), so a prefix change does not lose them.
fn source_status(paths: &Paths, source_name: &str) -> Result<()> {
    let out = crate::render::ctx();
    let registry = Registry::load(paths)?;
    let Some(source) = registry.find(source_name) else {
        return Err(MindError::SourceNotFound {
            name: source_name.to_string(),
        });
    };
    let items = catalog::scan(paths, &single(source))?;
    let manifest = Manifest::load(paths)?;

    let head = source
        .commit
        .as_deref()
        .map(short)
        .unwrap_or_else(|| "?".to_string());
    println!(
        "{} {source_name}: {} item(s) (source @ {head})",
        out.bullet(),
        items.len()
    );
    for it in &items {
        let installed = manifest
            .items
            .values()
            .find(|m| m.source == it.source && m.kind == it.kind && m.bare_name == it.name);
        match installed {
            Some(m) => {
                // CLI-75 / LIFE-11: an item is outdated exactly when `upgrade`
                // would act on it -- its source-content hash changed, or its
                // effective name changed (a namespace/prefix rename). A commit
                // advance that did not touch the item's content or name does NOT
                // mark it outdated; `upgrade` would report nothing pending for it.
                //
                // CLI-75: `upgrade` aborts the whole run via `?` when it cannot
                // hash the source content. This best-effort listing marker cannot
                // abort -- it must still print the other rows -- so it errs toward
                // flagging: a hash-computation error counts as drift (outdated)
                // rather than being silently read as "up to date". The same
                // hash-error-counts-as-lag rule is applied at all four marker
                // sites for consistency.
                let hash_lag = hash_path(&it.path).map_or(true, |h| h != m.hash);
                let rename_lag = it.effective_name() != m.name;
                let stale = hash_lag || rename_lag;
                let lag = if stale {
                    out.yellow(" (outdated; run `mind upgrade`)")
                } else {
                    String::new()
                };
                // Stale installs use the ↑ marker, distinct from ✓ for current.
                let marker = if stale { out.stale() } else { out.ok() };
                println!(
                    "  {} {}  installed @ {}{}",
                    marker,
                    it.key(),
                    out.green(&short(&m.commit)),
                    lag
                );
            }
            None => println!(
                "  {} {}  not installed (run `mind learn '{}'`)",
                out.available(),
                it.key(),
                it.key()
            ),
        }
    }
    Ok(())
}

/// Set (or clear) the namespace alias for a source, enforcing the mutability
/// lock (NS-30/CLI-161): the alias may only change while no items from the
/// source are installed. If items are installed and the requested alias differs
/// from the current one, returns `NamespaceLocked` listing those items. When
/// the alias is unchanged nothing is written. Called by `remeld` and exported
/// for the TUI source-details dialog (TUI-53).
pub fn set_source_namespace(
    paths: &Paths,
    source_name: &str,
    new_alias: Option<String>,
) -> Result<()> {
    // NS-25: validate the prefix (validate_prefix accepts None/empty).
    if let Some(ref a) = new_alias {
        crate::namespace::validate_prefix(a)?;
    }
    let mut registry = Registry::load(paths)?;
    let Some(source) = registry.sources.iter_mut().find(|s| s.name == source_name) else {
        return Ok(()); // source not found; nothing to change
    };
    let current = source.alias.clone().unwrap_or_default();
    let requested = new_alias.clone().unwrap_or_default();
    if current == requested {
        return Ok(()); // no change; nothing to do
    }
    // NS-30/CLI-161: check whether any of this source's items are installed.
    let manifest = Manifest::load(paths)?;
    let installed_names: Vec<String> = manifest
        .items
        .values()
        .filter(|it| it.source == source_name)
        .map(|it| it.key())
        .collect();
    if !installed_names.is_empty() {
        return Err(MindError::NamespaceLocked {
            src_name: source_name.to_string(),
            items: installed_names,
        });
    }
    source.alias = new_alias;
    registry.save(paths)
}

/// If two selected items would install under the same `kind:name`, return that
/// key and the sources that collide on it.
fn colliding_install(targets: &[&CatalogItem]) -> Option<(String, Vec<String>)> {
    let mut by_key: std::collections::BTreeMap<String, Vec<String>> = Default::default();
    for t in targets {
        by_key.entry(t.key()).or_default().push(t.source.clone());
    }
    by_key.into_iter().find(|(_, sources)| sources.len() > 1)
}

/// Install one item, then run its install hook (HOOK-81) as the final step. On a
/// hook failure, roll the just-installed item back (remove its links and store
/// copy via the file registry) so it is left not installed, then propagate the
/// error. `dangerously_skip` runs the hook unattended (HOOK-83).
fn install_item(
    paths: &Paths,
    item: &CatalogItem,
    commit: &str,
    siblings: &[CatalogItem],
    force: bool,
    dangerously_skip: bool,
) -> Result<crate::manifest::InstalledItem> {
    let installed = install::install(paths, item, commit, siblings, force)?;
    // HOOK-86: run every resolved install hook in declaration order (the scalar
    // shorthand is folded in as the first required hook). On a hook failure, roll
    // the just-installed item back.
    let install_hooks = item.install_hooks();
    if !install_hooks.is_empty() {
        let store = paths.mind_home.join(&installed.store);
        if let Err(e) =
            install::run_item_install_hooks(item, &install_hooks, &store, commit, dangerously_skip)
        {
            let _ = install::uninstall(paths, &installed);
            return Err(e);
        }
    }
    Ok(installed)
}

/// Run an item's uninstall hooks (HOOK-82, HOOK-86) in declaration order if any
/// are declared, then remove the item via its file registry. `uninstall_hooks`
/// come from the live source catalog (nothing is recorded for them, HOOK-84) and
/// are empty when the source or item is no longer available, in which case removal
/// proceeds with no hook. A hook failure propagates BEFORE removal, leaving the
/// item installed.
fn uninstall_item(
    paths: &Paths,
    item: &crate::manifest::InstalledItem,
    uninstall_hooks: &[&crate::mindfile::ResolvedHook],
    commit: &str,
    dangerously_skip: bool,
) -> Result<()> {
    if !uninstall_hooks.is_empty() {
        let store = paths.mind_home.join(&item.store);
        if store.exists() {
            install::run_item_uninstall_hooks(
                item,
                uninstall_hooks,
                &store,
                commit,
                dangerously_skip,
            )?;
        }
    }
    install::uninstall(paths, item)
}

/// The catalog item matching an installed item by stable identity (source, kind,
/// bare name), used to read its live uninstall hooks (HOOK-82/86; nothing is
/// recorded for them, HOOK-84). `None` when the item is gone from the catalog.
fn item_catalog_match<'a>(
    catalog: &'a [CatalogItem],
    item: &crate::manifest::InstalledItem,
) -> Option<&'a CatalogItem> {
    catalog
        .iter()
        .find(|c| c.kind == item.kind && c.name == item.bare_name && c.source == item.source)
}

/// Derive the convention path for a `(kind, name)` pair within a source root,
/// relative to that root. Used by `absorb` to know where to move an item.
///
/// - skill  -> `skills/<name>/`  (returns a directory path)
/// - agent  -> `agents/<name>.md`
/// - rule   -> `rules/<name>.md`
fn convention_path_in_root(
    root: &std::path::Path,
    kind: ItemKind,
    name: &str,
) -> std::path::PathBuf {
    match kind {
        ItemKind::Skill => root.join("skills").join(name),
        ItemKind::Agent => root.join("agents").join(format!("{name}.md")),
        ItemKind::Rule => root.join("rules").join(format!("{name}.md")),
        ItemKind::Tool => panic!("tools are never unmanaged; absorb should not reach this"),
    }
}

/// Resolve the FIRST effective scan root for a source at `dest_path`.
/// Mirrors catalog.rs ~:208-219 (DSC-50): `[source].roots` in `mind.toml`, or the
/// repo root if unset. Consumer `--root` overrides are not relevant here since
/// the destination may not be melded yet; we use the repo's own declaration.
///
/// The resolved root is checked for containment within `dest_path`. A roots entry
/// like `../../x` that escapes the repo is rejected with [`MindError::InvalidRoot`].
/// The check uses `canonicalize` when both paths exist, and a `..`-folding
/// normalizer otherwise (so the check catches escapes even for a not-yet-created
/// scan root directory).
fn first_scan_root(dest_path: &std::path::Path) -> Result<std::path::PathBuf> {
    let mindfile = crate::mindfile::MindToml::load(dest_path).unwrap_or_default();
    let root_rel = mindfile
        .as_ref()
        .and_then(|m| m.source.roots.as_ref())
        .and_then(|r| r.first())
        .map(String::as_str)
        .unwrap_or(".");
    let candidate = dest_path.join(root_rel);

    // Use canonicalize when both paths exist (resolves symlinks + `..`). When the
    // candidate does not yet exist on disk, fold `..` components logically via
    // `normalize_path` so we still catch escaping roots.
    let canon_dest = std::fs::canonicalize(dest_path).unwrap_or_else(|_| dest_path.to_path_buf());
    let canon_root =
        std::fs::canonicalize(&candidate).unwrap_or_else(|_| normalize_path(&candidate));

    if !canon_root.starts_with(&canon_dest) {
        return Err(MindError::InvalidRoot {
            source_name: dest_path.to_string_lossy().into_owned(),
            root: root_rel.to_string(),
        });
    }
    Ok(candidate)
}

/// Normalize an absolute path by folding `..` components without requiring the
/// path to exist on disk. Used as a fallback when `canonicalize` fails (e.g.
/// the target does not yet exist). Only handles absolute paths; relative paths
/// are returned unchanged.
fn normalize_path(path: &std::path::Path) -> std::path::PathBuf {
    use std::path::Component;
    let mut components: Vec<&std::ffi::OsStr> = Vec::new();
    for comp in path.components() {
        match comp {
            Component::ParentDir => {
                // Pop the last non-root component, if any.
                if components
                    .last()
                    .is_some_and(|c| *c != std::ffi::OsStr::new("/"))
                {
                    components.pop();
                }
            }
            Component::CurDir => {
                // Skip `.` components.
            }
            _ => {
                components.push(comp.as_os_str());
            }
        }
    }
    components.iter().collect()
}

/// Resolve the destination prefix from the source's `mind.toml [source].prefix`
/// (alias/--as is not relevant for absorb since we are looking at the destination
/// source's declared prefix, which determines the effective name after learn).
fn dest_source_prefix(dest_path: &std::path::Path, registry: &Registry) -> Option<String> {
    // If the destination is already melded, use its recorded alias (consumer override)
    // first, then the toml prefix.
    if let Ok(spec) = parse_spec(&dest_path.to_string_lossy())
        && let Some(src) = registry.find(&spec.name)
        && let Some(alias) = src.alias.as_deref().filter(|a| !a.is_empty())
    {
        return Some(alias.to_string());
    }
    let mindfile = crate::mindfile::MindToml::load(dest_path).unwrap_or_default();
    mindfile
        .as_ref()
        .and_then(|m| m.source.prefix.clone())
        .filter(|p| !p.is_empty())
}

/// `mind absorb <ref> [--to <path>] [--force]` — claim a single unmanaged lobe
/// item into a version-controlled source and install it as a managed item.
///
/// This is the constructive inverse of `forget --unmanaged` (UNM-7).
// spec: ABS-1 ABS-2 ABS-3 ABS-4 ABS-5 ABS-6 ABS-7 ABS-8 ABS-9 ABS-10
pub fn absorb(
    paths: &Paths,
    item_ref_str: &str,
    to: Option<String>,
    force: bool,
    yes: bool,
) -> Result<()> {
    let out = crate::render::ctx();

    // ABS-1: reject glob refs before calling resolve (a glob treats the * literally
    // and would fall through to NotInstalled; we want the exact InvalidItemRef error).
    let parsed = parse_item_ref(item_ref_str)?;
    if is_glob(&parsed.name) {
        return Err(MindError::InvalidItemRef {
            name: item_ref_str.to_string(),
        });
    }

    // ABS-1: resolve to a single unmanaged item.
    let manifest = Manifest::load(paths)?;
    let unmanaged_items = crate::unmanaged::scan(paths, &manifest)?;
    let item = crate::unmanaged::resolve(&unmanaged_items, &parsed)?;

    // ABS-1: tools are never unmanaged, but guard anyway.
    if item.kind == ItemKind::Tool {
        return Err(MindError::InvalidItemRef {
            name: item_ref_str.to_string(),
        });
    }

    // ABS-2: resolve destination: --to > MIND_ABSORB_TO > config.absorb_to.
    // ABS-3: if none set, prompt on TTY; non-TTY => ConfirmationRequired.
    let (dest_path, interactive_dest) = resolve_absorb_dest(paths, to, yes)?;

    // ABS-5: destination must be a git repo (or built-in personal that was just
    // created). After resolve_absorb_dest, the personal dir is already git-init'd.
    if !crate::git::is_repo(&dest_path) {
        return Err(MindError::DestinationNotRepo {
            path: dest_path.to_string_lossy().into_owned(),
        });
    }

    // ABS-4: offer to save absorb_to when the destination was resolved interactively.
    if interactive_dest {
        offer_save_absorb_to(paths, &dest_path, yes)?;
    }

    // C5: Compute and validate the convention path relative to the destination's
    // first scan root. first_scan_root now canonicalizes and checks containment.
    let scan_root = first_scan_root(&dest_path)?;
    let dest_item_path = convention_path_in_root(&scan_root, item.kind, &item.name);

    // ABS-6: check for a collision at the destination convention path.
    if dest_item_path.exists() && !force {
        return Err(MindError::AbsorbCollision {
            kind: item.kind.as_str().to_string(),
            name: item.name.clone(),
            dest_path: dest_item_path.to_string_lossy().into_owned(),
        });
    }

    // --- ABS-7 prompt (BEFORE moving/deleting anything) ---
    // One item may occupy multiple lobes. We absorb from the FIRST recorded path.
    // The remaining paths are "stray copies" that will be replaced by the managed
    // link after learn. We must remove them first (so learn can place the link).
    let source_lobe_path = item
        .paths
        .first()
        .ok_or_else(|| MindError::NotInstalled { name: item.key() })?
        .clone();
    let stray_paths: Vec<&std::path::PathBuf> = item.paths.iter().skip(1).collect();

    if !yes {
        // Print what we will do.
        if !out.json {
            println!("absorb will:");
            println!(
                "  move  {} -> {}",
                source_lobe_path.display(),
                dest_item_path.display()
            );
            for stray in &stray_paths {
                println!("  delete (stray copy) {}", stray.display());
            }
        }
        // C3 / ABS-7: json mode is non-interactive; treat it like non-TTY for
        // the destructive confirmation. A missing --yes refuses with
        // ConfirmationRequired regardless of whether a real TTY is attached.
        if !crate::hook::is_tty() || out.json {
            return Err(MindError::ConfirmationRequired {
                action: format!("absorbing {}", item.key()),
            });
        }
        if !confirm("proceed with absorb?")? {
            println!("cancelled; nothing changed");
            return Ok(());
        }
    }

    // --- ABS-10: transactional destructive operations begin here ---
    //
    // The invariant: if anything fails before learn completes, the original
    // lobe entry must be restored exactly as it was and the manifest left
    // unchanged. We mirror the staging/backup pattern from src/install.rs:
    //
    //  1. Copy the lobe item into the destination convention path (do NOT
    //     remove the original yet; the original is still in the lobe).
    //  2. git add_all + commit in dest.
    //  3. meld dest if not yet registered.
    //  4. Stash a backup copy of the lobe item so we can restore it.
    //  5. Remove the original lobe entry (making room for learn's symlink).
    //  6. learn the item. On failure, restore the backup to source_lobe_path.
    //  7. On success, drop the backup; stray copies in other lobes were
    //     replaced by learn's managed symlinks (Clobber::Force).

    // 1. Copy lobe item to dest convention path.
    if let Some(parent) = dest_item_path.parent() {
        std::fs::create_dir_all(parent).map_err(|e| MindError::io(parent, e))?;
    }
    if dest_item_path.exists() {
        // --force: remove existing dest content first so copy is clean.
        crate::install::remove_path(&dest_item_path)?;
    }
    copy_path_recursive(&source_lobe_path, &dest_item_path)?;

    // 2. ABS-5: stage and commit in the destination repo.
    let git_err = (|| {
        crate::git::add_all(&dest_path)?;
        let commit_msg = format!("absorb {}:{}", item.kind.as_str(), item.name);
        crate::git::commit(&dest_path, &commit_msg)
    })();
    if let Err(e) = git_err {
        // Restore: remove the dest copy we just made; source lobe is still intact.
        let _ = crate::install::remove_path(&dest_item_path);
        return Err(e);
    }

    // 3. ABS-1: meld the destination if not yet registered.
    let dest_spec = dest_path.to_string_lossy().into_owned();
    if !is_melded(paths, &dest_spec)? {
        let meld_err = meld(
            paths,
            &dest_spec,
            None,
            vec![],
            false,
            None,
            None,
            None,
            None,
            false,
        );
        if let Err(e) = meld_err {
            // Restore: source lobe still intact; clean up dest copy.
            let _ = crate::install::remove_path(&dest_item_path);
            return Err(e);
        }
        // meld() now returns MeldSummary; the Ok(_) case is discarded here
        // because absorb handles its own JSON output (ABS-11).
    }

    // 4. Backup the source lobe item before removing it.
    //    Use a tmp path under MIND_HOME so it survives an in-repo rename.
    let backup = paths
        .tmp_dir()
        .join("absorb-backup")
        .join(item.kind.as_str())
        .join(&item.name);
    let _ = crate::install::remove_path(&backup);
    if let Some(p) = backup.parent() {
        std::fs::create_dir_all(p).map_err(|e| MindError::io(p, e))?;
    }
    copy_path_recursive(&source_lobe_path, &backup)?;

    // 5. Remove the original lobe entry so learn can place its symlink there.
    if let Err(e) = crate::install::remove_path(&source_lobe_path) {
        // Couldn't clear path; restore is a no-op since lobe is still there.
        let _ = crate::install::remove_path(&backup);
        return Err(e);
    }

    // 6. Derive the effective name for reporting (destination prefix).
    let registry_for_prefix = Registry::load(paths)?;
    let effective_prefix = dest_source_prefix(&dest_path, &registry_for_prefix);
    let effective_name = crate::namespace::apply(&item.name, &effective_prefix);
    let effective_key = format!("{}:{}", item.kind.as_str(), effective_name);

    // ABS-1 / ABS-8: learn the item under the destination source.
    // When `--json` is in effect use `learn_collecting` (no JSON emitted by
    // learn itself) so that absorb can emit its own single result (ABS-11).
    // In human mode the regular `learn()` path prints the "learned ..." line.
    let dest_source_name = parse_spec(&dest_spec)
        .map(|s| s.name)
        .unwrap_or_else(|_| dest_spec.clone());
    let learn_ref = format!("{}:{}", item.kind.as_str(), effective_name);
    let qualified_ref = format!("{dest_source_name}#{learn_ref}");
    let learn_flow = InstallFlow {
        yes: true,               // already confirmed above
        clobber: Clobber::Force, // stray lobe copies handled by Force
        dangerously_skip: false,
    };
    let learn_err: Result<()> = if out.json {
        learn_collecting(paths, &qualified_ref, learn_flow).map(|_| ())
    } else {
        learn(paths, &qualified_ref, false, learn_flow)
    };

    if let Err(e) = learn_err {
        // Restore the original lobe entry from backup.
        // Best-effort: if restore fails we still return the original error.
        if let Some(parent) = source_lobe_path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let _ = copy_path_recursive(&backup, &source_lobe_path);
        let _ = crate::install::remove_path(&backup);
        return Err(e);
    }

    // 7. Success: drop the backup.
    let _ = crate::install::remove_path(&backup);

    if out.json {
        // ABS-11: emit exactly one structured result on stdout.
        let mut result = MutationResult::new("absorb", item_ref_str, "absorbed");
        result.key = Some(effective_key);
        return print_json(&result);
    }
    println!(
        "{} absorbed {} -> managed as {effective_key}",
        out.ok(),
        item.key()
    );
    Ok(())
}

/// Resolve the destination for `absorb` (ABS-2 / ABS-3).
///
/// Returns `(dest_path, interactive_dest)` where `interactive_dest` is true only
/// when the destination was obtained interactively (ABS-3), which triggers the
/// ABS-4 save offer.
fn resolve_absorb_dest(
    paths: &Paths,
    to_flag: Option<String>,
    yes: bool,
) -> Result<(std::path::PathBuf, bool)> {
    // ABS-2: --to flag takes precedence.
    if let Some(p) = to_flag {
        let path = expand_tilde(&p);
        return Ok((path, false));
    }

    // ABS-2: MIND_ABSORB_TO env var is next.
    if let Some(p) = std::env::var_os("MIND_ABSORB_TO") {
        let path = expand_tilde(&p.to_string_lossy());
        return Ok((path, false));
    }

    // ABS-2: absorb_to in config.toml.
    let config = Config::load(paths)?;
    if let Some(p) = config.absorb_to {
        let path = expand_tilde(&p);
        return Ok((path, false));
    }

    // ABS-3: none set and non-TTY (or --yes with no destination).
    if !crate::hook::is_tty() {
        return Err(MindError::ConfirmationRequired {
            action: "absorb (no destination configured; re-run with --to <path>)".to_string(),
        });
    }

    // Interactive: prompt, offering the built-in personal repo.
    let personal = paths.mind_home.join("personal");
    let personal_str = personal.to_string_lossy();
    let chosen = if yes {
        // With --yes, default to the built-in personal dir without prompting.
        personal.clone()
    } else {
        println!("No absorb destination configured.");
        println!("Enter a path, or press Enter to use the built-in: {personal_str}");
        print!("> ");
        let _ = std::io::stdout().flush();
        let mut line = String::new();
        std::io::stdin()
            .read_line(&mut line)
            .map_err(|e| MindError::io("<stdin>", e))?;
        let trimmed = line.trim();
        if trimmed.is_empty() {
            personal.clone()
        } else {
            expand_tilde(trimmed)
        }
    };

    // ABS-3: create and git-init the built-in personal repo on demand.
    if chosen == personal && !personal.exists() {
        if !out_ctx().json {
            println!(
                "Creating {} and initializing git repository",
                personal.display()
            );
        }
        crate::git::git_init(&personal)?;
    }

    Ok((chosen, true))
}

/// Offer to save the chosen absorb destination as `absorb_to` in config.toml (ABS-4).
/// Only called when the destination was resolved interactively.
fn offer_save_absorb_to(paths: &Paths, dest: &std::path::Path, yes: bool) -> Result<()> {
    if yes {
        // --yes skips the prompt; save automatically.
        let mut config = Config::load(paths)?;
        config.absorb_to = Some(dest.to_string_lossy().into_owned());
        paths.ensure_layout()?;
        config.save(paths)?;
        return Ok(());
    }
    if !crate::hook::is_tty() {
        // Non-TTY without --yes: skip (the destination was already used this run).
        return Ok(());
    }
    print!(
        "\nSave '{}' as absorb_to in config.toml? [y/N] ",
        dest.display()
    );
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    std::io::stdin()
        .read_line(&mut line)
        .map_err(|e| MindError::io("<stdin>", e))?;
    if parse_confirm(&line, false) {
        let mut config = Config::load(paths)?;
        config.absorb_to = Some(dest.to_string_lossy().into_owned());
        paths.ensure_layout()?;
        config.save(paths)?;
        println!("Saved absorb_to = '{}'", dest.display());
    }
    Ok(())
}

/// Thin output-ctx accessor for code that cannot use the `out` binding directly.
fn out_ctx() -> crate::render::OutputCtx {
    crate::render::ctx()
}

/// Recursively copy `src` to `dst` (file or directory).
fn copy_path_recursive(src: &std::path::Path, dst: &std::path::Path) -> Result<()> {
    if src.is_dir() {
        std::fs::create_dir_all(dst).map_err(|e| MindError::io(dst, e))?;
        let rd = std::fs::read_dir(src).map_err(|e| MindError::io(src, e))?;
        for entry in rd.flatten() {
            let from = entry.path();
            let to = dst.join(entry.file_name());
            copy_path_recursive(&from, &to)?;
        }
    } else {
        std::fs::copy(src, dst).map_err(|e| MindError::io(src, e))?;
    }
    Ok(())
}

/// Expand a leading `~` in `path` to the home directory.
fn expand_tilde(path: &str) -> std::path::PathBuf {
    if path == "~" {
        return dirs::home_dir().unwrap_or_else(|| std::path::PathBuf::from("~"));
    }
    if let Some(rest) = path.strip_prefix("~/")
        && let Some(home) = dirs::home_dir()
    {
        return home.join(rest);
    }
    std::path::PathBuf::from(path)
}

/// `mind forget <item>` — uninstall one item, or many via a glob.
///
/// When `unmanaged` is true, removal is scoped to unmanaged lobe items only
/// (UNM-7/UNM-8). `item_ref` may be `None` to remove every unmanaged item.
/// When `unmanaged` is false, behavior is unchanged: `item_ref` is required.
pub fn forget(
    paths: &Paths,
    item_ref: Option<&str>,
    unmanaged: bool,
    yes: bool,
    force: bool,
    dangerously_skip: bool,
) -> Result<()> {
    if unmanaged {
        return forget_unmanaged_bulk(paths, item_ref, yes);
    }

    // `unmanaged` is false: clap guarantees `item_ref` is Some (required_unless_present).
    let item_ref = item_ref.expect("item_ref required when --unmanaged is not set");

    let out = crate::render::ctx();
    let mut manifest = Manifest::load(paths)?;
    let parsed = parse_item_ref(item_ref)?;

    // A glob uninstalls every installed match (mirroring `learn`'s selection);
    // an exact ref honors the kind prefix and source qualifier and errors on an
    // ambiguous bare name (e.g. one shared by a skill and an agent).
    let keys: Vec<String> = if is_glob(&parsed.name) {
        let matches = select_installed(&manifest.items, &parsed);
        if matches.is_empty() {
            return Err(MindError::NotInstalled {
                name: parsed.name.clone(),
            });
        }
        matches.iter().map(|it| it.key()).collect()
    } else {
        match crate::resolve::resolve_installed(&manifest.items, &parsed) {
            Ok(it) => vec![it.key()],
            // UNM-4: an exact ref that names no managed item may name an
            // unmanaged lobe item; a glob never sweeps unmanaged entries.
            Err(MindError::NotInstalled { .. }) => {
                let unmanaged_items = crate::unmanaged::scan(paths, &manifest)?;
                let item = crate::unmanaged::resolve(&unmanaged_items, &parsed)?;
                return forget_unmanaged_single(item, yes);
            }
            Err(e) => return Err(e),
        }
    };

    // CLI-42: removing more than one item (typically a glob that matched more
    // broadly than intended) lists the matches and confirms first. `--yes` skips;
    // a non-TTY run without `--yes` refuses rather than removing silently.
    if keys.len() > 1 && !yes {
        if !out.json {
            println!("forget would remove {} item(s):", keys.len());
            for key in &keys {
                println!("  {} {key}", out.warn());
            }
        }
        if !crate::hook::is_tty() {
            return Err(MindError::ConfirmationRequired {
                action: format!("removing {} items", keys.len()),
            });
        }
        if !out.json && !confirm("remove these item(s)?")? {
            println!("cancelled; nothing removed");
            return Ok(());
        }
    }

    // HOOK-82/86: an item's uninstall hooks (when declared) run before its files
    // are removed, in declaration order. They are read from the live source
    // catalog (nothing is recorded for them, HOOK-84); a source no longer
    // registered or an item gone from its catalog yields no hook, and removal
    // proceeds.
    let registry = Registry::load(paths)?;
    let catalog = catalog::scan(paths, &registry).unwrap_or_default();

    // DEP-60: for a single-item forget, warn about installed items that depend on
    // the item being removed. The check only applies to the single-item path
    // (keys.len() == 1); the glob path already handled its CLI-42 confirmation.
    if keys.len() == 1 {
        let removed_key = &keys[0];
        let installed_keys: HashSet<String> = manifest.items.keys().cloned().collect();
        let graph = crate::deps::installed_graph(&catalog, &installed_keys, read_item_text);
        let dependents = graph.dependents(removed_key);
        if !dependents.is_empty() && !yes && !force {
            if !out.json {
                println!(
                    "{} removing {removed_key} will break the following installed items that depend on it:",
                    out.warn()
                );
                for dep in &dependents {
                    println!("  {dep}");
                }
            }
            // C3 / DEP-60: json mode is non-interactive; treat it like non-TTY
            // for this destructive confirmation. A missing --yes/--force refuses
            // with ConfirmationRequired regardless of whether a real TTY is attached.
            if !crate::hook::is_tty() || out.json {
                return Err(MindError::ConfirmationRequired {
                    action: format!(
                        "removing {removed_key} (has {} dependent(s))",
                        dependents.len()
                    ),
                });
            }
            if !confirm("remove anyway?")? {
                println!("cancelled; nothing removed");
                return Ok(());
            }
        }
    }

    let mut removed: Vec<String> = Vec::new();
    for key in keys {
        let item = manifest.items.remove(&key).expect("key from manifest");
        let uninstall_hooks: Vec<&crate::mindfile::ResolvedHook> =
            item_catalog_match(&catalog, &item)
                .map(|c| c.uninstall_hooks())
                .unwrap_or_default();
        let commit = registry
            .find(&item.source)
            .and_then(|s| s.commit.clone())
            .unwrap_or_default();
        // A hook failure stops here, leaving this item (and the rest) installed;
        // the manifest is saved with what remains.
        if let Err(e) = uninstall_item(paths, &item, &uninstall_hooks, &commit, dangerously_skip) {
            manifest.items.insert(key.clone(), item);
            manifest.save(paths)?;
            return Err(e);
        }
        removed.push(key.clone());
        if !out.json {
            println!("{} forgot {key}", out.ok());
        }
    }
    manifest.save(paths)?;
    if out.json {
        let mut result = MutationResult::new("forget", item_ref, "removed");
        result.removed = removed;
        return print_json(&result);
    }
    Ok(())
}

/// `forget` of a single unmanaged lobe item (UNM-4/5): remove the lobe entry
/// itself after a prompt that states it is not managed by mind. There is no
/// store copy or manifest entry, so the manifest is left untouched.
fn forget_unmanaged_single(item: &crate::unmanaged::UnmanagedItem, yes: bool) -> Result<()> {
    let out = crate::render::ctx();
    let where_ = item
        .paths
        .iter()
        .map(|p| p.display().to_string())
        .collect::<Vec<_>>()
        .join(", ");
    // UNM-5: always state explicitly that the item is not mind-managed and that
    // removal deletes the user's own file or directory.
    if !out.json {
        println!(
            "{} {} is not managed by mind: it is your own file or directory at {where_}, not a mind install. Removing it deletes it.",
            out.warn(),
            item.key()
        );
    }
    if !yes {
        if !crate::hook::is_tty() {
            return Err(MindError::ConfirmationRequired {
                action: format!("removing unmanaged {}", item.key()),
            });
        }
        if !out.json && !confirm("remove this unmanaged item?")? {
            println!("cancelled; nothing removed");
            return Ok(());
        }
    }
    for p in &item.paths {
        crate::install::remove_path(p)?;
    }
    if out.json {
        let mut result = MutationResult::new("forget", &item.key(), "removed");
        result.removed = vec![item.key()];
        return print_json(&result);
    }
    println!("{} forgot {} (unmanaged)", out.ok(), item.key());
    Ok(())
}

/// `forget --unmanaged [<ref>]` — bulk removal of unmanaged lobe items (UNM-7/8).
///
/// Selects every unmanaged item matching the optional `item_ref` (`None` = all),
/// lists them, confirms once (stating they are not managed and deletion is real),
/// then removes each. The manifest is never mutated (UNM-4).
// spec: UNM-7 UNM-8
fn forget_unmanaged_bulk(paths: &Paths, item_ref: Option<&str>, yes: bool) -> Result<()> {
    let out = crate::render::ctx();
    let manifest = Manifest::load(paths)?;
    let scanned = crate::unmanaged::scan(paths, &manifest)?;

    // Parse the ref (if given) and select matching items.
    let parsed = item_ref.map(parse_item_ref).transpose()?;
    let matched = crate::unmanaged::select(&scanned, parsed.as_ref());

    let sentinel = item_ref.unwrap_or("*");
    if matched.is_empty() {
        return Err(MindError::NotInstalled {
            name: sentinel.to_string(),
        });
    }

    // UNM-8: list the matched items, then a SINGLE confirm stating they are not
    // managed by mind and that removal deletes the user's own files/directories.
    if !out.json {
        println!(
            "{} forget --unmanaged would remove {} unmanaged item(s):",
            out.warn(),
            matched.len()
        );
        for item in &matched {
            println!("  {} {}", out.warn(), item.key());
        }
        println!(
            "{} these items are NOT managed by mind: removing them deletes your own files or directories, not symlinks.",
            out.warn()
        );
    }
    if !yes {
        if !crate::hook::is_tty() {
            return Err(MindError::ConfirmationRequired {
                action: format!("removing {} unmanaged items", matched.len()),
            });
        }
        if !out.json && !confirm("remove these unmanaged items?")? {
            println!("cancelled; nothing removed");
            return Ok(());
        }
    }

    // Remove each matched item's paths. The manifest is NOT mutated (UNM-4).
    let mut removed: Vec<String> = Vec::new();
    for item in &matched {
        for p in &item.paths {
            crate::install::remove_path(p)?;
        }
        removed.push(item.key());
        if !out.json {
            println!("{} forgot {} (unmanaged)", out.ok(), item.key());
        }
    }

    if out.json {
        let mut result = MutationResult::new("forget", sentinel, "removed");
        result.removed = removed;
        return print_json(&result);
    }
    Ok(())
}

/// `mind sync [--upgrade] [--dangerously-skip-install-hook-check]` — fetch every
/// source and refresh its recorded commit. With `--upgrade`, an `upgrade` pass
/// runs after the refresh (reporting pending upgrades and prompting before
/// applying, exactly like `mind upgrade`), so one command both fetches upstream
/// and applies pending upgrades. `dangerously_skip_hook_check` is forwarded to
/// the `upgrade` pass so install-hook re-runs can run unattended in CI (HOOK-11,
/// HOOK-23); it is unused when `--upgrade` is absent.
pub fn sync(paths: &Paths, then_upgrade: bool, dangerously_skip_hook_check: bool) -> Result<()> {
    let out = crate::render::ctx();
    // POL-3: load the managed policy once (fail closed on Err; None = inert).
    let policy = Policy::load()?;
    // CLI-19: auto-meld honors the user's SSH preference too.
    let prefer_ssh = Config::load(paths)?.ssh;
    let mut registry = Registry::load(paths)?;
    let mut sync_skipped: Vec<SkippedEntry> = Vec::new();

    // POL-32: provision the policy's auto-meld base set before syncing. Each entry
    // not already in the registry is melded at its declared pin; an entry already
    // present is left unchanged (idempotent). Reuses the meld path, so auto-meld
    // entries discover nested sources just like a user meld. Entries satisfy
    // allow/pinned by policy validation (POL-21/POL-31), so they pass the meld
    // enforcement above.
    if let Some(policy) = policy.as_ref() {
        paths.ensure_layout()?;
        let mut visited = HashSet::new();
        let mut provisioned = 0usize;
        for am in policy.auto_meld() {
            // Idempotency: derive the entry's identity and skip if already melded.
            // (meld_recursive also skips a same-URL duplicate, but checking here
            // avoids the clone attempt and the "melding ..." chatter.)
            if let Ok(spec) = parse_spec(&am.repo)
                && registry.find(&spec.name).is_some()
            {
                continue;
            }
            provisioned += meld_recursive(
                paths,
                &mut registry,
                &am.repo,
                None,
                vec![],
                false, // no consumer --flat-skills for an auto-melded source
                Some(am.pin.clone()),
                false, // skip (not error) if a same-URL entry is already present
                &mut visited,
                Some(policy),
                None,  // auto-meld supplies no install hook
                false, // auto-meld is non-TTY, so its hooks take the HOOK-22 skip path
                prefer_ssh,
                true, // auto-meld is non-interactive (no collision prompt)
                None, // auto-meld has no curator-supplied configuration
                &mut sync_skipped,
            )?;
        }
        if provisioned > 0 {
            registry.save(paths)?;
        }
    }

    if registry.sources.is_empty() {
        if out.json {
            return print_json(&MutationResult::new("sync", "", "no-op"));
        }
        println!("no sources melded; run `mind meld <owner/repo>`");
        return Ok(());
    }
    // A per-source failure (e.g. a network error on one remote) must not abort
    // the whole run: refresh each source independently, persist whatever
    // progress was made, then report the failures and exit non-zero.
    let total = registry.sources.len();
    let mut failures: Vec<String> = Vec::new();
    let mut synced = 0usize;
    for source in &mut registry.sources {
        // POL-12: with the allowlist locked, do not sync a source whose identity
        // is no longer allowed; report and skip it (the rest still sync).
        if let Some(policy) = policy.as_ref()
            && policy.lock()
            && !policy.allow_matches(&source.name)
        {
            if !out.json {
                println!(
                    "{} skipping {}: source not permitted by the managed policy's allowlist",
                    out.warn(),
                    source.name
                );
            }
            continue;
        }
        let dir = source.clone_dir(paths);
        if !out.json {
            print!("{} syncing {} ... ", out.bullet(), source.name);
            let _ = std::io::stdout().flush();
        }
        let refreshed = (|| -> Result<(String, bool, Option<String>)> {
            // A linked (no-pin) local source is its live working tree (CLI-27):
            // there is nothing to fetch and the tree is never touched. Just re-read
            // its HEAD (best effort) and description. A pinned local source is a
            // clone and syncs like any other.
            if source.is_linked() {
                // The working tree must still exist; a deleted one is a sync error
                // for this source (CLI-54 reports it and continues with the rest).
                if !dir.is_dir() {
                    return Err(MindError::NotADirectory {
                        path: dir.display().to_string(),
                    });
                }
                let new_commit = git::head_commit(&source.url, &dir)
                    .ok()
                    .or_else(|| source.commit.clone())
                    .unwrap_or_default();
                let changed = source.commit.as_deref() != Some(new_commit.as_str());
                let desc = MindToml::load(&dir)?.and_then(|mt| mt.source.description);
                return Ok((new_commit, changed, desc));
            }
            // CLI-55: resolve the source against its recorded pin (never change
            // the pin itself, only move HEAD to the pinned point).
            let pin = source.pin.clone();
            if dir.join(".git").is_dir() {
                git::sync_to_pin(&source.url, &dir, &pin)?;
            } else {
                if let Some(parent) = dir.parent() {
                    crate::paths::mkdir_p(parent)?;
                }
                git::clone_at(&source.url, &dir, &pin)?;
            }
            let new_commit = git::head_commit(&source.url, &dir)?;
            let changed = source.commit.as_deref() != Some(new_commit.as_str());
            let desc = MindToml::load(&dir)?.and_then(|mt| mt.source.description);
            Ok((new_commit, changed, desc))
        })();
        match refreshed {
            Ok((new_commit, changed, desc)) => {
                source.commit = Some(new_commit.clone());
                source.description = desc;
                synced += 1;
                if !out.json {
                    let label = if changed {
                        out.green("updated")
                    } else {
                        out.dim("up to date")
                    };
                    println!("{} ({})", label, short(&new_commit));
                }
            }
            Err(e) => {
                if !out.json {
                    println!("{}", out.red("failed"));
                    eprintln!("  {} {}: {e}", out.err(), source.name);
                }
                failures.push(source.name.clone());
            }
        }
    }
    // Save the progress made before reporting any failure, so the recorded
    // commits stay consistent with what is on disk.
    registry.save(paths)?;

    // DSC-57: re-walk each registered source's refreshed `[discover].sources` and
    // meld any newly-listed nested source not already registered. Register-only
    // (the DSC-54 default; nested items are not installed) and cycle-safe by the
    // DSC-38 guards. Only adds; a nested source dropped upstream stays registered.
    {
        // Collect the nested specs now, before mutably borrowing the registry.
        // DSC-61: carry each entry's curator-supplied configuration so a newly
        // discovered nested source is melded with the same gate/apply behavior as
        // a fresh meld. Hooks resolve against the super-source's mind.toml path.
        struct NestedTodo {
            spec: String,
            alias: Option<String>,
            curated: CuratedConfig,
            /// Auth-failure policy for this entry (DSC-68). Carried so the re-walk
            /// loop can handle auth failures the same way as meld (DSC-68 requires
            /// the same behavior applies during sync).
            on_auth_failure: Option<crate::mindfile::OnAuthFailure>,
        }
        let mut nested: Vec<NestedTodo> = Vec::new();
        for s in &registry.sources {
            let clone_dir = s.clone_dir(paths);
            let toml_path = clone_dir.join("mind.toml");
            let Some(mt) = MindToml::load(&clone_dir).ok().flatten() else {
                continue;
            };
            let Some(discover) = mt.discover else {
                continue;
            };
            for ns in discover.sources {
                let curated = CuratedConfig {
                    pin: ns.pin_directive(&toml_path)?,
                    roots: ns.roots.clone(),
                    flat_skills: ns.flat_skills,
                    hooks: ns.resolved_hooks(&toml_path)?,
                };
                // spec: DSC-78 — use effective_alias() so the canonical
                // `namespace =` key is honored (not just the legacy `as =` key).
                // Compute before consuming fields of `ns`.
                let ns_alias = ns.effective_alias();
                nested.push(NestedTodo {
                    spec: ns.source,
                    alias: ns_alias,
                    curated,
                    on_auth_failure: ns.on_auth_failure,
                });
            }
        }
        // MKT-7/DSC-57: also re-walk .claude-plugin/marketplace.json from registered
        // sources. For each marketplace source, add newly-listed plugin entries that
        // are not already registered. Additive only: a removed entry stays registered
        // (removal is an explicit `unmeld`). Cycle-safe via the visited set below.
        for s in &registry.sources {
            let clone_dir = s.clone_dir(paths);
            // An authoritative mind.toml suppresses the marketplace manifest (MKT-2).
            let is_authoritative_source = MindToml::load(&clone_dir)
                .ok()
                .flatten()
                .is_some_and(|m| m.is_authoritative());
            if is_authoritative_source {
                continue;
            }
            let marketplace_path = plugin_manifest::marketplace_manifest_path(&clone_dir);
            if !marketplace_path.is_file() {
                continue;
            }
            // Skip parse errors during sync re-walk (advisory; a bad manifest
            // was already surfaced at meld time).
            let Ok(manifest) = plugin_manifest::load_marketplace_manifest(&marketplace_path) else {
                continue;
            };
            for entry in manifest.into_entries() {
                // In-repo plugins are scan roots in catalog.rs, not sub-melded. spec: MKT-14
                if matches!(entry.source, plugin_manifest::PluginSource::InRepo { .. }) {
                    continue;
                }
                let repo_spec = marketplace_entry_spec(&entry, &clone_dir);
                nested.push(NestedTodo {
                    spec: repo_spec,
                    alias: Some(entry.name),
                    curated: CuratedConfig {
                        pin: None,
                        roots: None,
                        flat_skills: false,
                        hooks: Vec::new(),
                    },
                    on_auth_failure: None,
                });
            }
        }

        // Seed the cycle guard with every registered URL so an existing source is
        // skipped without a clone attempt.
        let mut visited: HashSet<String> = registry.sources.iter().map(|s| s.url.clone()).collect();
        let mut discovered = 0usize;
        for todo in nested {
            if let Ok(s) = parse_spec(&todo.spec)
                && registry.find(&s.name).is_some()
            {
                continue;
            }
            // spec: DSC-68 -- auth failures during the sync re-walk honor
            // on-auth-failure the same way as the nested-source loop in
            // meld_recursive. Without on-auth-failure, the error propagates
            // as a generic git error (hard failure).
            match meld_recursive(
                paths,
                &mut registry,
                &todo.spec,
                todo.alias,
                vec![],
                false, // no consumer --flat-skills on a sync re-walk (curator config supplies it)
                None,
                false,
                &mut visited,
                policy.as_ref(),
                None,  // a re-walked nested source supplies no install hook
                false, // sync is non-TTY: its hooks take the HOOK-22 skip path
                prefer_ssh,
                true, // sync re-walk is non-interactive (no collision prompt)
                Some(todo.curated),
                &mut sync_skipped,
            ) {
                Ok(n) => discovered += n,
                Err(e) if git::is_auth_failure(&e) => {
                    let entry_name = parse_spec(&todo.spec)
                        .map(|s| s.name)
                        .unwrap_or_else(|_| todo.spec.clone());
                    // spec: DSC-70 -- on-auth-failure only covers the entry's own
                    // clone failure. If the entry is already in the registry, it
                    // cloned successfully and the failure came from a descendant;
                    // propagate it unchanged.
                    if registry.find(&entry_name).is_some() {
                        return Err(e);
                    }
                    let Some(cfg) = &todo.on_auth_failure else {
                        return Err(e);
                    };
                    // spec: DSC-69 -- always warn to stderr regardless of --json mode
                    for line in auth_failure_lines(&entry_name, cfg) {
                        eprintln!("{line}");
                    }
                    if cfg.action == AuthFailureAction::Skip {
                        sync_skipped.push(SkippedEntry {
                            source: entry_name,
                            reason: "auth_failure".into(),
                        });
                        continue;
                    }
                    return Err(e);
                }
                // spec: DSC-79 -- the same non-auth clone-failure skip applies during
                // the sync re-walk. No curator-empty guard here: the source is already
                // melded, so DSC-80 does not apply.
                Err(e) => {
                    let entry_name = parse_spec(&todo.spec)
                        .map(|s| s.name)
                        .unwrap_or_else(|_| todo.spec.clone());
                    if registry.find(&entry_name).is_some() {
                        return Err(e);
                    }
                    for line in clone_failure_lines(&entry_name, &e) {
                        eprintln!("{line}");
                    }
                    sync_skipped.push(SkippedEntry {
                        source: entry_name,
                        reason: "clone_failure".into(),
                    });
                    continue;
                }
            }
        }
        if discovered > 0 {
            registry.save(paths)?;
        }
    }

    if !failures.is_empty() {
        return Err(MindError::SyncFailed {
            failed: failures.len(),
            total,
        });
    }
    if out.json {
        let mut result = MutationResult::new("sync", "", "synced");
        result.count = Some(synced);
        result.skipped = sync_skipped;
        print_json(&result)?;
    }
    if then_upgrade {
        // spec: HOOK-11, HOOK-23
        upgrade(paths, false, None, dangerously_skip_hook_check)?;
    }
    Ok(())
}

/// `mind upgrade [--yes] [item]` — report and optionally apply upgrades.
pub fn upgrade(
    paths: &Paths,
    yes: bool,
    item_ref: Option<&str>,
    dangerously_skip_hook_check: bool,
) -> Result<()> {
    let out = crate::render::ctx();
    // POL-3: load the managed policy once (fail closed on Err; None = inert).
    let policy = Policy::load()?;
    let mut registry = Registry::load(paths)?;
    let manifest = Manifest::load(paths)?;

    let filter = item_ref.map(parse_item_ref).transpose()?;

    // HOOK-11 scope: a scoped `upgrade <item>` must not re-run install hooks
    // (arbitrary code) for sources unrelated to the targeted item. When a filter
    // is present, restrict the hook re-run to sources that have at least one
    // INSTALLED item matching the filter (the same scoping the per-item loop uses
    // via `installed_matches_glob`). With no filter, `None` means every source is
    // in scope, leaving the unscoped behavior unchanged.
    let hook_scope: Option<HashSet<String>> = filter.as_ref().map(|f| {
        manifest
            .items
            .values()
            .filter(|it| crate::resolve::installed_matches_glob(it, f))
            .map(|it| it.source.clone())
            .collect()
    });

    // HOOK-11: re-run a source's install hook when its commit has advanced past
    // the commit the hook last ran at (or it was recorded but never run). This is
    // a source-level pass, separate from the per-item upgrade loop below.
    rerun_source_hooks(
        paths,
        &mut registry,
        dangerously_skip_hook_check,
        hook_scope.as_ref(),
        policy.as_ref(),
    )?;

    let catalog = catalog::scan(paths, &registry)?;
    let mut pending: Vec<Upgrade> = Vec::new();

    for installed in manifest.items.values() {
        match upgrade_item_disposition(installed, filter.as_ref(), policy.as_ref()) {
            // Out of the scoped selection: silent skip, no output.
            UpgradeDisposition::OutOfScope => continue,
            // POL-12: in-scope but the source is no longer allowed by the locked
            // allowlist; report and skip. The item-ref filter is checked first,
            // so a scoped upgrade never emits skip lines for out-of-scope sources
            // the user never selected.
            UpgradeDisposition::PolicyBlocked => {
                if !out.json {
                    println!(
                        "{} skipping {} from {}: source not permitted by the managed policy's allowlist",
                        out.warn(),
                        installed.key(),
                        installed.source
                    );
                }
                continue;
            }
            UpgradeDisposition::Consider => {}
        }
        // Match on stable identity (source, kind, bare_name) so a prefix change
        // is seen as a rename of the same item, not an orphan-plus-new-item.
        let Some(cat) = catalog.iter().find(|c| {
            c.kind == installed.kind
                && c.name == installed.bare_name
                && c.source == installed.source
        }) else {
            // Source dropped or item removed upstream; reported by introspect.
            continue;
        };
        let new_hash = hash_path(&cat.path)?;
        let new_name = cat.effective_name();
        let new_commit = registry
            .find(&installed.source)
            .and_then(|s| s.commit.clone())
            .unwrap_or_default();
        let renamed = new_name != installed.name;
        if new_hash != installed.hash || renamed {
            pending.push(Upgrade {
                cat: cat.clone(),
                old: installed.clone(),
                new_commit,
                new_hash,
                new_name,
            });
        }
    }

    let target = item_ref.unwrap_or("all");

    if pending.is_empty() {
        if out.json {
            return print_json(&MutationResult::new("upgrade", target, "up-to-date"));
        }
        println!("everything is up to date");
        return Ok(());
    }

    if !out.json {
        print_upgrade_report(&registry, &pending);
    }

    if !yes && !out.json && !confirm_default_yes("apply these upgrades?")? {
        println!("aborted; nothing changed");
        return Ok(());
    }

    let mut manifest = manifest;
    let mut applied: Vec<String> = Vec::new();
    let mut renamed = false;
    for up in &pending {
        let siblings = siblings_of(&catalog, &up.cat.source);
        // Build the new version first; the old copy is preserved until this
        // succeeds (transactional install). An upgrade never force-overwrites a
        // foreign target; that is for an explicit `learn --force`.
        let installed = install_item(
            paths,
            &up.cat,
            &up.new_commit,
            &siblings,
            false,
            dangerously_skip_hook_check,
        )?;
        if up.new_name != up.old.name {
            // Rename: drop the old item (by its file registry) and re-key. The OLD
            // item is removed, so its uninstall hook fires (HOOK-82); the new
            // item's install hook already ran in install_item above.
            uninstall_item(
                paths,
                &up.old,
                &up.cat.uninstall_hooks(),
                &up.old.commit,
                dangerously_skip_hook_check,
            )?;
            manifest.items.remove(&up.old.key());
            renamed = true;
            if !out.json {
                println!(
                    "{} upgraded {} -> {}",
                    out.ok(),
                    up.old.key(),
                    out.green(&installed.key())
                );
            }
        } else {
            // In-place upgrade (same effective name, so not a rename). The link
            // set can still change when an agent's harness name (its frontmatter
            // `name`, NS-40) changed: the new copy links under the new bare name,
            // so remove any old link the new install no longer owns, leaving no
            // orphaned symlink behind.
            for old_link in &up.old.links {
                if !installed.links.contains(old_link) {
                    install::remove_path(std::path::Path::new(old_link))?;
                }
            }
            if !out.json {
                println!("{} upgraded {}", out.ok(), out.green(&installed.key()));
            }
        }
        applied.push(installed.key());
        manifest.insert(installed);
    }
    manifest.save(paths)?;
    if out.json {
        let outcome = if renamed { "renamed" } else { "upgraded" };
        let mut result = MutationResult::new("upgrade", target, outcome);
        result.installed = applied;
        return print_json(&result);
    }
    Ok(())
}

/// HOOK-11, HOOK-55: re-run each source's install hooks when warranted (any
/// recorded hook whose `ran_at` differs from the source's current commit). Same
/// trust boundary as `meld`: prompt and disclose, unless
/// `--dangerously-skip-install-hook-check` is set or there is no TTY. In
/// `upgrade`, Abort is treated as Skip: the source is already registered, so
/// declining the re-run just leaves the existing install in place. Persists the
/// registry only if a hook was run and its recorded commit advanced.
fn rerun_source_hooks(
    paths: &Paths,
    registry: &mut Registry,
    dangerously_skip_hook_check: bool,
    in_scope: Option<&HashSet<String>>,
    policy: Option<&Policy>,
) -> Result<()> {
    let mut changed = false;
    for source in &mut registry.sources {
        if !hook_rerun_warranted(source) {
            continue;
        }
        // HOOK-11 scope: a scoped `upgrade <item>` restricts the hook re-run to
        // sources implicated by the filter. `None` = unscoped (all sources).
        if let Some(scope) = in_scope
            && !scope.contains(&source.name)
        {
            continue;
        }
        // POL-12: with the allowlist locked, do not re-run the install hook
        // (arbitrary code) for a source whose identity is no longer allowed;
        // report and skip it, exactly as the per-item loop does.
        if let Some(policy) = policy
            && policy.lock()
            && !policy.allow_matches(&source.name)
        {
            if !json_mode() {
                println!(
                    "skipping install hook for {}: source not permitted by the managed policy's allowlist",
                    source.name
                );
            }
            continue;
        }

        let dir = source.clone_dir(paths);
        let pin_desc = pin_description(&source.pin);
        let commit = source.commit.clone().unwrap_or_default();
        let clone_path = dir.display().to_string();

        // Collect indices of pending hooks so we can mutate by index below.
        // A hook is pending when it has never run (ran_at=None) OR its run-commit
        // differs from the source's current commit. Treating ran_at=None as always
        // pending ensures hooks skipped on a commitless linked source are re-offered.
        let pending_indices: Vec<usize> = source
            .install_hooks
            .iter()
            .enumerate()
            .filter(|(_, h)| h.ran_at.is_none() || h.ran_at.as_deref() != source.commit.as_deref())
            .map(|(i, _)| i)
            .collect();

        for idx in pending_indices {
            let cmd = source.install_hooks[idx].command.clone();

            let run = if dangerously_skip_hook_check {
                // HOOK-23: re-run without prompting.
                if !json_mode() {
                    println!(
                        "note: re-running install hook for {} without the safety prompt (--dangerously-skip-install-hook-check)",
                        source.name
                    );
                }
                true
            } else if !crate::hook::is_tty() {
                // HOOK-22: no TTY; never run silently. Skip the re-run.
                if !json_mode() {
                    println!(
                        "note: skipped re-running the install hook for {} (no TTY); its tooling may be out of date until the hook is re-run",
                        source.name
                    );
                }
                false
            } else {
                let disclosure = crate::hook::disclosure_text(
                    &source.name,
                    &pin_desc,
                    &commit,
                    &clone_path,
                    &cmd,
                    None,
                );
                // Abort is treated as Skip here (the source is already registered,
                // per the HOOK-11 note).
                matches!(
                    crate::hook::prompt_choice(&disclosure)?,
                    crate::hook::HookChoice::RunAndContinue
                )
            };

            if run {
                // HOOK-30: a non-zero exit is a hard error. The source stays
                // registered; just propagate the failure.
                crate::hook::run_hook(&cmd, &dir, &source.name, &cmd)?;
                // HOOK-55: record the commit the hook ran at.
                source.install_hooks[idx].ran_at = source.commit.clone();
                changed = true;
                if !json_mode() {
                    println!("re-ran install hook for {}", source.name);
                }
            }
        }
    }
    if changed {
        registry.save(paths)?;
    }
    Ok(())
}

/// What `upgrade` should do with one installed item before the catalog lookup.
#[derive(Debug, PartialEq, Eq)]
enum UpgradeDisposition {
    /// The item is outside the scoped item-ref selection: skip silently.
    OutOfScope,
    /// In scope, but its source is barred by the locked policy allowlist
    /// (POL-12): print a skip line.
    PolicyBlocked,
    /// In scope and permitted: consider it for an upgrade.
    Consider,
}

/// Decide an installed item's `upgrade` disposition. The item-ref filter is
/// applied first (POL-12 ordering fix): a scoped `upgrade <item>` must not emit
/// policy-skip lines for sources the user never selected. The policy block is
/// only ever reported for items that passed the filter.
fn upgrade_item_disposition(
    installed: &crate::manifest::InstalledItem,
    filter: Option<&crate::resolve::ItemRef>,
    policy: Option<&Policy>,
) -> UpgradeDisposition {
    if let Some(f) = filter
        && !crate::resolve::installed_matches_glob(installed, f)
    {
        return UpgradeDisposition::OutOfScope;
    }
    if let Some(policy) = policy
        && policy.lock()
        && !policy.allow_matches(&installed.source)
    {
        return UpgradeDisposition::PolicyBlocked;
    }
    UpgradeDisposition::Consider
}

struct Upgrade {
    cat: CatalogItem,
    old: crate::manifest::InstalledItem,
    new_commit: String,
    new_hash: String,
    new_name: String,
}

fn print_upgrade_report(registry: &Registry, pending: &[Upgrade]) {
    let out = crate::render::ctx();
    println!("{} item(s) have upstream changes:\n", pending.len());
    for up in pending {
        if up.new_name != up.old.name {
            println!(
                "  {} {} {} {}  rename {} -> {}",
                out.warn(),
                up.cat.kind,
                up.cat.name,
                out.dim(&format!("[{}]", up.cat.source)),
                up.old.name,
                out.green(&up.new_name)
            );
        } else {
            println!(
                "  {} {} {}",
                out.warn(),
                up.cat.key(),
                out.dim(&format!("[{}]", up.cat.source))
            );
        }
        println!(
            "    {}    {} -> {}",
            out.dim("hash"),
            short(&up.old.hash),
            short(&up.new_hash)
        );
        println!(
            "    {}  {} -> {}",
            out.dim("commit"),
            short(&up.old.commit),
            short(&up.new_commit)
        );
        if let Some(src) = registry.find(&up.cat.source)
            && !up.old.commit.is_empty()
            && !up.new_commit.is_empty()
            && let Some(url) = src.compare_url(&up.old.commit, &up.new_commit)
        {
            println!("    {}    {url}", out.dim("diff"));
        }
        println!();
    }
}

/// `mind recall [--sources] [item] [--kind K] [--source S] [--json] [--tree]`. The
/// `--kind` and `--source` filters narrow the installed-items listing; they do
/// not apply to `--sources` or to a single-item lookup (use a `kind:`/
/// `owner/repo#` ref there). `--json` emits the data as JSON on stdout.
/// `--tree` renders the installed dependency forest (DEP-61).
pub fn recall(
    paths: &Paths,
    sources: bool,
    item: Option<&str>,
    kind: Option<ItemKind>,
    source: Option<&str>,
    json: bool,
    tree: bool,
) -> Result<()> {
    let out = crate::render::ctx();
    // The listing filters are meaningless for --sources or a single-item lookup;
    // say so rather than silently ignoring them.
    if (sources || item.is_some()) && (kind.is_some() || source.is_some()) {
        eprintln!(
            "note: --kind/--source filter the item listing; ignored with --sources or a single item"
        );
    }
    // --tree is meaningless with --sources; note and ignore.
    if tree && sources {
        eprintln!("note: --tree shows the dependency forest; ignored with --sources");
    }

    // DEP-61 / DEP-63: --tree renders the installed dependency forest.
    if tree && !sources {
        // spec: DEP-61
        let manifest = Manifest::load(paths)?;
        let registry = Registry::load(paths)?;
        let catalog = catalog::scan(paths, &registry).unwrap_or_default();
        let installed_keys: HashSet<String> = manifest.items.keys().cloned().collect();
        let graph = crate::deps::installed_graph(&catalog, &installed_keys, read_item_text);

        if json {
            // spec: DEP-63 -- structured JSON output instead of the human rendering.
            if let Some(item_ref) = item {
                // Scoped to one item's subtree: emit a single JSON object.
                let parsed = parse_item_ref(item_ref)?;
                let found = crate::resolve::resolve_installed(&manifest.items, &parsed)?;
                let key = found.key();
                // subtree_node returns None when the item is installed but has
                // no catalog entry (and thus no node in the graph); fall back
                // to a no-dependency node so the caller always gets valid JSON.
                let node = graph
                    .subtree_node(&key)
                    .unwrap_or_else(|| crate::deps::DepNode::normal(key, vec![]));
                return print_json(&node);
            } else {
                // Full forest: emit a JSON array of root nodes.
                return print_json(&graph.forest_nodes());
            }
        }

        if let Some(item_ref) = item {
            // Scoped to one item's subtree.
            let parsed = parse_item_ref(item_ref)?;
            let found = crate::resolve::resolve_installed(&manifest.items, &parsed)?;
            let key = found.key();
            match graph.render_subtree(&key) {
                Some(subtree) => print!("{subtree}"),
                None => println!("{key}"),
            }
        } else {
            // Full forest.
            let forest = graph.render_forest();
            if forest.is_empty() {
                println!("no installed items");
            } else {
                print!("{forest}");
            }
        }
        return Ok(());
    }
    // CLI-86: the `--source` glob filter shares `source_matches_glob`; reject a
    // malformed pattern up front rather than silently matching nothing.
    if let Some(s) = source {
        crate::resolve::validate_source_selector(s)?;
    }

    if sources {
        let registry = Registry::load(paths)?;
        if json {
            return print_json(&registry.sources);
        }
        if registry.sources.is_empty() {
            println!("no sources melded");
            return Ok(());
        }
        let rows = registry
            .sources
            .iter()
            .map(|s| {
                let commit = s
                    .commit
                    .as_deref()
                    .map(short)
                    .unwrap_or_else(|| "unsynced".into());
                let ns = match &s.alias {
                    Some(a) => format!(" namespace:{a}"),
                    None => String::new(),
                };
                // HOOK-58: surface that a source carries install hooks with a
                // count-aware token.
                let hook = match s.install_hooks.len() {
                    0 => String::new(),
                    1 => " hook".to_string(),
                    n => format!(" hooks({n})"),
                };
                // MKT-10: show the manifest origin so a native-plugin source is
                // distinguishable from a convention or mind.toml source.
                let origin = origin_label(s.origin);
                vec![
                    out.bullet(),
                    s.name.clone(),
                    out.dim(&s.url),
                    out.dim(&format!("[{commit}{ns}{hook}{origin}]")),
                    s.description.clone().unwrap_or_default(),
                ]
            })
            .collect::<Vec<_>>();
        out.print_rows(&rows);
        return Ok(());
    }

    let manifest = Manifest::load(paths)?;
    if let Some(item_ref) = item {
        let parsed = parse_item_ref(item_ref)?;
        let found = crate::resolve::resolve_installed(&manifest.items, &parsed)?;
        if json {
            return print_json(found);
        }
        println!("{}", out.bold(&found.key()));
        if let Some(d) = &found.description {
            println!("  {}{d}", out.dim("desc    "));
        }
        println!("  {}{}", out.dim("source  "), found.source);
        println!("  {}{}", out.dim("commit  "), short(&found.commit));
        println!("  {}{}", out.dim("hash    "), short(&found.hash));
        println!(
            "  {}{}",
            out.dim("store   "),
            paths.mind_home.join(&found.store).display()
        );
        for link in &found.links {
            println!("  {}{link}", out.dim("link    "));
        }
        // CLI-75 / LIFE-11: mark out of date exactly when `upgrade` would act --
        // source-content hash changed, or effective name changed (rename).
        {
            let registry = Registry::load(paths)?;
            let catalog = catalog::scan(paths, &registry)?;
            if let Some(cat) = catalog.iter().find(|c| {
                c.kind == found.kind && c.name == found.bare_name && c.source == found.source
            }) {
                // CLI-75: a hash error counts as drift (see the recall listing
                // site); the marker errs toward flagging rather than hiding it.
                let hash_lag = hash_path(&cat.path).map_or(true, |h| h != found.hash);
                let rename_lag = cat.effective_name() != found.name;
                if hash_lag || rename_lag {
                    println!(
                        "  {}{}",
                        out.dim("status  "),
                        out.yellow("out of date; run `mind upgrade`")
                    );
                }
            }
        }
        return Ok(());
    }

    // CLI-70/74: the status view -- each melded source with its catalog items
    // nested beneath it, every item marked installed (with commit) or available.
    // Items installed but no longer in the source's catalog (removed upstream) are
    // shown too, marked. `--kind`/`--source` filter what is shown.
    let registry = Registry::load(paths)?;
    let catalog = catalog::scan(paths, &registry)?;
    let filtering = kind.is_some() || source.is_some();

    // The source's catalog items (honoring --kind), sorted by key.
    let cat_items = |s: &crate::source::Source| -> Vec<&CatalogItem> {
        let mut v: Vec<&CatalogItem> = catalog
            .iter()
            .filter(|it| it.source == s.name && kind.is_none_or(|k| it.kind == k))
            .collect();
        v.sort_by_key(|x| x.key());
        v
    };
    // Installed items of a source with no catalog match (removed upstream). An
    // item is an orphan only when NO catalog item shares its stable identity
    // (source, kind, bare_name). A pure namespace/prefix rename keeps the same
    // bare identity, so it is NOT an orphan -- it is matched in the status loop
    // and marked outdated. A genuinely removed-upstream item has no such match.
    let orphans_of = |s: &crate::source::Source| -> Vec<&crate::manifest::InstalledItem> {
        let mut v: Vec<&crate::manifest::InstalledItem> = manifest
            .items
            .values()
            .filter(|m| {
                m.source == s.name
                    && kind.is_none_or(|k| m.kind == k)
                    && !catalog.iter().any(|it| {
                        it.source == m.source && it.kind == m.kind && it.name == m.bare_name
                    })
            })
            .collect();
        v.sort_by_key(|x| x.key());
        v
    };
    // CLI-86: the `--source` filter accepts a glob, matched against each source's
    // identity and trailing-suffix forms; a multi-source match is the normal case.
    let source_shown =
        |s: &crate::source::Source| source.is_none_or(|q| source_matches_glob(&s.name, q));

    if json {
        let out: Vec<serde_json::Value> = registry
            .sources
            .iter()
            .filter(|s| source_shown(s))
            .map(|s| {
                let items = cat_items(s);
                let mut rows: Vec<serde_json::Value> = items
                    .iter()
                    .map(|it| {
                        // Match by stable identity (source, kind, bare_name) so a
                        // renamed item still resolves to its manifest entry.
                        let inst = manifest.items.values().find(|m| {
                            m.source == it.source && m.kind == it.kind && m.bare_name == it.name
                        });
                        serde_json::json!({
                            "key": it.key(),
                            "installed": inst.is_some(),
                            "commit": inst.map(|m| m.commit.clone()),
                        })
                    })
                    .collect();
                for m in orphans_of(s) {
                    rows.push(serde_json::json!({
                        "key": m.key(),
                        "installed": true,
                        "commit": m.commit.clone(),
                        "orphaned": true,
                    }));
                }
                serde_json::json!({
                    "name": s.name,
                    "url": s.url,
                    "commit": s.commit,
                    "alias": s.alias,
                    "items": rows,
                })
            })
            .collect();
        return print_json(&out);
    }

    if registry.sources.is_empty() {
        println!("no sources melded; `mind meld <repo>` to add one");
        // Fall through: unmanaged lobe items are still worth showing (UNM-2).
    }

    for s in &registry.sources {
        if !source_shown(s) {
            continue;
        }
        let items = cat_items(s);
        let orphans = orphans_of(s);
        if items.is_empty() && orphans.is_empty() && filtering {
            continue; // a filter excluded everything this source offers
        }
        let commit = s
            .commit
            .as_deref()
            .map(short)
            .unwrap_or_else(|| "unsynced".into());
        let ns = match &s.alias {
            Some(a) => format!(" namespace:{a}"),
            None => String::new(),
        };
        let hook = match s.install_hooks.len() {
            0 => String::new(),
            1 => " hook".to_string(),
            n => format!(" hooks({n})"),
        };
        // MKT-10: show the manifest origin in the source header so the
        // provenance is visible in the default recall view too.
        let origin = origin_label(s.origin);
        println!(
            "{} {}  {}{}",
            out.bullet(),
            out.bold(&s.name),
            out.dim(&format!("[{commit}{ns}{hook}{origin}]")),
            s.description
                .as_deref()
                .map(|d| format!("  {d}"))
                .unwrap_or_default()
        );
        // Each item is a status-marked row; print_rows aligns the key column even
        // with the leading glyph (its visible width ignores any ANSI codes).
        let mut rows: Vec<Vec<String>> = Vec::new();
        for it in items {
            let key = it.key();
            // Match by stable identity (source, kind, bare_name), as source_status,
            // the single-item detail, and probe do, so a pure namespace/prefix
            // rename (effective name changed, bare identity unchanged) still
            // resolves to its manifest entry and is marked outdated rather than
            // misclassified as available + removed-upstream.
            let installed = manifest
                .items
                .values()
                .find(|m| m.source == it.source && m.kind == it.kind && m.bare_name == it.name);
            match installed {
                Some(m) => {
                    // CLI-75 / LIFE-11: mark out of date exactly when `upgrade`
                    // would act -- source-content hash changed, or effective name
                    // changed (rename). Commit advance alone does not trigger this.
                    // CLI-75: a hash error counts as drift (see the recall listing
                    // site); the marker errs toward flagging rather than hiding it.
                    let hash_lag = hash_path(&it.path).map_or(true, |h| h != m.hash);
                    let rename_lag = it.effective_name() != m.name;
                    let lag = hash_lag || rename_lag;
                    let outdated = if lag {
                        format!("  {}", out.yellow("(outdated; run mind upgrade)"))
                    } else {
                        String::new()
                    };
                    // A stale install gets its own marker (↑), distinct from a
                    // current install (✓): installed but not up to date.
                    let marker = if lag { out.stale() } else { out.ok() };
                    rows.push(vec![
                        format!("  {marker}"),
                        key,
                        format!("installed @ {}{}", out.green(&short(&m.commit)), outdated),
                    ]);
                }
                None => rows.push(vec![
                    format!("  {}", out.available()),
                    out.dim(&key),
                    out.dim("available"),
                ]),
            }
        }
        for m in orphans {
            rows.push(vec![
                format!("  {}", out.warn()),
                m.key(),
                format!(
                    "installed @ {} {}",
                    short(&m.commit),
                    out.yellow("(removed upstream)")
                ),
            ]);
        }
        out.print_rows(&rows);
    }

    // UNM-2: list unmanaged lobe items after the sources. Human view only;
    // `recall --json` keeps its sources-only schema (CLI-73). `--source` excludes
    // them (they have no source); `--kind` filters as it does managed items.
    if source.is_none() {
        let unmanaged: Vec<crate::unmanaged::UnmanagedItem> =
            crate::unmanaged::scan(paths, &manifest)?
                .into_iter()
                .filter(|u| kind.is_none_or(|k| u.kind == k))
                .collect();
        if !unmanaged.is_empty() {
            println!(
                "{} {}",
                out.bullet(),
                out.bold("unmanaged: not installed by mind")
            );
            let rows: Vec<Vec<String>> = unmanaged
                .iter()
                .map(|u| {
                    let where_ = u
                        .paths
                        .iter()
                        .map(|p| p.display().to_string())
                        .collect::<Vec<_>>()
                        .join(", ");
                    vec![format!("  {}", out.warn()), u.key(), out.dim(&where_)]
                })
                .collect();
            out.print_rows(&rows);
        }
    }
    Ok(())
}

/// `mind probe [query] [--kind K] [--source S] [--json]`. A leading `*` marks
/// installed items; the hash is of the current source content. `--kind` and
/// `--source` narrow the listing and compose with the substring query. `--json`
/// emits the rows as JSON on stdout.
pub fn probe(
    paths: &Paths,
    query: Option<&str>,
    kind: Option<ItemKind>,
    source: Option<&str>,
    json: bool,
) -> Result<()> {
    let out = crate::render::ctx();
    // CLI-86: the `--source` glob filter shares `source_matches_glob`; reject a
    // malformed pattern up front rather than silently matching nothing.
    if let Some(s) = source {
        crate::resolve::validate_source_selector(s)?;
    }
    let registry = Registry::load(paths)?;
    let items = catalog::scan(paths, &registry)?;
    let manifest = Manifest::load(paths)?;
    let q = query.unwrap_or("");
    let mut hits: Vec<&CatalogItem> = items
        .iter()
        .filter(|it| {
            catalog::matches_query(it, q) // spec: CLI-85
                && kind.is_none_or(|k| it.kind == k)
                // CLI-86: `--source` accepts a glob over source identities.
                && source.is_none_or(|s| source_matches_glob(&it.source, s))
        })
        .collect();
    hits.sort_by_key(|a| a.key());

    let installed = |it: &CatalogItem| {
        manifest
            .items
            .values()
            .any(|m| m.source == it.source && m.kind == it.kind && m.bare_name == it.name)
    };

    // UNM-3: unmanaged lobe items, matched by name (CLI-85) and `--kind`. A
    // `--source` filter excludes them, since they have no source.
    let mut unmanaged: Vec<crate::unmanaged::UnmanagedItem> = if source.is_none() {
        let needle = q.to_lowercase();
        crate::unmanaged::scan(paths, &manifest)?
            .into_iter()
            .filter(|u| kind.is_none_or(|k| u.kind == k) && u.name.to_lowercase().contains(&needle))
            .collect()
    } else {
        Vec::new()
    };
    unmanaged.sort_by_key(|u| u.key());

    if json {
        // spec: DEP-62
        let mut rows: Vec<ProbeRow> = hits
            .iter()
            .map(|it| {
                // DEP-62: add direct dependency keys to each catalog row.
                let dependencies = crate::deps::direct_dependency_keys(it, &items, &read_item_text);
                ProbeRow {
                    installed: installed(it),
                    kind: it.kind.as_str(),
                    name: it.effective_name(),
                    source: &it.source,
                    hash: hash_path(&it.path).ok(),
                    description: it.description.as_deref(),
                    unmanaged: false,
                    dependencies,
                }
            })
            .collect();
        for u in &unmanaged {
            rows.push(ProbeRow {
                installed: false,
                kind: u.kind.as_str(),
                name: u.name.clone(),
                source: "",
                hash: None,
                description: None,
                unmanaged: true,
                dependencies: Vec::new(),
            });
        }
        return print_json(&rows);
    }

    if hits.is_empty() && unmanaged.is_empty() {
        if registry.sources.is_empty() {
            println!("no sources melded; run `mind meld <owner/repo>`");
        } else {
            println!("no items match '{q}'");
        }
        return Ok(());
    }

    // spec: DEP-62
    // Human listing: nest each hit's transitive dependencies beneath it. Build a
    // graph over all catalog items (passing every catalog key as the "installed"
    // set makes every item a node), then render_subtree for each hit.
    let all_catalog_keys: HashSet<String> = items.iter().map(|it| it.key()).collect();
    let catalog_graph = crate::deps::installed_graph(&items, &all_catalog_keys, read_item_text);

    let mut rows = Vec::new();
    for it in &hits {
        let cur = hash_path(&it.path).ok();
        let hash = cur.as_deref().map(short).unwrap_or_else(|| "-".into());
        // The matched installed item, if any, for the install marker and the
        // out-of-date check (CLI-75).
        let m = manifest
            .items
            .values()
            .find(|m| m.source == it.source && m.kind == it.kind && m.bare_name == it.name);
        // CLI-75 / LIFE-11: mark out of date exactly when `upgrade` would
        // act -- source-content hash changed, or effective name changed
        // (rename). Commit advance alone does not trigger this.
        let outdated = m.is_some_and(|m| {
            // CLI-75: a hash error (cur == None) counts as drift; the marker
            // errs toward flagging rather than reading "cannot hash" as up to
            // date, consistent with the other three marker sites.
            let hash_drift = cur.as_deref().is_none_or(|h| h != m.hash);
            let rename_drift = it.effective_name() != m.name;
            hash_drift || rename_drift
        });
        // CLI-81: a leading `*` marks an installed item (greened when color is
        // on). Not-installed rows have an empty marker cell so the row does not
        // start with `*`.
        let marker = if m.is_some() {
            out.green("*")
        } else {
            String::new()
        };
        let mut desc = summary(it.description.as_deref(), 60);
        if outdated {
            desc = format!("{desc} {}", out.yellow("(outdated; run `mind upgrade`)"));
        }
        rows.push(vec![
            marker,
            it.key(),
            out.dim(&it.source),
            out.dim(&hash),
            desc,
        ]);

        // DEP-62: nest transitive dependencies beneath each hit. Use the
        // catalog graph to render a subtree; each dependency line is indented
        // with two leading spaces so it reads as a child of the hit above.
        // Cycle back-edges are marked (cycle) by render_subtree/render_forest.
        if let Some(subtree) = catalog_graph.render_subtree(&it.key()) {
            // The subtree includes the root (it.key()) at depth 0; skip it
            // and emit only the nested child lines (depth >= 1).
            for line in subtree.lines().skip(1) {
                rows.push(vec![
                    String::new(),
                    line.to_string(),
                    String::new(),
                    String::new(),
                    String::new(),
                ]);
            }
        }
    }
    // UNM-3: unmanaged rows are marked in the source column and carry their lobe
    // path in place of a description. No dependency nesting for unmanaged items.
    for u in &unmanaged {
        let where_ = u
            .paths
            .iter()
            .map(|p| p.display().to_string())
            .collect::<Vec<_>>()
            .join(", ");
        rows.push(vec![
            String::new(),
            u.key(),
            out.dim("(unmanaged)"),
            out.dim("-"),
            out.dim(&where_),
        ]);
    }
    out.print_rows(&rows);
    Ok(())
}

/// One `probe --json` row. `unmanaged` is omitted for managed (catalog) rows, so
/// the existing schema is unchanged; an unmanaged row sets it true with no
/// `hash` and an empty `source`. `dependencies` lists the direct dependency keys
/// for catalog (managed) rows (DEP-62); empty for unmanaged rows.
#[derive(Serialize)]
struct ProbeRow<'a> {
    installed: bool,
    kind: &'a str,
    name: String,
    source: &'a str,
    hash: Option<String>,
    description: Option<&'a str>,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    unmanaged: bool,
    /// Direct dependency keys (DEP-62). Empty for unmanaged rows. Omitted when
    /// the vec is empty so existing consumers that do not need deps see no change.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    dependencies: Vec<String>,
}

/// One diagnostic finding from `introspect`. `kind` is a stable machine tag;
/// `message` is the human line.
#[derive(Serialize)]
struct Issue {
    kind: &'static str,
    target: String,
    message: String,
}

/// `mind introspect [--fix] [--json]` — report drift and breakage. With `--fix`,
/// repair what can be fixed without changing versions: recreate missing symlinks
/// from each item's file registry. Drifted or renamed items are left to
/// `upgrade`. `--json` emits the findings as JSON on stdout.
pub fn introspect(paths: &Paths, fix: bool, json: bool) -> Result<()> {
    let registry = Registry::load(paths)?;
    let catalog = catalog::scan(paths, &registry)?;
    let mut manifest = Manifest::load(paths)?;
    let mut issues: Vec<Issue> = Vec::new();
    let mut repaired: Vec<String> = Vec::new();
    // HARN-8: `--fix` may create new lobe links; record whether we mutated the
    // manifest so it is saved once after the loop.
    let mut manifest_dirty = false;
    let all_lobes = paths.agent_homes()?;

    for s in &registry.sources {
        if !s.clone_dir(paths).join(".git").is_dir() {
            issues.push(Issue {
                kind: "no-clone",
                target: s.name.clone(),
                message: format!("source '{}' has no clone on disk; run `mind sync`", s.name),
            });
        } else if s.commit.is_none() {
            issues.push(Issue {
                kind: "never-synced",
                target: s.name.clone(),
                message: format!("source '{}' was never synced; run `mind sync`", s.name),
            });
        }
    }

    for it in manifest.items.values_mut() {
        let missing: Vec<String> = it
            .links
            .iter()
            .filter(|link| std::fs::symlink_metadata(link).is_err())
            .cloned()
            .collect();
        if !missing.is_empty() {
            // With --fix, re-link from the store copy; report only what cannot
            // be repaired (e.g. the store copy itself is gone).
            let n = if fix { install::relink(paths, it)? } else { 0 };
            if n > 0 {
                repaired.push(format!("{}: relinked {n} missing symlink(s)", it.key()));
            }
            for link in &missing {
                if std::fs::symlink_metadata(link).is_err() {
                    issues.push(Issue {
                        kind: "missing-link",
                        target: it.key(),
                        message: format!("{}: symlink missing at {link}", it.key()),
                    });
                }
            }
        }
        // HARN-8: check that the item is linked into every configured lobe that
        // admits its kind. A link that is in the manifest but not on disk is
        // already handled above (missing-link). This checks for lobes that were
        // added after the item was installed -- the link would be absent from
        // both the manifest and disk.
        let link_rel = it
            .links
            .iter()
            .find_map(|link_str| {
                let link = std::path::Path::new(link_str);
                all_lobes
                    .iter()
                    .find_map(|lobe| link.strip_prefix(&lobe.path).ok())
                    .map(|rel| rel.to_string_lossy().into_owned())
            })
            .or_else(|| paths.default_link_rel(it.kind, &it.name));
        if let Some(rel) = link_rel {
            for lobe in &all_lobes {
                if !lobe.admits(it.kind) {
                    continue;
                }
                let expected = lobe.path.join(&rel);
                let expected_str = expected.to_string_lossy().into_owned();
                let in_manifest = it.links.iter().any(|l| l == &expected_str);
                let on_disk = std::fs::symlink_metadata(&expected).is_ok();
                if in_manifest && on_disk {
                    continue;
                }
                if fix {
                    let (created, errs) =
                        install::link_into_new_lobes(paths, it, std::slice::from_ref(lobe));
                    if !created.is_empty() {
                        it.links.extend(
                            created
                                .into_iter()
                                .map(|p| p.to_string_lossy().into_owned()),
                        );
                        manifest_dirty = true;
                        repaired.push(format!(
                            "{}: linked into new lobe {}",
                            it.key(),
                            lobe.path.display()
                        ));
                    }
                    for (p, e) in errs {
                        issues.push(Issue {
                            kind: "missing-lobe-link",
                            target: it.key(),
                            message: format!("{}: {e}", p.display()),
                        });
                    }
                } else {
                    issues.push(Issue {
                        kind: "missing-lobe-link",
                        target: it.key(),
                        message: format!(
                            "{}: not linked into lobe {}; run `mind introspect --fix`",
                            it.key(),
                            lobe.path.display()
                        ),
                    });
                }
            }
        }
        // Match on stable identity (source, kind, bare_name).
        match catalog
            .iter()
            .find(|c| c.kind == it.kind && c.name == it.bare_name && c.source == it.source)
        {
            None => issues.push(Issue {
                kind: "removed-upstream",
                target: it.key(),
                message: format!("{}: no longer present in source '{}'", it.key(), it.source),
            }),
            Some(cat) => {
                if cat.effective_name() != it.name {
                    issues.push(Issue {
                        kind: "namespace-changed",
                        target: it.key(),
                        message: format!(
                            "{}: namespace changed to '{}'; run `mind upgrade`",
                            it.key(),
                            cat.effective_name()
                        ),
                    });
                } else if let Ok(h) = hash_path(&cat.path)
                    && h != it.hash
                {
                    issues.push(Issue {
                        kind: "drifted",
                        target: it.key(),
                        message: format!("{}: upstream changed; run `mind upgrade`", it.key()),
                    });
                }
            }
        }
    }

    if fix && manifest_dirty {
        manifest.save(paths)?;
    }

    if json {
        #[derive(Serialize)]
        struct Report<'a> {
            issues: &'a [Issue],
            sources: usize,
            items: usize,
        }
        return print_json(&Report {
            issues: &issues,
            sources: registry.sources.len(),
            items: manifest.items.len(),
        });
    }

    let out = crate::render::ctx();
    for note in &repaired {
        println!("{} {note}", out.ok());
    }
    for issue in &issues {
        println!("{} {}", out.warn(), issue.message);
    }
    if issues.is_empty() {
        println!(
            "{} all good: {} source(s), {} item(s) installed",
            out.ok(),
            registry.sources.len(),
            manifest.items.len()
        );
    } else {
        println!("\n{} {} issue(s) found", out.err(), issues.len());
    }
    Ok(())
}

/// `mind review <target> [--as <prefix>]` — validate a source for publishing.
///
/// Read-only. Collects hard errors and advisory findings; hard errors cause a
/// non-zero exit (CLI-132). Installs nothing and changes nothing on disk.
///
/// spec: CLI-130, CLI-131, CLI-132, CLI-133
pub fn review(paths: &Paths, target: &str, alias: Option<String>, fix: bool) -> Result<()> {
    let result = crate::review::review(paths, target, alias, fix)?;

    // Print hard then advisory findings in the shared format.
    crate::review::print_findings(&result.hard, &result.advisory);

    let out = crate::render::ctx();
    // Report any files `--fix` rewrote.
    for f in &result.fixed {
        println!("{} fixed {f}", out.ok());
    }

    if result.hard.is_empty() {
        if result.advisory.is_empty() {
            println!("{} review: no issues found", out.ok());
        } else {
            println!(
                "{} review: {} advisory finding(s); source is publishable",
                out.warn(),
                result.advisory.len()
            );
        }
        Ok(())
    } else {
        println!(
            "\n{} review: {} hard error(s), {} advisory finding(s)",
            out.err(),
            result.hard.len(),
            result.advisory.len()
        );
        Err(crate::error::MindError::ReviewFailed {
            hard: result.hard.len(),
        })
    }
}

/// `mind config show` — print the config file location and its key/value pairs.
pub fn config_show(paths: &Paths) -> Result<()> {
    let out = crate::render::ctx();
    paths.ensure_config()?;
    let file = paths.config_file();
    let cfg = Config::load(paths)?;
    if out.json {
        return print_json(&serde_json::json!({
            "config_file": file.display().to_string(),
            "lobes": cfg.lobes,
            "default_lobe": paths.claude_home.display().to_string(),
            "ssh": cfg.ssh,
        }));
    }
    println!("{} config file: {}", out.bullet(), file.display());
    if cfg.lobes.is_empty() {
        println!(
            "  {} lobes = []  (default: {})",
            out.dim("·"),
            paths.claude_home.display()
        );
    } else {
        let rendered: Vec<String> = cfg.lobes.iter().map(format_lobe).collect();
        println!("  {} lobes = {}", out.dim("·"), rendered.join(", "));
    }
    println!(
        "  {} ssh = {}  (prefer SSH for melded remotes)",
        out.dim("·"),
        cfg.ssh
    );
    if let Some(env) = std::env::var_os("MIND_AGENT_HOMES") {
        println!(
            "note: MIND_AGENT_HOMES is set and overrides lobes: {}",
            env.to_string_lossy()
        );
    }
    Ok(())
}

/// Render a lobe entry for display: the path, plus its `kinds` filter in brackets
/// when present (HARN-1). A no-kinds lobe shows just the path (it admits all).
fn format_lobe(entry: &crate::config::LobeEntry) -> String {
    match entry.kinds() {
        None => entry.path().to_string(),
        Some(kinds) => {
            let names: Vec<&str> = kinds.iter().map(|k| k.as_str()).collect();
            format!("{} [{}]", entry.path(), names.join(", "))
        }
    }
}

/// Backfill all installed items into `new_lobes`. Called after a lobe is added
/// so existing items also land in the new home. With `yes = true`, applies
/// unconditionally; otherwise prompts on a TTY or defers to `introspect --fix`
/// in non-TTY / JSON mode (HARN-8).
fn backfill_new_lobes(paths: &Paths, new_lobes: &[crate::paths::Lobe], yes: bool) -> Result<()> {
    let out = crate::render::ctx();
    let mut manifest = Manifest::load(paths)?;
    if manifest.items.is_empty() {
        return Ok(());
    }

    let do_backfill = if yes {
        true
    } else if !out.json && crate::hook::is_tty() {
        confirm_default_yes(&format!(
            "Link {} installed item(s) into {} new lobe(s)?",
            manifest.items.len(),
            new_lobes.len()
        ))?
    } else if !out.json {
        println!("note: run `mind introspect --fix` to link installed items into new lobe(s)");
        return Ok(());
    } else {
        return Ok(());
    };

    if !do_backfill {
        return Ok(());
    }

    for item in manifest.items.values_mut() {
        let (created, errs) = install::link_into_new_lobes(paths, item, new_lobes);
        item.links.extend(
            created
                .into_iter()
                .map(|p| p.to_string_lossy().into_owned()),
        );
        for (p, e) in errs {
            println!("{} could not link {}: {e}", out.warn(), p.display());
        }
    }
    manifest.save(paths)?;
    Ok(())
}

/// Convert detected-lobe candidates (name + config entry) into resolved
/// [`Lobe`]s for backfill (HARN-7). Each entry's path is used verbatim (the
/// detection base produces absolute paths) with its declared `kinds` filter.
fn candidates_to_lobes(
    candidates: &[(&'static str, crate::config::LobeEntry)],
) -> Vec<crate::paths::Lobe> {
    candidates
        .iter()
        .map(|(_, entry)| crate::paths::Lobe {
            path: std::path::PathBuf::from(entry.path()),
            kinds: entry.kinds().map(|ks| ks.to_vec()),
        })
        .collect()
}

/// `mind config lobes add <path>` — add an agent home by path.
pub fn lobe_add(paths: &Paths, path: &str, yes: bool) -> Result<()> {
    let out = crate::render::ctx();
    // POL-40: a lobe lock pins the effective agent homes; refuse and change
    // nothing. Load the policy first so the refusal precedes any config write.
    if let Some(policy) = Policy::load()?
        && policy.lobes_lock()
    {
        return Err(lobes_locked_error("add"));
    }
    paths.ensure_config()?;
    let mut cfg = Config::load(paths)?;
    if cfg.lobes.iter().any(|e| e.path() == path) {
        if out.json {
            return print_json(&MutationResult::new("lobe-add", path, "no-op"));
        }
        println!("{} lobe already configured: {path}", out.available());
        return Ok(());
    }
    // spec: HARN-9 -- preserve the implicit claude_home default when this is
    // the first explicit lobe. Without this the default is silently replaced
    // by the configured list and new installs no longer reach ~/.claude.
    if cfg.lobes.is_empty() {
        let ch = paths.claude_home.to_string_lossy().into_owned();
        if ch.as_str() != path {
            cfg.lobes.push(crate::config::LobeEntry::bare(&ch));
        }
    }
    cfg.lobes.push(crate::config::LobeEntry::bare(path));
    cfg.save(paths)?;
    if out.json {
        backfill_new_lobes(
            paths,
            &[crate::paths::Lobe::all_kinds(std::path::PathBuf::from(
                path,
            ))],
            yes,
        )?;
        return print_json(&MutationResult::new("lobe-add", path, "added"));
    }
    println!("{} added lobe {path}", out.ok());
    backfill_new_lobes(
        paths,
        &[crate::paths::Lobe::all_kinds(std::path::PathBuf::from(
            path,
        ))],
        yes,
    )?;
    Ok(())
}

/// `mind config lobes add --preset <name>` — add a known harness preset's lobe
/// (its parent path and `kinds` filter) (HARN-4).
pub fn lobe_add_preset(paths: &Paths, name: &str, yes: bool) -> Result<()> {
    let out = crate::render::ctx();
    // POL-40: refuse under a lobe lock before validating or writing anything.
    if let Some(policy) = Policy::load()?
        && policy.lobes_lock()
    {
        return Err(lobes_locked_error("add"));
    }
    // Resolve (and validate) the preset before touching config.
    let lobe = Paths::preset_lobe(name)?;
    let path = lobe.path.to_string_lossy().into_owned();
    let entry = crate::config::LobeEntry {
        path: path.clone(),
        kinds: lobe.kinds.clone(),
    };
    paths.ensure_config()?;
    let mut cfg = Config::load(paths)?;
    if cfg.lobes.iter().any(|e| e.path() == path) {
        if out.json {
            return print_json(&MutationResult::new("lobe-add", &path, "no-op"));
        }
        println!("{} lobe already configured: {path}", out.available());
        return Ok(());
    }
    // spec: HARN-9
    if cfg.lobes.is_empty() {
        let ch = paths.claude_home.to_string_lossy().into_owned();
        if ch.as_str() != path {
            cfg.lobes.push(crate::config::LobeEntry::bare(&ch));
        }
    }
    cfg.lobes.push(entry.clone());
    cfg.save(paths)?;
    if out.json {
        backfill_new_lobes(paths, std::slice::from_ref(&lobe), yes)?;
        return print_json(&MutationResult::new("lobe-add", &path, "added"));
    }
    println!("{} added {name} lobe {}", out.ok(), format_lobe(&entry));
    backfill_new_lobes(paths, std::slice::from_ref(&lobe), yes)?;
    Ok(())
}

/// `mind config lobes list` — list configured agent homes, with each lobe's
/// `kinds` filter when it carries one (HARN-1).
pub fn lobe_list(paths: &Paths) -> Result<()> {
    let out = crate::render::ctx();
    paths.ensure_config()?;
    let cfg = Config::load(paths)?;
    if out.json {
        if cfg.lobes.is_empty() {
            let default = crate::config::LobeEntry::bare(paths.claude_home.display().to_string());
            return print_json(&serde_json::json!({ "lobes": [default] }));
        }
        return print_json(&serde_json::json!({ "lobes": cfg.lobes }));
    }
    if cfg.lobes.is_empty() {
        println!("{}  (default)", paths.claude_home.display());
    } else {
        for e in &cfg.lobes {
            println!("{}", format_lobe(e));
        }
    }
    // POL-40: under a managed lobe lock, `Paths::agent_homes` ignores
    // $MIND_AGENT_HOMES, so the override note would be false. Suppress it when a
    // policy is in effect and lobes are locked; otherwise behavior is unchanged.
    let lobes_locked = matches!(Policy::load()?, Some(p) if p.lobes_lock());
    if show_override_note(std::env::var_os("MIND_AGENT_HOMES").is_some(), lobes_locked) {
        println!("note: MIND_AGENT_HOMES is set and overrides the above");
    }
    Ok(())
}

/// POL-40: the `config lobes list` override note is shown only when
/// `$MIND_AGENT_HOMES` is set AND it actually takes effect. Under a managed lobe
/// lock `Paths::agent_homes` ignores the env var, so the note would be false;
/// suppress it.
fn show_override_note(env_set: bool, lobes_locked: bool) -> bool {
    env_set && !lobes_locked
}

/// `mind config lobes remove <path>` — drop an agent home.
pub fn lobe_remove(paths: &Paths, path: &str) -> Result<()> {
    let out = crate::render::ctx();
    // POL-40: a lobe lock pins the effective agent homes; refuse and change
    // nothing.
    if let Some(policy) = Policy::load()?
        && policy.lobes_lock()
    {
        return Err(lobes_locked_error("remove"));
    }
    paths.ensure_config()?;
    let mut cfg = Config::load(paths)?;
    let before = cfg.lobes.len();
    cfg.lobes.retain(|e| e.path() != path);
    if cfg.lobes.len() == before {
        return Err(MindError::UnknownLobe {
            path: path.to_string(),
        });
    }
    cfg.save(paths)?;
    if out.json {
        return print_json(&MutationResult::new("lobe-remove", path, "removed"));
    }
    println!("{} removed lobe {path}", out.ok());
    Ok(())
}

/// `mind config lobes detect` — detect installed harness homes and offer to add
/// their presets (HARN-5). Detection itself never mutates config: it adds the
/// detected lobes only with `--yes` (or, on a TTY, after a confirm prompt).
/// Without a TTY and without `--yes`, it reports only. Honors the POL-40 lobe
/// lock and dedups against the already-configured lobes.
pub fn lobe_detect(paths: &Paths, yes: bool) -> Result<()> {
    let out = crate::render::ctx();
    // POL-40: refuse under a lobe lock before reporting or writing anything.
    if let Some(policy) = Policy::load()?
        && policy.lobes_lock()
    {
        return Err(lobes_locked_error("detect"));
    }
    paths.ensure_config()?;
    let mut cfg = Config::load(paths)?;
    let configured: HashSet<String> = cfg.lobes.iter().map(|e| e.path().to_string()).collect();

    // Dedup detected lobes against the configured set and against each other
    // (codex and universal can both point at ~/.agents).
    let detected = Paths::detect_homes()?;
    let mut seen: HashSet<std::path::PathBuf> = HashSet::new();
    let mut candidates: Vec<(&'static str, crate::config::LobeEntry)> = Vec::new();
    for (name, lobe) in detected {
        let path = lobe.path.to_string_lossy().into_owned();
        if configured.contains(&path) || !seen.insert(lobe.path.clone()) {
            continue;
        }
        candidates.push((
            name,
            crate::config::LobeEntry {
                path,
                kinds: lobe.kinds.clone(),
            },
        ));
    }

    // Decide whether to mutate. With --yes, add unconditionally. Without it, a
    // TTY gets a confirm prompt; a non-TTY reports only (HARN-5).
    let do_add = if candidates.is_empty() {
        false
    } else if yes {
        true
    } else if crate::hook::is_tty() {
        let names: Vec<String> = candidates
            .iter()
            .map(|(n, e)| format!("{n} ({})", format_lobe(e)))
            .collect();
        confirm(&format!("add detected lobe(s): {}?", names.join(", ")))?
    } else {
        false
    };

    if out.json {
        let detected_json: Vec<serde_json::Value> = candidates
            .iter()
            .map(|(name, entry)| {
                serde_json::json!({
                    "preset": name,
                    "path": entry.path(),
                    "kinds": entry.kinds().map(|ks| {
                        ks.iter().map(|k| k.as_str()).collect::<Vec<_>>()
                    }),
                })
            })
            .collect();
        if do_add {
            // spec: HARN-9
            if cfg.lobes.is_empty() {
                let ch = paths.claude_home.to_string_lossy().into_owned();
                if !candidates.iter().any(|(_, e)| e.path() == ch.as_str()) {
                    cfg.lobes.push(crate::config::LobeEntry::bare(&ch));
                }
            }
            for (_, entry) in &candidates {
                cfg.lobes.push(entry.clone());
            }
            cfg.save(paths)?;
            let new_lobes = candidates_to_lobes(&candidates);
            backfill_new_lobes(paths, &new_lobes, yes)?;
        }
        return print_json(&serde_json::json!({
            "action": "lobe-detect",
            "detected": detected_json,
            "added": do_add,
        }));
    }

    if candidates.is_empty() {
        println!("{} no new harness homes detected", out.bullet());
        return Ok(());
    }

    if do_add {
        // spec: HARN-9
        if cfg.lobes.is_empty() {
            let ch = paths.claude_home.to_string_lossy().into_owned();
            if !candidates.iter().any(|(_, e)| e.path() == ch.as_str()) {
                cfg.lobes.push(crate::config::LobeEntry::bare(&ch));
            }
        }
        for (name, entry) in &candidates {
            cfg.lobes.push(entry.clone());
            println!("{} added {name} lobe {}", out.ok(), format_lobe(entry));
        }
        cfg.save(paths)?;
        let new_lobes = candidates_to_lobes(&candidates);
        backfill_new_lobes(paths, &new_lobes, yes)?;
    } else {
        println!("{} detected harness home(s):", out.bullet());
        for (name, entry) in &candidates {
            println!("  {} {name}: {}", out.dim("·"), format_lobe(entry));
        }
        println!("re-run with --yes to add them");
    }
    Ok(())
}

/// `mind completions <shell>` — write a shell completion script to stdout.
pub fn completions(shell: clap_complete::Shell) {
    use clap::CommandFactory;
    let mut cmd = crate::cli::Cli::command();
    clap_complete::generate(shell, &mut cmd, "mind", &mut std::io::stdout());
}

/// `mind man` — write the roff man page to stdout.
pub fn man() -> Result<()> {
    use clap::CommandFactory;
    let mut out = Vec::new();
    clap_mangen::Man::new(crate::cli::Cli::command())
        .render(&mut out)
        .map_err(|e| MindError::io("<man>", e))?;
    std::io::stdout()
        .write_all(&out)
        .map_err(|e| MindError::io("<stdout>", e))
}

// --- helpers ---------------------------------------------------------------

/// Build the refusal error for a locked `config lobes <action>` (POL-40). The
/// effective agent homes are pinned by `[lobes].lock`, so the action changes
/// nothing.
fn lobes_locked_error(action: &str) -> MindError {
    MindError::LobesLocked {
        action: action.to_string(),
    }
}

/// A source entry that was skipped during meld or sync due to an auth failure
/// with `on-auth-failure.action = "skip"` (DSC-68, DSC-69).
#[derive(Serialize, Debug, PartialEq, Eq)]
pub(crate) struct SkippedEntry {
    source: String,
    reason: String,
}

/// Data returned by `meld()` so the dispatcher can combine it with the
/// post-meld install outcome into ONE JSON object (CLI-153, CLI-156).
pub(crate) struct MeldSummary {
    pub(crate) source_name: String,
    pub(crate) added: usize,
    pub(crate) skipped: Vec<SkippedEntry>,
}

/// The structured result a mutating verb emits under `--json` (CLI-153).
/// `action` is the verb, `target` the item/source ref it acted on, and `outcome`
/// a stable token (`installed|removed|melded|synced|upgraded|renamed|no-op|...`).
/// Optional fields are only serialized when a verb genuinely returns more (e.g.
/// `learn` fills `installed` with its closure keys; `sync` fills `count`).
#[derive(Serialize, Debug, PartialEq, Eq)]
struct MutationResult {
    action: &'static str,
    target: String,
    outcome: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    count: Option<usize>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    installed: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    removed: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    skipped: Vec<SkippedEntry>,
    /// Count of items available to install but not yet installed (no `--yes` given).
    /// Only set for `meld` JSON results when items are pending (CLI-156).
    #[serde(skip_serializing_if = "Option::is_none")]
    pending_items: Option<usize>,
    /// The managed `kind:name` key after a successful absorb (ABS-11).
    #[serde(skip_serializing_if = "Option::is_none")]
    key: Option<String>,
}

impl MutationResult {
    /// A result with no optional fields populated.
    fn new(action: &'static str, target: &str, outcome: &'static str) -> Self {
        Self {
            action,
            target: target.to_string(),
            outcome,
            count: None,
            installed: Vec::new(),
            removed: Vec::new(),
            skipped: Vec::new(),
            pending_items: None,
            key: None,
        }
    }
}

/// True when the current output context wants machine JSON. A mutating verb gates
/// its prose on `!json_mode()` and emits a [`MutationResult`] when it is true.
fn json_mode() -> bool {
    crate::render::ctx().json
}

use crate::render::print_json;

/// A throwaway registry holding just one source, for catalog scans during meld.
fn single(source: &crate::source::Source) -> Registry {
    Registry {
        sources: vec![source.clone()],
    }
}

/// First 8 chars of a hash/commit, for compact display.
fn short(s: &str) -> String {
    if s.is_empty() {
        "-".to_string()
    } else {
        s.chars().take(8).collect()
    }
}

/// One-line summary for list views: first sentence or `max` chars, whichever is
/// shorter. The full text stays available via `recall <item>`.
fn summary(desc: Option<&str>, max: usize) -> String {
    let Some(d) = desc else { return String::new() };
    let first = d.split(". ").next().unwrap_or(d).trim_end_matches('.');
    if first.chars().count() <= max {
        return first.to_string();
    }
    let cut: String = first.chars().take(max.saturating_sub(1)).collect();
    format!("{}...", cut.trim_end())
}

/// Print `prompt` and read one line from stdin (trimmed by the caller). EOF
/// yields an empty string. Used for free-form answers like the prefix prompt
/// (CLI-24), where `[y/N]` is not enough.
fn prompt_line(prompt: &str) -> Result<String> {
    print!("{prompt}");
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    if std::io::stdin()
        .read_line(&mut line)
        .map_err(|e| MindError::io("<stdin>", e))?
        == 0
    {
        return Ok(String::new()); // EOF -> empty (accept the declared prefix)
    }
    Ok(line)
}

/// Resolve a yes/no reply. An explicit `y`/`yes` or `n`/`no` (any case, trimmed)
/// wins; an empty line or any unrecognized reply takes `default_yes`.
fn parse_confirm(input: &str, default_yes: bool) -> bool {
    match input.trim().to_ascii_lowercase().as_str() {
        "y" | "yes" => true,
        "n" | "no" => false,
        _ => default_yes,
    }
}

/// Print `prompt {hint}`, read one line from stdin, and resolve it against
/// `default_yes`. EOF (no input) is always No.
fn read_confirm(prompt: &str, hint: &str, default_yes: bool) -> Result<bool> {
    print!("\n{prompt} {hint} ");
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    let stdin = std::io::stdin();
    if stdin
        .read_line(&mut line)
        .map_err(|e| MindError::io("<stdin>", e))?
        == 0
    {
        return Ok(false); // EOF (no input) -> treat as No
    }
    Ok(parse_confirm(&line, default_yes))
}

/// Prompt `[y/N]` on the terminal; default No.
pub(crate) fn confirm(prompt: &str) -> Result<bool> {
    read_confirm(prompt, "[y/N]", false)
}

/// Like `confirm` but defaulting to yes (`[Y/n]`): a bare Enter (or any reply that
/// is not an explicit no) confirms. Used where the affirmative is the expected
/// path and the action is reversible (the meld install-items prompt, CLI-23).
pub(crate) fn confirm_default_yes(prompt: &str) -> Result<bool> {
    read_confirm(prompt, "[Y/n]", true)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ItemKind;
    use crate::manifest::InstalledItem;
    use std::path::PathBuf;
    use std::sync::Mutex;
    use std::sync::atomic::{AtomicU32, Ordering};

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

    // ----- DSC-69: auth-failure message rendering -----

    #[test]
    fn auth_failure_skip_lines_no_message() {
        // spec: DSC-69 -- skip action produces standard line + " (skipping)"
        use crate::mindfile::OnAuthFailure;
        let cfg = OnAuthFailure {
            action: AuthFailureAction::Skip,
            message: None,
        };
        let lines = auth_failure_lines("owner/private-repo", &cfg);
        assert_eq!(lines.len(), 1);
        assert!(
            lines[0].contains("unable to meld source owner/private-repo"),
            "line: {}",
            lines[0]
        );
        assert!(
            lines[0].contains("(skipping)"),
            "must include (skipping) for skip action: {}",
            lines[0]
        );
    }

    #[test]
    fn auth_failure_skip_lines_with_message() {
        // spec: DSC-69 -- message is printed on the line immediately following
        use crate::mindfile::OnAuthFailure;
        let cfg = OnAuthFailure {
            action: AuthFailureAction::Skip,
            message: Some("Configure credentials: https://example.com/auth".into()),
        };
        let lines = auth_failure_lines("owner/private-repo", &cfg);
        assert_eq!(lines.len(), 2);
        assert!(lines[0].contains("(skipping)"), "first line: {}", lines[0]);
        assert_eq!(lines[1], "Configure credentials: https://example.com/auth");
    }

    #[test]
    fn auth_failure_error_lines_no_skipping_suffix() {
        // spec: DSC-69 -- error action does NOT have " (skipping)" in the message
        use crate::mindfile::OnAuthFailure;
        let cfg = OnAuthFailure {
            action: AuthFailureAction::Error,
            message: None,
        };
        let lines = auth_failure_lines("owner/private-repo", &cfg);
        assert_eq!(lines.len(), 1);
        assert!(
            lines[0].contains("unable to meld source"),
            "line: {}",
            lines[0]
        );
        assert!(
            !lines[0].contains("(skipping)"),
            "error action must NOT include (skipping): {}",
            lines[0]
        );
    }

    #[test]
    fn auth_failure_error_lines_with_message_included() {
        // spec: DSC-69 -- message is printed before the process exits non-zero
        use crate::mindfile::OnAuthFailure;
        let cfg = OnAuthFailure {
            action: AuthFailureAction::Error,
            message: Some("Contact admin for access.".into()),
        };
        let lines = auth_failure_lines("owner/private-repo", &cfg);
        assert_eq!(lines.len(), 2);
        assert!(
            !lines[0].contains("(skipping)"),
            "error action must NOT include (skipping)"
        );
        assert_eq!(lines[1], "Contact admin for access.");
    }

    #[test]
    fn auth_failure_lines_strips_ansi_escape() {
        // spec: DSC-69 -- ANSI escape bytes in message are stripped before output
        use crate::mindfile::OnAuthFailure;
        let cfg = OnAuthFailure {
            action: AuthFailureAction::Skip,
            message: Some("\x1b[2J hello\x1b[0m".into()),
        };
        let lines = auth_failure_lines("src", &cfg);
        assert_eq!(lines.len(), 2);
        // ANSI bytes are stripped; only printable characters remain.
        assert_eq!(
            lines[1], " hello",
            "expected printable portion only: {:?}",
            lines[1]
        );
        assert!(
            !lines[1].contains('\x1b'),
            "ANSI escape must be stripped: {:?}",
            lines[1]
        );
    }

    #[test]
    fn strip_ansi_drops_bidi_and_separator_chars() {
        // spec: DSC-69 -- bidi-override code points and line/paragraph separators
        // are dropped so a curator-controlled message cannot spoof terminal output.

        // U+202E (RIGHT-TO-LEFT OVERRIDE) is the canonical bidi-spoof char.
        assert_eq!(
            strip_ansi("pay \u{202E}oot"),
            "pay oot",
            "RLO must be dropped"
        );
        // Full blocked range U+202A-U+202E.
        assert_eq!(
            strip_ansi("\u{202A}\u{202B}\u{202C}\u{202D}\u{202E}"),
            "",
            "bidi U+202A-202E must all be dropped"
        );
        // Full blocked range U+2066-U+2069.
        assert_eq!(
            strip_ansi("\u{2066}\u{2067}\u{2068}\u{2069}"),
            "",
            "isolate U+2066-2069 must all be dropped"
        );
        // U+2028 (LINE SEPARATOR) and U+2029 (PARAGRAPH SEPARATOR).
        assert_eq!(
            strip_ansi("line\u{2028}break"),
            "linebreak",
            "U+2028 must be dropped"
        );
        assert_eq!(
            strip_ansi("para\u{2029}sep"),
            "parasep",
            "U+2029 must be dropped"
        );
        // Plain ASCII and non-blocked Unicode are still passed through.
        assert_eq!(strip_ansi("hello\u{00e9}"), "hello\u{00e9}");
    }

    #[test]
    fn strip_ansi_preserves_chars_adjacent_to_blocked_ranges() {
        // spec: DSC-69 -- the blocked sets are the exact ranges U+202A-U+202E,
        // U+2066-U+2069, and the two separators U+2028/U+2029. Codepoints
        // immediately adjacent to those ranges are legitimate text and must pass
        // through; a widened range would be a regression that silently eats
        // normal content.

        // U+2027 (HYPHENATION POINT) sits just below the 2028/2029 separators.
        assert_eq!(
            strip_ansi("a\u{2027}b"),
            "a\u{2027}b",
            "U+2027 must pass through (below the separator block)"
        );
        // U+202F (NARROW NO-BREAK SPACE) sits just above the U+202A-202E block.
        assert_eq!(
            strip_ansi("a\u{202F}b"),
            "a\u{202F}b",
            "U+202F must pass through (above the bidi-override block)"
        );
        // U+2065 sits just below the U+2066-2069 isolate block.
        assert_eq!(
            strip_ansi("a\u{2065}b"),
            "a\u{2065}b",
            "U+2065 must pass through (below the isolate block)"
        );
        // U+206A sits just above the U+2066-2069 isolate block.
        assert_eq!(
            strip_ansi("a\u{206A}b"),
            "a\u{206A}b",
            "U+206A must pass through (above the isolate block)"
        );
    }

    #[test]
    fn strip_ansi_separator_at_every_position() {
        // spec: DSC-69 -- a separator must be dropped regardless of where it
        // appears: leading, interior, or trailing.
        assert_eq!(strip_ansi("\u{2028}tail"), "tail", "leading U+2028");
        assert_eq!(strip_ansi("mid\u{2028}dle"), "middle", "interior U+2028");
        assert_eq!(strip_ansi("head\u{2028}"), "head", "trailing U+2028");
        // A run consisting solely of separators collapses to empty.
        assert_eq!(
            strip_ansi("\u{2028}\u{2029}\u{2028}"),
            "",
            "only-separator run must be empty"
        );
    }

    #[test]
    fn strip_ansi_alternating_blocked_and_allowed() {
        // spec: DSC-69 -- interleaving blocked codepoints with allowed text must
        // drop only the blocked ones and keep the rest in order.
        assert_eq!(
            strip_ansi("a\u{202E}b\u{2066}c\u{2028}d\u{2069}e"),
            "abcde",
            "blocked chars removed, allowed text preserved in order"
        );
    }

    // CLI-153: the mutating-verb JSON result has the stable
    // action/target/outcome shape; optional fields appear only when populated.
    #[test]
    fn mutation_result_minimal_shape() {
        let r = MutationResult::new("forget", "skill:review", "removed");
        let v: serde_json::Value = serde_json::to_value(&r).unwrap();
        assert_eq!(v["action"], "forget");
        assert_eq!(v["target"], "skill:review");
        assert_eq!(v["outcome"], "removed");
        // Unpopulated optional fields are omitted entirely.
        assert!(v.get("count").is_none(), "count must be omitted: {v}");
        assert!(v.get("installed").is_none(), "installed omitted: {v}");
        assert!(v.get("removed").is_none(), "removed omitted: {v}");
    }

    #[test]
    fn mutation_result_populated_optional_fields() {
        let mut r = MutationResult::new("learn", "skill:review", "installed");
        r.installed = vec!["agent:reviewer".to_string(), "skill:review".to_string()];
        r.count = Some(2);
        let v: serde_json::Value = serde_json::to_value(&r).unwrap();
        assert_eq!(v["action"], "learn");
        assert_eq!(v["outcome"], "installed");
        assert_eq!(v["count"], 2);
        assert_eq!(
            v["installed"],
            serde_json::json!(["agent:reviewer", "skill:review"])
        );
        // `removed` is still empty, so it is omitted.
        assert!(v.get("removed").is_none(), "empty removed omitted: {v}");
    }

    #[test]
    fn parse_confirm_default_no_only_yes_confirms() {
        // spec: CLI-42 - the default-no guard (e.g. the forget glob confirm):
        // only an explicit yes confirms; empty and unrecognized are no.
        assert!(parse_confirm("y", false));
        assert!(parse_confirm("YES", false));
        assert!(!parse_confirm("", false));
        assert!(!parse_confirm("n", false));
        assert!(!parse_confirm("maybe", false));
    }

    #[test]
    fn parse_confirm_default_yes_only_no_declines() {
        // spec: CLI-23 - the meld install prompt defaults to yes: a bare Enter (or
        // anything but an explicit no) installs; only n/no declines.
        assert!(parse_confirm("", true));
        assert!(parse_confirm("y", true));
        assert!(parse_confirm(" Y \n", true));
        assert!(parse_confirm("whatever", true));
        assert!(!parse_confirm("n", true));
        assert!(!parse_confirm("NO", true));
    }

    /// Serialize every test that mutates process-global env vars
    /// (`MIND_POLICY_FILE`, `MIND_AGENT_HOMES`). Env is process-wide, so these
    /// tests cannot run concurrently.
    static ENV_LOCK: Mutex<()> = Mutex::new(());

    /// Write `policy_toml` to a temp file and point `$MIND_POLICY_FILE` at it,
    /// also clearing `$MIND_AGENT_HOMES` so the outer env never bleeds in.
    /// Returns the held env guard (drop last) and the base temp dir.
    fn with_policy(policy_toml: &str) -> (std::sync::MutexGuard<'static, ()>, PathBuf) {
        let guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-cmd-test-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&base).unwrap();
        let policy_file = base.join("policy.toml");
        std::fs::write(&policy_file, policy_toml).unwrap();
        // SAFETY: ENV_LOCK is held, so no other test reads env concurrently.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
            std::env::set_var("MIND_POLICY_FILE", policy_file.to_str().unwrap());
        }
        (guard, base)
    }

    fn item(name: &str, source: &str) -> InstalledItem {
        InstalledItem {
            kind: ItemKind::Skill,
            name: name.to_string(),
            bare_name: name.to_string(),
            source: source.to_string(),
            commit: "deadbeef".to_string(),
            hash: "h".to_string(),
            store: format!("store/skills/{name}"),
            links: vec![],
            description: None,
        }
    }

    // ---- F2: POL-40 override-note suppression --------------------------------

    // spec: POL-40
    // The override note is shown only when the env var is set AND actually takes
    // effect. Under a lobe lock the env var is ignored, so suppress it.
    #[test]
    fn pol40_override_note_predicate() {
        // Unlocked: env var set -> show the note (behavior unchanged).
        assert!(show_override_note(true, false));
        // Locked: env var ignored by agent_homes -> suppress the note.
        assert!(!show_override_note(true, true));
        // Env var unset -> never show, locked or not.
        assert!(!show_override_note(false, false));
        assert!(!show_override_note(false, true));
    }

    // spec: POL-40
    // End-to-end against a real `$MIND_POLICY_FILE`: with `[lobes].lock = true`
    // the loaded policy reports lobes_lock(), so the override note must be
    // suppressed even though `$MIND_AGENT_HOMES` is set. Drives the same
    // `Policy::load()?` + `lobes_lock()` path `lobe_list` uses.
    #[test]
    fn pol40_locked_policy_suppresses_override_note() {
        let managed = std::env::temp_dir().join("mind-pol40-managed-target");
        let policy_toml = format!(
            "[lobes]\nlock = true\ntargets = [\"{}\"]\n",
            managed.display()
        );
        let (_guard, base) = with_policy(&policy_toml);
        // Simulate the user setting the override var (ignored under lock).
        // SAFETY: ENV_LOCK held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", base.join("env-lobe").to_str().unwrap());
        }

        let policy = Policy::load().unwrap().expect("policy should load");
        let env_set = std::env::var_os("MIND_AGENT_HOMES").is_some();
        let lobes_locked = policy.lobes_lock();

        // SAFETY: ENV_LOCK held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }

        assert!(env_set, "test must have the override var set");
        assert!(lobes_locked, "policy must report a lobe lock");
        assert!(
            !show_override_note(env_set, lobes_locked),
            "POL-40: a locked policy must suppress the false override note"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    // spec: POL-40
    // With a policy present but lobes unlocked (lock = false), the override note
    // is still shown when the env var is set: the env var really does take
    // effect, so the fix must not change the unlocked path.
    #[test]
    fn pol40_unlocked_keeps_override_note() {
        let policy_toml = "[lobes]\nlock = false\n";
        let (_guard, base) = with_policy(policy_toml);
        // SAFETY: ENV_LOCK held.
        unsafe {
            std::env::set_var("MIND_AGENT_HOMES", base.join("env-lobe").to_str().unwrap());
        }

        let lobes_locked = matches!(Policy::load().unwrap(), Some(p) if p.lobes_lock());
        let env_set = std::env::var_os("MIND_AGENT_HOMES").is_some();

        // SAFETY: ENV_LOCK held.
        unsafe {
            std::env::remove_var("MIND_AGENT_HOMES");
        }

        assert!(!lobes_locked, "lock = false means no lobe lock");
        assert!(
            show_override_note(env_set, lobes_locked),
            "unlocked behavior must be unchanged: the note still shows"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    // ---- F3: POL-12 scoped-upgrade skip ordering -----------------------------

    // spec: POL-12
    // A scoped `upgrade <item>` must apply the item-ref filter before the policy
    // skip, so an out-of-scope item from a disallowed source produces no skip
    // line. The pre-fix ordering (policy skip first) would classify it as
    // PolicyBlocked and print a skip line for a source the user never selected.
    #[test]
    fn pol12_scoped_upgrade_no_skip_for_out_of_scope_source() {
        // Locked allowlist that permits only `allowed-src`.
        let policy_toml = concat!(
            "[sources]\n",
            "lock = true\n",
            "allow = [\"github.com/me/allowed-src\"]\n",
        );
        let (_guard, base) = with_policy(policy_toml);
        let policy = Policy::load().unwrap().expect("policy should load");
        assert!(policy.lock());

        // The user scopes to an item from the allowed source.
        let selected = item("wanted", "github.com/me/allowed-src");
        // An installed item from a *disallowed* source the user did NOT select.
        let other = item("unwanted", "github.com/them/blocked-src");

        let filter = parse_item_ref("wanted").unwrap();

        // Out-of-scope item: silently skipped, never reported as PolicyBlocked.
        assert_eq!(
            upgrade_item_disposition(&other, Some(&filter), Some(&policy)),
            UpgradeDisposition::OutOfScope,
            "POL-12: an unselected item must not be policy-skipped (no skip line)"
        );
        // The selected, allowed item is considered for upgrade.
        assert_eq!(
            upgrade_item_disposition(&selected, Some(&filter), Some(&policy)),
            UpgradeDisposition::Consider,
        );

        // Sanity: with no scope filter, the disallowed item IS policy-blocked
        // (the existing unscoped behavior is preserved).
        assert_eq!(
            upgrade_item_disposition(&other, None, Some(&policy)),
            UpgradeDisposition::PolicyBlocked,
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    // spec: POL-12
    // When the scoped item itself comes from a disallowed source, it passes the
    // filter and is then correctly reported as PolicyBlocked (the skip is for an
    // item the user actually selected, which is the intended behavior).
    #[test]
    fn pol12_scoped_upgrade_skips_selected_disallowed_item() {
        let policy_toml = concat!(
            "[sources]\n",
            "lock = true\n",
            "allow = [\"github.com/me/allowed-src\"]\n",
        );
        let (_guard, base) = with_policy(policy_toml);
        let policy = Policy::load().unwrap().expect("policy should load");

        let selected = item("blocked-item", "github.com/them/blocked-src");
        let filter = parse_item_ref("blocked-item").unwrap();

        assert_eq!(
            upgrade_item_disposition(&selected, Some(&filter), Some(&policy)),
            UpgradeDisposition::PolicyBlocked,
            "a selected item from a disallowed source is still reported"
        );

        let _ = std::fs::remove_dir_all(&base);
    }

    /// Build a bare `Source` for the `hook_rerun_warranted` truth table. Uses
    /// `parse_spec` so the identity fields are filled the same way `meld` fills
    /// them; the test only manipulates the commit and install_hooks fields.
    ///
    /// `hooks` is a list of `(command, ran_at)` pairs to populate
    /// `Source.install_hooks`.
    fn hook_source(commit: Option<&str>, hooks: &[(&str, Option<&str>)]) -> crate::source::Source {
        use crate::source::RecordedHook;
        let mut s = crate::source::parse_spec("acme/tools").expect("spec parses");
        s.commit = commit.map(str::to_string);
        s.install_hooks = hooks
            .iter()
            .map(|(cmd, ran_at)| RecordedHook {
                command: cmd.to_string(),
                ran_at: ran_at.map(str::to_string),
            })
            .collect();
        s
    }

    // spec: HOOK-11 HOOK-55
    #[test]
    fn hook_rerun_warranted_truth_table() {
        // No hooks recorded: never re-run.
        assert!(
            !hook_rerun_warranted(&hook_source(Some("abc1234"), &[])),
            "no install_hooks means no re-run"
        );

        // Hook already ran at the current commit: nothing to do.
        assert!(
            !hook_rerun_warranted(&hook_source(
                Some("abc1234"),
                &[("make install", Some("abc1234"))],
            )),
            "ran_at == commit means the hook already ran here"
        );

        // All hooks ran at current commit: nothing to do.
        assert!(
            !hook_rerun_warranted(&hook_source(
                Some("abc1234"),
                &[
                    ("make build", Some("abc1234")),
                    ("make install", Some("abc1234")),
                ],
            )),
            "all hooks ran at current commit means no re-run warranted"
        );

        // Hook recorded but never run (skipped meld): re-offer it.
        assert!(
            hook_rerun_warranted(&hook_source(Some("abc1234"), &[("make install", None)],)),
            "a recorded-but-never-run hook is re-offered"
        );

        // Commit advanced past the commit the hook last ran at: re-offer it.
        assert!(
            hook_rerun_warranted(&hook_source(
                Some("def5678"),
                &[("make install", Some("abc1234"))],
            )),
            "an advanced commit warrants a re-run"
        );

        // Mixed: one hook ran at current commit, one at a stale commit.
        assert!(
            hook_rerun_warranted(&hook_source(
                Some("new0000"),
                &[
                    ("make build", Some("new0000")),
                    ("make install", Some("old0000")),
                ],
            )),
            "at least one stale hook warrants a re-run"
        );
    }

    // spec: HOOK-57
    // The init-source scaffold must include commented [[hooks]] examples for both
    // install and uninstall events, at least one marked optional = true.
    #[test]
    fn init_source_scaffold_includes_hooks_examples() {
        // Create a temp directory to run init_source in.
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let tmp =
            std::env::temp_dir().join(format!("mind-cmd-init-hooks-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&tmp).unwrap();
        struct Rm(std::path::PathBuf);
        impl Drop for Rm {
            fn drop(&mut self) {
                let _ = std::fs::remove_dir_all(&self.0);
            }
        }
        let _rm = Rm(tmp.clone());

        // init_source should create the scaffold.
        init_source(Some(tmp.to_str().unwrap()), false, false, false, None)
            .expect("init_source should succeed");

        let toml_path = tmp.join("mind.toml");
        assert!(toml_path.exists(), "mind.toml must be created");
        let contents = std::fs::read_to_string(&toml_path).unwrap();

        // HOOK-57: must include [[hooks]] commented examples.
        assert!(
            contents.contains("[[hooks]]"),
            "scaffold must include a commented [[hooks]] example: {contents}"
        );
        // Must show an install event.
        assert!(
            contents.contains("install"),
            "scaffold must show event = \"install\": {contents}"
        );
        // Must show an uninstall event.
        assert!(
            contents.contains("uninstall"),
            "scaffold must show event = \"uninstall\": {contents}"
        );
        // At least one example marked optional = true.
        assert!(
            contents.contains("optional = true"),
            "scaffold must have at least one optional = true example: {contents}"
        );
        // All [[hooks]] content is commented out (lines starting with # after trimming).
        // Check that the literal text "[[hooks]]" is preceded by a #.
        let has_uncommented_hooks = contents.lines().any(|l| l.trim() == "[[hooks]]");
        assert!(
            !has_uncommented_hooks,
            "[[hooks]] examples must all be commented out: {contents}"
        );

        // Existing assertions still pass (regression guard).
        assert!(
            contents.contains("[source]"),
            "scaffold must still have [source]"
        );
        assert!(
            contents.contains("# prefix = \"prefix\""),
            "scaffold must still have commented prefix: {contents}"
        );
    }

    // spec: HOOK-58
    // The recall --sources hook token is count-aware: no token for 0 hooks,
    // ` hook` for 1, ` hooks(N)` for N > 1.
    #[test]
    fn hook_token_is_count_aware() {
        // 0 hooks -> empty string.
        let s0 = hook_source(Some("abc"), &[]);
        let token0 = match s0.install_hooks.len() {
            0 => String::new(),
            1 => " hook".to_string(),
            n => format!(" hooks({n})"),
        };
        assert_eq!(token0, "", "no hooks => empty token");

        // 1 hook -> ` hook`.
        let s1 = hook_source(Some("abc"), &[("make install", Some("abc"))]);
        let token1 = match s1.install_hooks.len() {
            0 => String::new(),
            1 => " hook".to_string(),
            n => format!(" hooks({n})"),
        };
        assert_eq!(token1, " hook", "1 hook => ' hook'");

        // 2 hooks -> ` hooks(2)`.
        let s2 = hook_source(
            Some("abc"),
            &[("make build", Some("abc")), ("make install", Some("abc"))],
        );
        let token2 = match s2.install_hooks.len() {
            0 => String::new(),
            1 => " hook".to_string(),
            n => format!(" hooks({n})"),
        };
        assert_eq!(token2, " hooks(2)", "2 hooks => ' hooks(2)'");
    }

    // spec: HOOK-50 HOOK-55
    // Verifies that `hook_rerun_warranted` uses the new multi-hook model: a source
    // with multiple install hooks is re-offered when ANY hook is pending, and not
    // re-offered when ALL hooks have ran_at == commit.
    #[test]
    fn hook_rerun_warranted_multi_hook_model() {
        // All hooks ran at the current commit: not warranted.
        let all_current = hook_source(
            Some("fff000"),
            &[
                ("make build", Some("fff000")),
                ("make install", Some("fff000")),
                ("make test", Some("fff000")),
            ],
        );
        assert!(
            !hook_rerun_warranted(&all_current),
            "all hooks current => no re-run warranted"
        );

        // One hook never ran (ran_at == None): warranted.
        let one_never_ran = hook_source(
            Some("fff000"),
            &[
                ("make build", Some("fff000")),
                ("make install", None), // skipped at meld time
            ],
        );
        assert!(
            hook_rerun_warranted(&one_never_ran),
            "one hook with ran_at=None => re-run warranted"
        );

        // Source has no commit yet (None): all pending (ran_at=None matches None but
        // hooks with a ran_at=Some differ from None).
        let no_commit = hook_source(None, &[("make install", Some("old"))]);
        assert!(
            hook_rerun_warranted(&no_commit),
            "commit=None and ran_at=Some => they differ => warranted"
        );
    }

    // ---- absorb helper unit tests ----

    /// convention_path_in_root derives the correct convention path for each kind.
    // spec: ABS-1
    #[test]
    fn convention_path_in_root_derives_correct_paths() {
        let root = std::path::Path::new("/repo");
        assert_eq!(
            convention_path_in_root(root, ItemKind::Skill, "review"),
            PathBuf::from("/repo/skills/review"),
            "skill convention path is skills/<name>/"
        );
        assert_eq!(
            convention_path_in_root(root, ItemKind::Agent, "dev"),
            PathBuf::from("/repo/agents/dev.md"),
            "agent convention path is agents/<name>.md"
        );
        assert_eq!(
            convention_path_in_root(root, ItemKind::Rule, "style"),
            PathBuf::from("/repo/rules/style.md"),
            "rule convention path is rules/<name>.md"
        );
    }

    /// expand_tilde expands a leading `~` to the home directory.
    // spec: ABS-2 ABS-3
    #[test]
    fn expand_tilde_handles_home_prefix() {
        let home = dirs::home_dir().expect("home dir");
        // Bare `~` expands to home.
        let expanded = expand_tilde("~");
        assert_eq!(expanded, home, "bare ~ must expand to home directory");
        // `~/foo` expands to home/foo.
        let expanded2 = expand_tilde("~/foo");
        assert_eq!(
            expanded2,
            home.join("foo"),
            "~/foo must expand to <home>/foo"
        );
        // An absolute path passes through unchanged.
        let abs = expand_tilde("/tmp/mydir");
        assert_eq!(
            abs,
            PathBuf::from("/tmp/mydir"),
            "absolute path must be unchanged"
        );
        // A relative path (no tilde) passes through unchanged.
        let rel = expand_tilde("relpath/dir");
        assert_eq!(
            rel,
            PathBuf::from("relpath/dir"),
            "relative path must be unchanged"
        );
    }

    /// first_scan_root returns the destination directory when no mind.toml is present.
    // spec: ABS-1
    #[test]
    fn first_scan_root_defaults_to_dest_dir() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-abs-scanroot-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // No mind.toml: first_scan_root should return the directory itself.
        let root = first_scan_root(&dir).unwrap();
        assert_eq!(
            root,
            dir.join("."),
            "first_scan_root with no mind.toml must be dest/."
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// first_scan_root uses the first entry in [source].roots when mind.toml declares it.
    // spec: ABS-1
    #[test]
    fn first_scan_root_uses_minds_toml_roots() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-abs-scanroot2-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // Write a mind.toml with roots = ["packages/agents"]
        std::fs::write(
            dir.join("mind.toml"),
            "[source]\nroots = [\"packages/agents\"]\n",
        )
        .unwrap();
        // The subdirectory must exist for canonicalize-based containment check.
        std::fs::create_dir_all(dir.join("packages/agents")).unwrap();
        let root = first_scan_root(&dir).unwrap();
        assert_eq!(
            root,
            dir.join("packages/agents"),
            "first_scan_root must use first entry of [source].roots"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// first_scan_root rejects a roots entry that escapes the repo via `..`.
    // spec: ABS-10
    #[test]
    fn first_scan_root_rejects_escaping_root() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir = std::env::temp_dir().join(format!(
            "mind-abs-scanroot-escape-{}-{n}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        // Write a mind.toml whose roots entry uses `..` to escape the repo.
        std::fs::write(
            dir.join("mind.toml"),
            "[source]\nroots = [\"../../outside\"]\n",
        )
        .unwrap();
        // The escaped path does exist on the filesystem (the parent dirs do),
        // so canonicalize will work and detect the escape.
        let err = first_scan_root(&dir).unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::InvalidRoot { .. }),
            "an escaping roots entry must be InvalidRoot: {err}"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// normalize_path folds `..` and `.` components logically without touching
    /// the filesystem, so it can detect escapes for not-yet-created roots.
    // spec: ABS-10
    #[test]
    fn normalize_path_folds_parent_and_current_components() {
        use std::path::PathBuf;
        // `.` is dropped.
        assert_eq!(
            normalize_path(&PathBuf::from("/repo/./skills")),
            PathBuf::from("/repo/skills"),
            "a `.` component must be dropped"
        );
        // `..` pops the previous component.
        assert_eq!(
            normalize_path(&PathBuf::from("/repo/sub/../skills")),
            PathBuf::from("/repo/skills"),
            "a `..` must pop the previous component"
        );
        // `..` that climbs above the root yields a path that no longer starts
        // with the repo root (so the containment check rejects it).
        let escaped = normalize_path(&PathBuf::from("/repo/../../outside"));
        assert!(
            !escaped.starts_with("/repo"),
            "a climbing `..` chain must escape the repo root: {escaped:?}"
        );
        assert_eq!(
            escaped,
            PathBuf::from("/outside"),
            "folding /repo/../../outside yields /outside"
        );
    }

    /// first_scan_root takes the canonicalize branch (root exists on disk) and
    /// still rejects an escaping root. Distinct from the normalize_path fallback,
    /// this forces the candidate to exist so std::fs::canonicalize succeeds.
    // spec: ABS-10
    #[test]
    fn first_scan_root_rejects_existing_escaping_root_via_canonicalize() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!(
            "mind-abs-scanroot-canon-{}-{n}",
            std::process::id()
        ));
        let dest = base.join("repo");
        let outside = base.join("outside");
        std::fs::create_dir_all(&dest).unwrap();
        // The escape target exists, so canonicalize resolves it to a real path.
        std::fs::create_dir_all(&outside).unwrap();
        std::fs::write(
            dest.join("mind.toml"),
            "[source]\nroots = [\"../outside\"]\n",
        )
        .unwrap();
        let err = first_scan_root(&dest).unwrap_err();
        assert!(
            matches!(err, crate::error::MindError::InvalidRoot { .. }),
            "an existing escaping root (canonicalize branch) must be InvalidRoot: {err}"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    /// dest_source_prefix with no melded source and no mind.toml yields None
    /// (unprefixed install).
    // spec: ABS-8
    #[test]
    fn dest_source_prefix_none_when_unset() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-abs-pfx-none-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let registry = crate::source::Registry::default();
        assert_eq!(
            dest_source_prefix(&dir, &registry),
            None,
            "no alias and no mind.toml prefix means no effective prefix"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// dest_source_prefix reads `[source].prefix` from the destination mind.toml
    /// when the source is not yet melded (no alias to consult).
    // spec: ABS-8
    #[test]
    fn dest_source_prefix_reads_mindfile_prefix() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-abs-pfx-toml-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("mind.toml"), "[source]\nprefix = \"tomlpfx\"\n").unwrap();
        let registry = crate::source::Registry::default();
        assert_eq!(
            dest_source_prefix(&dir, &registry),
            Some("tomlpfx".to_string()),
            "an unmelded destination uses its mind.toml [source].prefix"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// When the destination is already melded with a recorded alias (`meld --as`),
    /// the alias wins over the repo's own `[source].prefix` (namespacing.md).
    // spec: ABS-8
    #[test]
    fn dest_source_prefix_alias_beats_mindfile_prefix() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-abs-pfx-alias-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        // The repo declares prefix = "tomlpfx" ...
        std::fs::write(dir.join("mind.toml"), "[source]\nprefix = \"tomlpfx\"\n").unwrap();
        // ... but the melded source records alias = "aliaspfx" (the consumer's --as).
        let mut src = crate::source::parse_spec(&dir.to_string_lossy()).unwrap();
        src.alias = Some("aliaspfx".to_string());
        let registry = crate::source::Registry { sources: vec![src] };
        assert_eq!(
            dest_source_prefix(&dir, &registry),
            Some("aliaspfx".to_string()),
            "the recorded alias must win over the repo's [source].prefix"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    /// An empty alias on a melded source is ignored and the mind.toml prefix is
    /// used (an empty alias is not a meaningful namespace).
    // spec: ABS-8
    #[test]
    fn dest_source_prefix_empty_alias_falls_through_to_mindfile() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir =
            std::env::temp_dir().join(format!("mind-abs-pfx-empty-{}-{n}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("mind.toml"), "[source]\nprefix = \"tomlpfx\"\n").unwrap();
        let mut src = crate::source::parse_spec(&dir.to_string_lossy()).unwrap();
        src.alias = Some(String::new()); // empty alias
        let registry = crate::source::Registry { sources: vec![src] };
        assert_eq!(
            dest_source_prefix(&dir, &registry),
            Some("tomlpfx".to_string()),
            "an empty alias must not suppress the mind.toml prefix"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }

    // ----- NS-30/CLI-161: set_source_namespace mutability lock -----

    /// A throwaway `Paths` under the system temp dir, unique per call.
    fn ns_paths() -> (Paths, PathBuf) {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-ns-set-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let paths = Paths {
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
        };
        (paths, base)
    }

    /// Build a source named `github.com/acme/<repo>` with the given alias and
    /// persist a registry holding exactly it.
    fn seed_source(paths: &Paths, repo: &str, alias: Option<&str>) -> String {
        let mut src = crate::source::parse_spec(&format!("github:acme/{repo}")).unwrap();
        src.alias = alias.map(|s| s.to_string());
        let name = src.name.clone();
        let registry = crate::source::Registry { sources: vec![src] };
        registry.save(paths).expect("save registry");
        name
    }

    /// Record an installed item attributed to `source` in the manifest.
    fn seed_installed_item(paths: &Paths, source: &str, kind: ItemKind, name: &str) {
        let mut manifest = Manifest::load(paths).expect("load manifest");
        manifest.insert(InstalledItem {
            kind,
            name: name.to_string(),
            bare_name: name.to_string(),
            source: source.to_string(),
            commit: "deadbeef".to_string(),
            hash: "abc123".to_string(),
            store: format!("store/{name}"),
            links: vec![],
            description: None,
        });
        manifest.save(paths).expect("save manifest");
    }

    #[test]
    fn set_source_namespace_source_not_found_is_noop() {
        // spec: NS-30 CLI-161 - an unknown source name is a safe no-op (Ok), not
        // an error, and writes nothing.
        let (paths, base) = ns_paths();
        seed_source(&paths, "agents", None);
        let r = set_source_namespace(&paths, "github.com/nope/missing", Some("jk".into()));
        assert!(r.is_ok(), "unknown source must be a no-op Ok: {r:?}");
        // The real source's alias is untouched.
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(reg.sources[0].alias, None, "no alias should be written");
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn set_source_namespace_locked_when_items_installed_and_alias_differs() {
        // spec: NS-30 CLI-161 - changing the alias while items are installed is
        // refused with NamespaceLocked naming the installed item keys; nothing
        // is persisted.
        let (paths, base) = ns_paths();
        let name = seed_source(&paths, "agents", None);
        seed_installed_item(&paths, &name, ItemKind::Skill, "review");
        let r = set_source_namespace(&paths, &name, Some("jk".into()));
        match r {
            Err(MindError::NamespaceLocked { src_name, items }) => {
                assert_eq!(src_name, name);
                assert!(
                    items.contains(&"skill:review".to_string()),
                    "locked error must list the installed item key: {items:?}"
                );
            }
            other => panic!("expected NamespaceLocked, got {other:?}"),
        }
        // The alias must NOT have been persisted despite the requested change.
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(
            reg.sources[0].alias, None,
            "a locked change must not write the new alias"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn set_source_namespace_unchanged_alias_with_items_is_noop() {
        // spec: NS-30 CLI-161 - re-applying the SAME alias is allowed even with
        // items installed: the lock only guards an actual change.
        let (paths, base) = ns_paths();
        let name = seed_source(&paths, "agents", Some("jk"));
        seed_installed_item(&paths, &name, ItemKind::Skill, "jk:review");
        let r = set_source_namespace(&paths, &name, Some("jk".into()));
        assert!(
            r.is_ok(),
            "an unchanged alias must be a no-op even with items installed: {r:?}"
        );
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(reg.sources[0].alias.as_deref(), Some("jk"));
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn set_source_namespace_allowed_and_persisted_when_no_items() {
        // spec: NS-30 CLI-161 - with zero installed items the alias changes and
        // is persisted to sources.json.
        let (paths, base) = ns_paths();
        let name = seed_source(&paths, "agents", None);
        set_source_namespace(&paths, &name, Some("jk".into())).expect("set namespace");
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(
            reg.sources[0].alias.as_deref(),
            Some("jk"),
            "the new alias must be persisted"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn set_source_namespace_empty_string_clears_consumer_prefix() {
        // spec: NS-30 CLI-161 - setting an empty alias (the "no prefix" override)
        // persists Some("") which the catalog treats as no consumer prefix.
        let (paths, base) = ns_paths();
        let name = seed_source(&paths, "agents", Some("jk"));
        set_source_namespace(&paths, &name, Some(String::new())).expect("clear namespace");
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(
            reg.sources[0].alias.as_deref(),
            Some(""),
            "empty string override must persist as Some(\"\")"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn set_source_namespace_none_equals_empty_is_noop() {
        // spec: NS-30 CLI-161 - None and Some("") are the same "no prefix" state,
        // so requesting None when the current alias is None changes nothing.
        let (paths, base) = ns_paths();
        let name = seed_source(&paths, "agents", None);
        set_source_namespace(&paths, &name, None).expect("noop");
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(reg.sources[0].alias, None);
        let _ = std::fs::remove_dir_all(&base);
    }

    #[test]
    fn set_source_namespace_rejects_reserved_kind_word() {
        // spec: NS-25 NS-30 - validate_prefix rejects a reserved kind word before
        // any registry mutation, returning ReservedPrefix.
        let (paths, base) = ns_paths();
        let name = seed_source(&paths, "agents", None);
        let r = set_source_namespace(&paths, &name, Some("skill".into()));
        assert!(
            matches!(r, Err(MindError::ReservedPrefix { ref prefix }) if prefix == "skill"),
            "a reserved kind word must be rejected: {r:?}"
        );
        // The registry must be untouched.
        let reg = Registry::load(&paths).unwrap();
        assert_eq!(reg.sources[0].alias, None);
        let _ = std::fs::remove_dir_all(&base);
    }

    // ----- MKT-10: origin_label mapping -----

    #[test]
    fn origin_label_none_returns_empty() {
        assert_eq!(
            origin_label(None),
            "",
            "no origin -> empty string (no extra token)"
        );
    }

    #[test]
    fn origin_label_claude_plugin_returns_token() {
        let label = origin_label(Some(ManifestOrigin::ClaudePlugin));
        assert_eq!(
            label, " origin:claude-plugin",
            "ClaudePlugin must produce the 'origin:claude-plugin' token with leading space"
        );
    }

    #[test]
    fn origin_label_claude_marketplace_returns_token() {
        let label = origin_label(Some(ManifestOrigin::ClaudeMarketplace));
        assert_eq!(
            label, " origin:claude-marketplace",
            "ClaudeMarketplace must produce the 'origin:claude-marketplace' token with leading space"
        );
    }

    // ----- MKT-7: marketplace_entry_spec helper -----

    #[test]
    fn marketplace_entry_spec_external_passes_spec_through() {
        let entry = plugin_manifest::MarketplaceEntry {
            name: "my-plugin".to_string(),
            source: plugin_manifest::PluginSource::External {
                spec: "owner/my-plugin".to_string(),
            },
            version: None,
            description: None,
            skills: vec![],
        };
        let clone_dir = std::path::Path::new("/some/catalog/clone");
        let spec = marketplace_entry_spec(&entry, clone_dir);
        assert_eq!(
            spec, "owner/my-plugin",
            "External spec must pass through verbatim"
        );
    }

    #[test]
    fn marketplace_entry_spec_in_repo_joins_onto_clone_dir() {
        let entry = plugin_manifest::MarketplaceEntry {
            name: "embedded".to_string(),
            source: plugin_manifest::PluginSource::InRepo {
                path: "plugins/embedded".to_string(),
            },
            version: None,
            description: None,
            skills: vec![],
        };
        let clone_dir = std::path::Path::new("/home/user/.mind/sources/local/owner/catalog");
        let spec = marketplace_entry_spec(&entry, clone_dir);
        assert_eq!(
            spec, "/home/user/.mind/sources/local/owner/catalog/plugins/embedded",
            "InRepo spec must be clone_dir joined with the in-repo path"
        );
    }

    #[test]
    fn marketplace_entry_spec_in_repo_dotslash_prefix() {
        // A relative path like "./plugins/p1" (validated safe by load_marketplace_manifest)
        // is joined onto clone_dir and the result is a usable local path.
        let entry = plugin_manifest::MarketplaceEntry {
            name: "p1".to_string(),
            source: plugin_manifest::PluginSource::InRepo {
                path: "./plugins/p1".to_string(),
            },
            version: None,
            description: None,
            skills: vec![],
        };
        let clone_dir = std::path::Path::new("/repo");
        let spec = marketplace_entry_spec(&entry, clone_dir);
        // Path::join normalises "./" on the joined string; the key property is
        // that the spec resolves inside clone_dir.
        assert!(
            spec.starts_with("/repo"),
            "InRepo spec with ./ prefix must still be rooted inside clone_dir: {spec}"
        );
    }

    /// `offer_save_absorb_to(yes=true)` writes `absorb_to` into config.toml,
    /// creating the config when absent (the ABS-4 save path, reachable headlessly
    /// only via the --yes branch). This is the side of ABS-4 that does NOT need a
    /// TTY; the interactive [y/N] save prompt is TTY-gated (see certification).
    // spec: ABS-4
    #[test]
    fn offer_save_absorb_to_yes_writes_config() {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-abs-save-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let paths = Paths {
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
        };
        // No config exists yet.
        assert!(
            !paths.config_file().exists(),
            "sanity: config.toml must not pre-exist"
        );
        let dest = base.join("personal");
        offer_save_absorb_to(&paths, &dest, true).expect("offer_save_absorb_to");

        // Config now exists and records absorb_to = the chosen dest.
        let cfg = Config::load(&paths).expect("load config");
        assert_eq!(
            cfg.absorb_to.as_deref(),
            Some(dest.to_string_lossy().as_ref()),
            "the chosen destination must be saved as absorb_to"
        );
        let _ = std::fs::remove_dir_all(&base);
    }

    // ---- NS-44: collision prompt parsing (parse_collision_answer) ----

    #[test]
    fn collision_prompt_empty_accepts_suggested() {
        // spec: NS-44 — pressing Enter (empty answer) accepts the suggested prefix.
        match parse_collision_answer("", "myrepo") {
            CollisionAnswer::Prefix(p) => assert_eq!(p, "myrepo"),
            CollisionAnswer::Abort => panic!("empty must accept suggested, not abort"),
        }
        // Whitespace-only is also empty after trim.
        match parse_collision_answer("   ", "myrepo") {
            CollisionAnswer::Prefix(p) => assert_eq!(p, "myrepo"),
            CollisionAnswer::Abort => panic!("whitespace must accept suggested, not abort"),
        }
    }

    #[test]
    fn collision_prompt_dot_aborts() {
        // spec: NS-44 — typing "." aborts the meld (same as non-interactive path).
        assert!(
            matches!(
                parse_collision_answer(".", "myrepo"),
                CollisionAnswer::Abort
            ),
            "dot must abort"
        );
        // Dot with surrounding whitespace is still the abort sentinel.
        assert!(
            matches!(
                parse_collision_answer("  .  ", "myrepo"),
                CollisionAnswer::Abort
            ),
            "dot with whitespace must abort"
        );
    }

    #[test]
    fn collision_prompt_custom_prefix_is_preserved() {
        // spec: NS-44 — typing a custom prefix uses it verbatim (trimmed).
        match parse_collision_answer("mypfx", "suggested") {
            CollisionAnswer::Prefix(p) => assert_eq!(p, "mypfx"),
            CollisionAnswer::Abort => panic!("custom prefix must not abort"),
        }
        // Trimming applies.
        match parse_collision_answer("  mypfx  ", "suggested") {
            CollisionAnswer::Prefix(p) => assert_eq!(p, "mypfx"),
            CollisionAnswer::Abort => panic!("trimmed custom prefix must not abort"),
        }
    }

    #[test]
    fn format_conflicts_display_strips_ansi_from_name_and_source() {
        // spec: NS-44 — ANSI escape sequences in item name or source name are
        // stripped so a malicious source cannot inject terminal control codes into
        // the interactive collision prompt.
        let conflicts = vec![(
            "skill".to_string(),
            "\x1b[31mreview\x1b[0m".to_string(), // ANSI-colored name
            "\x1b[32mevil/source\x1b[0m".to_string(), // ANSI-colored source
        )];
        let out = format_conflicts_display(&conflicts);
        assert!(
            out.contains("skill:review"),
            "bare name must appear without ANSI: {out}"
        );
        assert!(
            out.contains("evil/source"),
            "bare source must appear without ANSI: {out}"
        );
        assert!(
            !out.contains('\x1b'),
            "no ANSI escape bytes must appear in the output: {out}"
        );
    }
}