mind-cli 0.30.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
//! Cross-harness lobes (spec/harness-lobes.md, HARN-1..6): end-to-end tests that
//! drive the real `mind` binary against a hermetic, network-free fixture. They
//! cover the per-lobe `kinds` filter, the `--preset` add, the `kinds`-aware
//! display, and the auto-detect-and-prompt setup (via `MIND_DETECT_HOME`).

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

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

/// A throwaway environment: a source git repo plus isolated MIND/CLAUDE homes.
struct Sandbox {
    base: PathBuf,
    source: PathBuf,
    mind_home: PathBuf,
    claude_home: PathBuf,
}

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

impl Sandbox {
    /// A source repo with one skill (`review`) and one rule (`style`), committed.
    fn new() -> Sandbox {
        let n = COUNTER.fetch_add(1, Ordering::SeqCst);
        let base = std::env::temp_dir().join(format!("mind-lobes-{}-{n}", std::process::id()));
        let _ = std::fs::remove_dir_all(&base);
        let source = base.join("agents");
        let sb = Sandbox {
            base: base.clone(),
            source: source.clone(),
            mind_home: base.join("mind"),
            claude_home: base.join("claude"),
        };
        write(
            &source.join("skills/review/SKILL.md"),
            "---\nname: review\ndescription: Review the diff for bugs\n---\n# review skill\n",
        );
        write(
            &source.join("rules/style.md"),
            "---\ndescription: ASCII only\n---\n# style rule\n",
        );
        git(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
        git(&source, &["config", "user.email", "t@t"]);
        git(&source, &["config", "user.name", "t"]);
        git(&source, &["add", "-A"]);
        git(&source, &["commit", "-qm", "initial"]);
        std::fs::create_dir_all(&sb.mind_home).unwrap();
        sb
    }

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

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

    /// Run `mind` with `HOME` pinned to the sandbox base, so a GLOBAL preset
    /// (gemini/codex/universal) resolves under the sandbox rather than the real
    /// machine home. HARN-15 creates the resolved lobe path on disk, so any test
    /// exercising a global preset add must sandbox `HOME` or it would mkdir under
    /// the real user's home directory.
    fn mind_home_sandboxed(&self, args: &[&str]) -> Run {
        let home_str = self.base.to_string_lossy().into_owned();
        self.mind_env(args, &[("HOME", &home_str)])
    }

    /// Run `mind` with cwd pinned to the sandbox base, so a PROJECT-scoped
    /// preset (windsurf) with no explicit base resolves under the sandbox rather
    /// than wherever the test binary happens to run from (e.g. the repo root).
    /// Same HARN-15 rationale as `mind_home_sandboxed`.
    fn mind_cwd_sandboxed(&self, args: &[&str]) -> Run {
        self.run_cwd(args, &[], Some(&self.base))
    }

    fn run(&self, args: &[&str], envs: &[(&str, &str)]) -> Run {
        self.run_cwd(args, envs, None)
    }

    fn run_cwd(&self, args: &[&str], envs: &[(&str, &str)], cwd: Option<&Path>) -> Run {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_mind"));
        cmd.args(args)
            .env("MIND_HOME", &self.mind_home)
            .env("CLAUDE_HOME", &self.claude_home)
            .env_remove("MIND_AGENT_HOMES")
            .env_remove("MIND_POLICY_FILE")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        for (k, v) in envs {
            cmd.env(k, v);
        }
        if let Some(dir) = cwd {
            cmd.current_dir(dir);
        }
        let out = cmd.output().expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    }

    fn source_spec(&self) -> String {
        self.source.to_string_lossy().into_owned()
    }

    /// Write `config.toml` verbatim into the mind home (so a test can pin the
    /// exact lobe set, including a `kinds`-filtered table entry).
    fn write_config(&self, body: &str) {
        write(&self.mind_home.join("config.toml"), body);
    }
}

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

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

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

fn parse_json(stdout: &str) -> serde_json::Value {
    serde_json::from_str(stdout.trim()).unwrap_or_else(|e| panic!("not JSON: {e}\n{stdout}"))
}

// HARN-4: `config lobes add --preset gemini` records the preset's parent path
// and `kinds` filter as a detailed lobe entry.
#[test]
fn preset_add_records_path_and_kinds() {
    // spec: HARN-4
    let sb = Sandbox::new();
    let added = sb.mind_home_sandboxed(&["config", "lobes", "add", "--preset", "gemini"]);
    assert!(added.success, "preset add failed: {}", added.stderr);

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let lobes = v["lobes"].as_array().expect("lobes array");
    let gemini = lobes
        .iter()
        .find(|l| {
            l["path"]
                .as_str()
                .is_some_and(|p| p.ends_with(".gemini/config"))
        })
        .expect("a .gemini/config lobe entry");
    let kinds: Vec<&str> = gemini["kinds"]
        .as_array()
        .expect("kinds array")
        .iter()
        .map(|k| k.as_str().unwrap())
        .collect();
    assert_eq!(kinds, vec!["skill"], "gemini is skill-only");

    // An unknown preset name is rejected.
    let bad = sb.mind(&["config", "lobes", "add", "--preset", "emacs"]);
    assert!(!bad.success, "unknown preset must fail");
    assert!(bad.stderr.contains("preset"), "{}", bad.stderr);

    // Removed presets are also unknown.
    let ag = sb.mind(&["config", "lobes", "add", "--preset", "antigravity"]);
    assert!(!ag.success, "removed antigravity preset must fail");
    let agcli = sb.mind(&["config", "lobes", "add", "--preset", "antigravity-cli"]);
    assert!(!agcli.success, "removed antigravity-cli preset must fail");

    // Supplying both a path and --preset is rejected by the CLI.
    let both = sb.mind(&["config", "lobes", "add", "/tmp/x", "--preset", "gemini"]);
    assert!(!both.success, "path + --preset must conflict");
}

// HARN-2 / HARN-3: a skill links into a `[skill]`-only lobe AND the all-kinds
// Claude lobe, while a rule links ONLY into the all-kinds lobe. The rule's
// manifest `links` omit the skill-only lobe, and no rule file lands there.
#[test]
fn kinds_filter_excludes_rule_from_skill_only_lobe() {
    // spec: HARN-2
    // spec: HARN-3
    // spec: HARN-6
    let sb = Sandbox::new();
    let skill_lobe = sb.base.join("gemini-lobe");
    sb.write_config(&format!(
        "lobes = [\"{claude}\", {{ path = \"{skill}\", kinds = [\"skill\"] }}]\n",
        claude = sb.claude_home.display(),
        skill = skill_lobe.display(),
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");
    assert!(sb.mind(&["learn", "style"]).success, "learn rule");

    // The skill is linked into BOTH lobes (skill is admitted everywhere).
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "skill must link into the Claude lobe"
    );
    assert!(
        std::fs::symlink_metadata(skill_lobe.join("skills/review")).is_ok(),
        "skill must link into the skill-only lobe"
    );

    // The rule links ONLY into the all-kinds Claude lobe, never the skill-only one.
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("rules/style")).is_ok()
            || std::fs::symlink_metadata(sb.claude_home.join("rules/style.md")).is_ok(),
        "rule must link into the Claude lobe"
    );
    assert!(
        std::fs::symlink_metadata(skill_lobe.join("rules/style.md")).is_err(),
        "rule must NOT link into a skill-only lobe (HARN-3)"
    );

    // The recorded manifest links reflect exactly the admitted lobes (HARN-2).
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let rule_links: Vec<&str> = manifest["items"]["rule:style"]["links"]
        .as_array()
        .expect("rule links array")
        .iter()
        .map(|l| l.as_str().unwrap())
        .collect();
    let skill_lobe_str = skill_lobe.display().to_string();
    assert!(
        !rule_links.iter().any(|l| l.starts_with(&skill_lobe_str)),
        "rule manifest links must omit the skill-only lobe: {rule_links:?}"
    );
    assert!(
        rule_links
            .iter()
            .any(|l| l.starts_with(&sb.claude_home.display().to_string())),
        "rule manifest links must include the Claude lobe: {rule_links:?}"
    );

    // HARN-6: the linked skill file is verbatim - the frontmatter is not rewritten
    // for the non-Claude lobe.
    let linked = std::fs::read_to_string(skill_lobe.join("skills/review/SKILL.md")).unwrap();
    let original = std::fs::read_to_string(sb.source.join("skills/review/SKILL.md")).unwrap();
    assert_eq!(
        linked, original,
        "mind links skill/agent files verbatim; no frontmatter rewrite (HARN-6)"
    );
}

// HARN-1: `config lobes list` and `config show` surface a lobe's kinds filter.
#[test]
fn list_and_show_display_kinds() {
    // spec: HARN-1
    let sb = Sandbox::new();
    assert!(
        sb.mind_home_sandboxed(&["config", "lobes", "add", "--preset", "gemini"])
            .success
    );

    let list = sb.mind(&["config", "lobes", "list"]).stdout;
    assert!(
        list.contains(".gemini/config") && list.contains("skill"),
        "list must show the kinds filter: {list}"
    );

    let show = sb.mind(&["config", "show"]).stdout;
    assert!(
        show.contains(".gemini/config") && show.contains("skill"),
        "show must surface the kinds filter: {show}"
    );
}

// HARN-5: `config lobes detect` reports the harness homes that exist under the
// detection base; without `--yes` (and non-TTY) it never mutates config; with
// `--yes` it adds the detected lobes. `--json` is machine-readable.
#[test]
fn detect_reports_then_yes_adds() {
    // spec: HARN-5
    let sb = Sandbox::new();
    // A detection base with .gemini present but no other harness markers.
    let detect_home = sb.base.join("detect");
    std::fs::create_dir_all(detect_home.join(".gemini")).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    // Report-only: a non-TTY run without --yes must NOT mutate config.
    let report = sb.mind_env(
        &["config", "lobes", "detect"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(report.success, "detect failed: {}", report.stderr);
    assert!(
        report.stdout.contains("gemini"),
        "detect must report gemini: {}",
        report.stdout
    );
    let after_report = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&after_report.stdout);
    assert!(
        !v["lobes"].as_array().unwrap().iter().any(|l| l["path"]
            .as_str()
            .is_some_and(|p| p.ends_with(".gemini/config"))),
        "report-only detect must NOT add the lobe: {}",
        after_report.stdout
    );

    // --json is machine-readable and lists the detected preset.
    let json = sb.mind_env(
        &["config", "lobes", "detect", "--json"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    let jv = parse_json(&json.stdout);
    assert_eq!(jv["action"], "lobe-detect", "{}", json.stdout);
    assert_eq!(
        jv["added"], false,
        "json report must not mutate: {}",
        json.stdout
    );
    assert!(
        jv["detected"]
            .as_array()
            .unwrap()
            .iter()
            .any(|d| d["preset"] == "gemini"),
        "detected must list gemini: {}",
        json.stdout
    );

    // --yes adds the detected lobe(s) under the detection base.
    let added = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(added.success, "detect --yes failed: {}", added.stderr);
    let after_add = sb.mind(&["config", "lobes", "list", "--json"]);
    let av = parse_json(&after_add.stdout);
    let gemini = av["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .find(|l| {
            l["path"]
                .as_str()
                .is_some_and(|p| p.ends_with(".gemini/config"))
        })
        .expect("detect --yes must add the gemini/config lobe");
    assert_eq!(
        gemini["path"].as_str().unwrap(),
        detect_home.join(".gemini/config").display().to_string(),
        "added lobe path must be under the detection base"
    );
}

// HARN-5: the `--yes` NON-JSON text path reports each added lobe in human output
// and actually persists it to config (the JSON --yes path is covered above; this
// pins the plain-text branch the implementor flagged).
#[test]
fn detect_yes_text_output_reports_and_persists() {
    // spec: HARN-5
    let sb = Sandbox::new();
    let detect_home = sb.base.join("detect");
    std::fs::create_dir_all(detect_home.join(".gemini")).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    let added = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(added.success, "detect --yes failed: {}", added.stderr);
    assert!(
        added.stdout.contains("gemini") && added.stdout.contains("added"),
        "text --yes must report the added gemini lobe: {}",
        added.stdout
    );

    // It must have persisted: a second non-JSON list shows the .gemini/config lobe.
    let list = sb.mind(&["config", "lobes", "list"]).stdout;
    assert!(
        list.contains(".gemini/config"),
        "detect --yes must persist the lobe: {list}"
    );
}

// HARN-5: when no known harness dirs exist under the detection base, detect
// reports "no new agent homes (lobes) detected" and mutates nothing - in both the
// text and JSON forms, with and without --yes (the empty-candidates path the
// implementor flagged).
#[test]
fn detect_no_homes_reports_nothing_and_mutates_nothing() {
    // spec: HARN-5
    let sb = Sandbox::new();
    // An empty detection base: no harness markers at all.
    let detect_home = sb.base.join("empty-detect");
    std::fs::create_dir_all(&detect_home).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    // Text form, even with --yes, says nothing was found and adds nothing.
    let text = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(text.success, "detect failed: {}", text.stderr);
    assert!(
        text.stdout.contains("no new agent homes (lobes) detected"),
        "empty detection must report none found: {}",
        text.stdout
    );

    // JSON form: detected is empty and added is false.
    let json = sb.mind_env(
        &["config", "lobes", "detect", "--json", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    let jv = parse_json(&json.stdout);
    assert_eq!(jv["action"], "lobe-detect");
    assert_eq!(
        jv["added"], false,
        "no candidates => added=false: {}",
        json.stdout
    );
    assert!(
        jv["detected"].as_array().unwrap().is_empty(),
        "detected must be empty: {}",
        json.stdout
    );

    // Config still has no lobes added.
    let list = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&list.stdout);
    // The default-only listing is the claude home (a single default entry), never
    // a harness lobe.
    assert!(
        !lv["lobes"].as_array().unwrap().iter().any(|l| l["path"]
            .as_str()
            .is_some_and(|p| p.ends_with(".gemini/config") || p.ends_with(".agents"))),
        "empty detection must not have added any harness lobe: {}",
        list.stdout
    );
}

// HARN-2/HARN-4/HARN-5: codex and universal both resolve to ~/.agents. When the
// detection base has BOTH `.codex` and `.agents` markers, detect must collapse
// the two same-path candidates to a single .agents lobe (first-seen wins) rather
// than offering/adding the same path twice. Drives the binary end-to-end.
#[test]
fn detect_dedups_codex_and_universal_same_path() {
    // spec: HARN-2
    // spec: HARN-5
    let sb = Sandbox::new();
    let detect_home = sb.base.join("detect-dup");
    // Both markers present: .codex (codex preset) and .agents (universal preset).
    std::fs::create_dir_all(detect_home.join(".codex")).unwrap();
    std::fs::create_dir_all(detect_home.join(".agents")).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    let json = sb.mind_env(
        &["config", "lobes", "detect", "--json"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    let jv = parse_json(&json.stdout);
    let agents_path = detect_home.join(".agents").display().to_string();
    let agents_entries: Vec<&serde_json::Value> = jv["detected"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|d| d["path"].as_str() == Some(agents_path.as_str()))
        .collect();
    assert_eq!(
        agents_entries.len(),
        1,
        "codex+universal must collapse to ONE ~/.agents candidate: {}",
        json.stdout
    );

    // And adding them persists exactly one .agents lobe.
    let added = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(added.success, "{}", added.stderr);
    let list = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&list.stdout);
    let agents_lobes: Vec<&serde_json::Value> = lv["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|l| l["path"].as_str() == Some(agents_path.as_str()))
        .collect();
    assert_eq!(
        agents_lobes.len(),
        1,
        "only one ~/.agents lobe must be persisted: {}",
        list.stdout
    );
}

// HARN-4: the codex preset adds its specific parent path and kinds end-to-end
// through the CLI (not just the unit lookup). codex is skill-only.
#[test]
fn preset_add_codex() {
    // spec: HARN-4
    let sb = Sandbox::new();
    let added = sb.mind_home_sandboxed(&["config", "lobes", "add", "--preset", "codex"]);
    assert!(added.success, "codex add failed: {}", added.stderr);

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let entry = v["lobes"]
        .as_array()
        .expect("lobes array")
        .iter()
        .find(|l| l["path"].as_str().is_some_and(|p| p.ends_with(".agents")))
        .unwrap_or_else(|| panic!("a .agents lobe entry for codex: {}", listed.stdout));
    let kinds: Vec<&str> = entry["kinds"]
        .as_array()
        .expect("kinds array")
        .iter()
        .map(|k| k.as_str().unwrap())
        .collect();
    assert_eq!(kinds, vec!["skill"], "codex kinds");
}

// HARN-4: the windsurf preset adds its specific parent path and kinds end-to-end
// through the CLI. windsurf is skill-only.
#[test]
fn preset_add_windsurf() {
    // spec: HARN-4
    let sb = Sandbox::new();
    let added = sb.mind_cwd_sandboxed(&["config", "lobes", "add", "--preset", "windsurf"]);
    assert!(added.success, "windsurf add failed: {}", added.stderr);

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let entry = v["lobes"]
        .as_array()
        .expect("lobes array")
        .iter()
        .find(|l| l["path"].as_str().is_some_and(|p| p.ends_with(".windsurf")))
        .unwrap_or_else(|| panic!("a .windsurf lobe entry for windsurf: {}", listed.stdout));
    let kinds: Vec<&str> = entry["kinds"]
        .as_array()
        .expect("kinds array")
        .iter()
        .map(|k| k.as_str().unwrap())
        .collect();
    assert_eq!(kinds, vec!["skill"], "windsurf kinds");
}

// HARN-2: a kinds-filtered lobe survives the item lifecycle. Install a skill
// (admitted everywhere) and a rule (Claude-only) into a [skill]-only lobe plus
// the all-kinds Claude lobe, then:
//  - `introspect` reports NO drift/missing-link for the intentionally-absent
//    rule link in the skill-only lobe (it operates on RECORDED links).
//  - `forget` removes exactly the recorded links and errors on nothing, even
//    though the rule was never linked into the skill-only lobe.
#[test]
fn kinds_filtered_lobe_lifecycle_forget_and_introspect() {
    // spec: HARN-2
    let sb = Sandbox::new();
    let skill_lobe = sb.base.join("skill-only-lobe");
    sb.write_config(&format!(
        "lobes = [\"{claude}\", {{ path = \"{skill}\", kinds = [\"skill\"] }}]\n",
        claude = sb.claude_home.display(),
        skill = skill_lobe.display(),
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");
    assert!(sb.mind(&["learn", "style"]).success, "learn rule");

    // introspect must be clean: the rule was never linked into the skill-only
    // lobe, so it must NOT be reported as a missing link.
    let intro = sb.mind(&["introspect", "--json"]);
    assert!(intro.success, "introspect failed: {}", intro.stderr);
    let iv = parse_json(&intro.stdout);
    let issues = iv["issues"].as_array().expect("issues array");
    assert!(
        issues.is_empty(),
        "a kinds-filtered lobe must produce no drift/missing-link issues: {}",
        intro.stdout
    );

    // forget the rule: it removes the recorded Claude link, leaves the skill-only
    // lobe untouched, and reports success with no error about a missing rule link.
    let forget_rule = sb.mind(&["forget", "style", "--yes"]);
    assert!(
        forget_rule.success,
        "forget of a rule in a kinds-filtered setup must succeed: {}",
        forget_rule.stderr
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("rules/style.md")).is_err(),
        "the recorded Claude rule link must be removed by forget"
    );
    // The skill is still linked in both lobes (it was admitted everywhere).
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok()
            && std::fs::symlink_metadata(skill_lobe.join("skills/review")).is_ok(),
        "the skill must remain linked in both lobes after forgetting the rule"
    );

    // forget the skill: both recorded links go away cleanly.
    let forget_skill = sb.mind(&["forget", "review", "--yes"]);
    assert!(forget_skill.success, "{}", forget_skill.stderr);
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err()
            && std::fs::symlink_metadata(skill_lobe.join("skills/review")).is_err(),
        "forget must remove the skill from every recorded lobe"
    );

    // Manifest is now empty of these items; introspect is still clean.
    let intro2 = sb.mind(&["introspect", "--json"]);
    let iv2 = parse_json(&intro2.stdout);
    assert!(
        iv2["issues"].as_array().unwrap().is_empty(),
        "introspect must stay clean after forget: {}",
        intro2.stdout
    );
}

// HARN-2: `upgrade` re-installs through the same kinds-aware link planning, so an
// upstream content change to a rule re-links only into the lobes that admit it
// (never the skill-only lobe), and produces no error about the absent link.
#[test]
fn upgrade_respects_kinds_filter() {
    // spec: HARN-2
    let sb = Sandbox::new();
    let skill_lobe = sb.base.join("skill-only-lobe");
    sb.write_config(&format!(
        "lobes = [\"{claude}\", {{ path = \"{skill}\", kinds = [\"skill\"] }}]\n",
        claude = sb.claude_home.display(),
        skill = skill_lobe.display(),
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "style"]).success, "learn rule");

    // Change the rule upstream and commit, then sync so the catalog sees it.
    write(
        &sb.source.join("rules/style.md"),
        "---\ndescription: ASCII only\n---\n# style rule v2\n",
    );
    git(&sb.source, &["commit", "-aqm", "bump rule"]);
    assert!(sb.mind(&["sync"]).success, "sync failed");

    let up = sb.mind(&["upgrade", "--yes"]);
    assert!(
        up.success,
        "upgrade of a kinds-filtered rule must succeed: {}",
        up.stderr
    );

    // The rule still links only into the Claude lobe, never the skill-only one.
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("rules/style.md")).is_ok(),
        "rule must remain linked in the Claude lobe after upgrade"
    );
    assert!(
        std::fs::symlink_metadata(skill_lobe.join("rules/style.md")).is_err(),
        "rule must NOT be linked into the skill-only lobe after upgrade (HARN-2)"
    );

    // The recorded links still omit the skill-only lobe.
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let rule_links: Vec<&str> = manifest["items"]["rule:style"]["links"]
        .as_array()
        .expect("rule links")
        .iter()
        .map(|l| l.as_str().unwrap())
        .collect();
    let skill_lobe_str = skill_lobe.display().to_string();
    assert!(
        !rule_links.iter().any(|l| l.starts_with(&skill_lobe_str)),
        "rule links must still omit the skill-only lobe after upgrade: {rule_links:?}"
    );
}

// HARN-3 / `config lobes` UX: a path supplied without `--preset` is fine, but
// supplying NEITHER a path nor `--preset` is the LobeTargetRequired error. Driven
// through the binary (the dispatch arm the implementor flagged as untested).
#[test]
fn lobes_add_without_path_or_preset_errors() {
    // spec: HARN-4
    let sb = Sandbox::new();
    let run = sb.mind(&["config", "lobes", "add"]);
    assert!(!run.success, "add with no target must fail");
    assert!(
        run.stderr.contains("path") && run.stderr.contains("--preset"),
        "error must mention both a path and --preset: {}",
        run.stderr
    );
}

// HARN-4: backward compat. An existing `lobes = ["~/.claude"]` style config (a
// bare string entry) must SURVIVE a `config lobes add --preset` rewrite as a
// bare string - the rewrite must not promote it to a table. The preset entry is
// added as a table with its kinds.
#[test]
fn preset_add_preserves_bare_entry_shape() {
    // spec: HARN-1
    // spec: HARN-4
    let sb = Sandbox::new();
    // Seed a bare-entry config exactly as a pre-feature install would have.
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));

    let added = sb.mind_home_sandboxed(&["config", "lobes", "add", "--preset", "gemini"]);
    assert!(added.success, "preset add failed: {}", added.stderr);

    // Read the rewritten config.toml verbatim and assert the bare entry stayed
    // bare (a quoted string), while the preset entry is a table with kinds.
    let raw = std::fs::read_to_string(sb.mind_home.join("config.toml")).unwrap();
    let bare = format!("\"{}\"", sb.claude_home.display());
    assert!(
        raw.contains(&bare),
        "the original bare lobe must remain a bare string after rewrite:\n{raw}"
    );
    assert!(
        raw.contains("kinds") && raw.contains(".gemini/config"),
        "the preset lobe must be a table with kinds:\n{raw}"
    );

    // And the JSON list shows the bare entry as a plain string (its shape-
    // preserving serialization), while the preset entry is an object with kinds.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let lobes = v["lobes"].as_array().unwrap();
    let claude_str = sb.claude_home.display().to_string();
    assert!(
        lobes
            .iter()
            .any(|l| l.as_str() == Some(claude_str.as_str())),
        "a bare lobe must serialize as a plain JSON string (all-kinds): {}",
        listed.stdout
    );
    assert!(
        lobes.iter().any(|l| l.is_object()
            && l["path"]
                .as_str()
                .is_some_and(|p| p.ends_with(".gemini/config"))
            && l["kinds"].is_array()),
        "the preset lobe must serialize as an object with a kinds array: {}",
        listed.stdout
    );
}

// HARN-4: `config lobes remove` drops a preset-added (detailed table) lobe by its
// path - removal keys on the path regardless of whether the entry carries a
// kinds filter.
#[test]
fn remove_preset_added_detailed_lobe_by_path() {
    // spec: HARN-4
    let sb = Sandbox::new();
    assert!(
        sb.mind_home_sandboxed(&["config", "lobes", "add", "--preset", "gemini"])
            .success
    );

    // Find the persisted path.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let gemini_path = v["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .find_map(|l| {
            l["path"]
                .as_str()
                .filter(|p| p.ends_with(".gemini/config"))
                .map(str::to_string)
        })
        .expect("gemini lobe path");

    let removed = sb.mind(&["config", "lobes", "remove", &gemini_path]);
    assert!(
        removed.success,
        "removing a detailed preset lobe by path must succeed: {}",
        removed.stderr
    );

    let after = sb.mind(&["config", "lobes", "list", "--json"]);
    let av = parse_json(&after.stdout);
    assert!(
        !av["lobes"].as_array().unwrap().iter().any(|l| l["path"]
            .as_str()
            .is_some_and(|p| p.ends_with(".gemini/config"))),
        "the gemini lobe must be gone after remove: {}",
        after.stdout
    );
}

// HARN-1: a tool item with an EXPLICIT link still links into a no-kinds lobe
// (TOOL-4 preserved: a no-kinds lobe admits every kind, including tool), but is
// excluded from a kinds-filtered lobe that does not list `tool`.
#[test]
fn tool_with_explicit_link_respects_kinds_filter() {
    // spec: HARN-1
    // A bespoke source: an authoritative mind.toml declaring a tool with a link.
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let base = std::env::temp_dir().join(format!("mind-tool-lobe-{}-{n}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    let source = base.join("agents");
    write(&source.join("toolkit/run.sh"), "#!/bin/sh\necho hi\n");
    write(
        &source.join("mind.toml"),
        "[source]\ndescription = \"tool source\"\n\n[[items]]\nkind = \"tool\"\nname = \"toolkit\"\npath = \"toolkit\"\nlink = \"tools/toolkit\"\n",
    );
    git(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
    git(&source, &["config", "user.email", "t@t"]);
    git(&source, &["config", "user.name", "t"]);
    git(&source, &["add", "-A"]);
    git(&source, &["commit", "-qm", "initial"]);

    let mind_home = base.join("mind");
    let claude_home = base.join("claude");
    std::fs::create_dir_all(&mind_home).unwrap();
    let skill_lobe = base.join("skill-only-lobe");

    let run = |args: &[&str]| -> Run {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_mind"));
        cmd.args(args)
            .env("MIND_HOME", &mind_home)
            .env("CLAUDE_HOME", &claude_home)
            .env_remove("MIND_AGENT_HOMES")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let out = cmd.output().expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    };

    // Config: a no-kinds Claude lobe plus a [skill]-only lobe.
    write(
        &mind_home.join("config.toml"),
        &format!(
            "lobes = [\"{claude}\", {{ path = \"{skill}\", kinds = [\"skill\"] }}]\n",
            claude = claude_home.display(),
            skill = skill_lobe.display(),
        ),
    );

    assert!(run(&["meld", &source.to_string_lossy()]).success);
    let learned = run(&["learn", "toolkit"]);
    assert!(learned.success, "learn tool failed: {}", learned.stderr);

    // The tool's explicit link lands in the no-kinds Claude lobe (TOOL-4).
    assert!(
        std::fs::symlink_metadata(claude_home.join("tools/toolkit")).is_ok(),
        "a tool with an explicit link must link into a no-kinds lobe (TOOL-4)"
    );
    // But NOT into the skill-only lobe (it does not admit `tool`).
    assert!(
        std::fs::symlink_metadata(skill_lobe.join("tools/toolkit")).is_err(),
        "a skill-only lobe must not receive a tool link (HARN-1)"
    );

    // Manifest links record only the admitted (Claude) lobe.
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let links: Vec<&str> = manifest["items"]["tool:toolkit"]["links"]
        .as_array()
        .expect("tool links")
        .iter()
        .map(|l| l.as_str().unwrap())
        .collect();
    let skill_lobe_str = skill_lobe.display().to_string();
    assert!(
        !links.iter().any(|l| l.starts_with(&skill_lobe_str)),
        "tool links must omit the skill-only lobe: {links:?}"
    );
    assert!(
        links
            .iter()
            .any(|l| l.starts_with(&claude_home.display().to_string())),
        "tool links must include the no-kinds Claude lobe: {links:?}"
    );

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

// CLI-150: `mind config lobes detect -y` must parse and run (not error with
// "unexpected argument '-y'"). With no detected homes the command exits 0.
#[test]
fn detect_short_yes_flag_is_accepted() {
    // spec: CLI-150
    let sb = Sandbox::new();
    // Empty detection base: no harness markers, so detect exits cleanly.
    let detect_home = sb.base.join("detect-empty");
    std::fs::create_dir_all(&detect_home).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    // Post-verb short flag: `mind config lobes detect -y`
    let run = sb.mind_env(
        &["config", "lobes", "detect", "-y"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(
        run.success,
        "detect -y must succeed (not error on the flag): stderr={}",
        run.stderr
    );
    assert!(
        !run.stderr.contains("unexpected argument"),
        "detect -y must not produce 'unexpected argument': {}",
        run.stderr
    );
}

// CLI-150: `mind -y config lobes detect` must parse correctly; the global -y
// must be the source of the confirmation flag, not a local field that would
// silently ignore the pre-verb position.
#[test]
fn detect_global_yes_pre_verb_is_accepted() {
    // spec: CLI-150
    let sb = Sandbox::new();
    let detect_home = sb.base.join("detect-empty2");
    std::fs::create_dir_all(&detect_home).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    // Pre-verb global flag: `mind -y config lobes detect`
    let run = sb.mind_env(
        &["-y", "config", "lobes", "detect"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(
        run.success,
        "mind -y config lobes detect must succeed: stderr={}",
        run.stderr
    );
    assert!(
        !run.stderr.contains("unexpected argument"),
        "mind -y detect must not error on the flag: {}",
        run.stderr
    );

    // Also verify pre-verb --yes works the same way.
    let detect_home2 = sb.base.join("detect-empty3");
    std::fs::create_dir_all(&detect_home2).unwrap();
    let detect_str2 = detect_home2.to_string_lossy().into_owned();
    let run2 = sb.mind_env(
        &["--yes", "config", "lobes", "detect"],
        &[("MIND_DETECT_HOME", &detect_str2)],
    );
    assert!(
        run2.success,
        "mind --yes config lobes detect must succeed: stderr={}",
        run2.stderr
    );
}

// HARN-7: `config lobes add --yes <path>` backfills already-installed items into
// the newly-added lobe without prompting.
#[test]
fn lobe_add_backfills_installed_items_with_yes() {
    // spec: HARN-7
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("newlobe");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", "--yes", &new_lobe_str]);
    assert!(added.success, "lobe add --yes failed: {}", added.stderr);

    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "the installed skill must be backfilled into the new lobe: {}",
        added.stdout
    );
}

// HARN-7: `config lobes add --preset <name> --yes` backfills installed items into
// the preset's lobe.
#[test]
fn lobe_add_preset_backfills_with_yes() {
    // spec: HARN-7
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // Pin HOME to the sandbox so the gemini preset resolves under it (never the
    // real home), keeping the backfilled symlink hermetic.
    let home_str = sb.base.to_string_lossy().into_owned();
    let added = sb.mind_env(
        &["config", "lobes", "add", "--preset", "gemini", "--yes"],
        &[("HOME", &home_str)],
    );
    assert!(added.success, "preset add --yes failed: {}", added.stderr);

    assert!(
        std::fs::symlink_metadata(sb.base.join(".gemini/config/skills/review")).is_ok(),
        "the installed skill must be backfilled into the gemini preset lobe: {}",
        added.stdout
    );
}

// HARN-7: `config lobes detect --yes` backfills installed items into a detected
// harness lobe.
#[test]
fn lobe_detect_backfills_with_yes() {
    // spec: HARN-7
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let detect_home = sb.base.join("detect");
    std::fs::create_dir_all(detect_home.join(".gemini")).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();
    let added = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(added.success, "detect --yes failed: {}", added.stderr);

    assert!(
        std::fs::symlink_metadata(detect_home.join(".gemini/config/skills/review")).is_ok(),
        "the installed skill must be backfilled into the detected gemini lobe: {}",
        added.stdout
    );
}

// HARN-17: non-interactive (non-TTY) `config lobes add` WITHOUT `--yes` still
// backfills already-installed items immediately (the backfill is unconditional
// in every mode) and prints no self-referential `introspect --fix` note.
#[test]
fn lobe_add_no_tty_no_yes_backfills_immediately() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("newlobe");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(added.success, "lobe add failed: {}", added.stderr);

    assert!(
        !added.stdout.contains("mind introspect --fix"),
        "HARN-17: the backfill is unconditional, so no introspect note is printed: {}",
        added.stdout
    );
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "HARN-17: without --yes, in a non-TTY, the skill must STILL be backfilled \
         into the new lobe immediately: {}",
        added.stdout
    );
}

// HARN-8: `introspect` (without --fix) reports a lobe whose installed items were
// never linked into it as a `missing-lobe-link` finding.
#[test]
fn introspect_reports_missing_lobe_links() {
    // spec: HARN-8
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // Register a second lobe by editing config directly rather than through
    // `config lobes add`: since HARN-17 that command backfills immediately, so
    // driving it here would link the item before introspect ever gets to see
    // the gap. Editing config.toml models a lobe added by any means that skips
    // the backfill (e.g. hand-edited config), leaving the skill genuinely
    // uncovered for introspect to detect.
    let new_lobe = sb.base.join("newlobe");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        new_lobe.display()
    ));

    let intro = sb.mind(&["introspect", "--json"]);
    let iv = parse_json(&intro.stdout);
    let issues = iv["issues"].as_array().expect("issues array");
    assert!(
        issues.iter().any(|i| i["kind"] == "missing-lobe-link"),
        "introspect must report the uncovered lobe as missing-lobe-link: {}",
        intro.stdout
    );
}

// HARN-8: `introspect --fix` creates the missing lobe links, updates the
// manifest, and leaves no missing-lobe-link finding on a re-run.
#[test]
fn introspect_fix_creates_missing_lobe_links() {
    // spec: HARN-8
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // Register a second lobe directly in config (see the comment in
    // introspect_reports_missing_lobe_links: `config lobes add` now backfills
    // immediately per HARN-17, which would pre-empt this test's scenario).
    let new_lobe = sb.base.join("newlobe");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        new_lobe.display()
    ));

    let fixed = sb.mind(&["introspect", "--fix"]);
    assert!(fixed.success, "introspect --fix failed: {}", fixed.stderr);
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "introspect --fix must create the missing lobe link: {}",
        fixed.stdout
    );

    // A re-run is clean: the manifest now records the link, so no finding remains.
    let intro = sb.mind(&["introspect", "--json"]);
    let iv = parse_json(&intro.stdout);
    let issues = iv["issues"].as_array().expect("issues array");
    assert!(
        !issues.iter().any(|i| i["kind"] == "missing-lobe-link"),
        "after --fix no missing-lobe-link finding must remain: {}",
        intro.stdout
    );
}

// HARN-7: adding a lobe when nothing is installed skips the backfill silently
// (no prompt, no note) and still reports the added lobe.
#[test]
fn lobe_add_no_items_skips_backfill_silently() {
    // spec: HARN-7
    let sb = Sandbox::new();
    let new_lobe = sb.base.join("newlobe");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(added.success, "lobe add failed: {}", added.stderr);

    assert!(
        added.stdout.contains("added lobe"),
        "add must confirm the lobe: {}",
        added.stdout
    );
    assert!(
        !added.stdout.contains("mind introspect --fix"),
        "with nothing installed there is no backfill note: {}",
        added.stdout
    );
}

// HARN-17: `config lobes add --json <path>` WITHOUT `--yes` still backfills
// already-installed items immediately — the backfill is unconditional in every
// mode, including JSON without `--yes` — while emitting valid JSON as its only
// stdout output (no "introspect" prose note).
#[test]
fn harn17_json_no_yes_backfills_silently() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("newlobe-json-noskip");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    // Non-TTY, no --yes, but in --json mode.
    let run = sb.mind(&["config", "lobes", "add", "--json", &new_lobe_str]);
    assert!(run.success, "lobe add --json failed: {}", run.stderr);

    // Output must be parseable JSON (not prose).
    let v = parse_json(&run.stdout);
    assert_eq!(
        v["action"], "lobe-add",
        "JSON must include action: {}",
        run.stdout
    );
    assert_eq!(v["outcome"], "added", "lobe must be added: {}", run.stdout);

    // No self-referential "introspect --fix" note, in JSON or otherwise.
    assert!(
        !run.stdout.contains("introspect"),
        "JSON mode must not emit the introspect note: {}",
        run.stdout
    );

    // HARN-17: the item IS backfilled even without --yes, in JSON mode.
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "HARN-17: the backfill is unconditional, so the skill must be backfilled \
         even without --yes in JSON mode: {}",
        run.stdout
    );
}

// HARN-7: `config lobes add --json --yes <path>` backfills already-installed items
// silently (no prose) and emits valid JSON as its only stdout output.
#[test]
fn harn7_json_yes_backfills_silently() {
    // spec: HARN-7
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("newlobe-json-yes");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let run = sb.mind(&["config", "lobes", "add", "--json", "--yes", &new_lobe_str]);
    assert!(run.success, "lobe add --json --yes failed: {}", run.stderr);

    // Output must be parseable JSON.
    let v = parse_json(&run.stdout);
    assert_eq!(v["action"], "lobe-add", "{}", run.stdout);
    assert_eq!(v["outcome"], "added", "{}", run.stdout);

    // The item IS backfilled (JSON + --yes = silent backfill).
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "with --yes the skill must be backfilled in JSON mode: {}",
        run.stdout
    );
}

// HARN-7: backfill via a skill-only preset (codex) respects the `kinds` filter:
// the skill is linked into the new lobe but the rule is NOT.
#[test]
fn harn7_backfill_preset_codex_skill_only_excludes_rule() {
    // spec: HARN-7
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");
    assert!(sb.mind(&["learn", "style"]).success, "learn rule");

    // Add the codex preset (skill-only, resolves to ~/.agents) with --yes to
    // trigger immediate backfill. Pin HOME to the sandbox base so the preset
    // resolves hermetically under it.
    let home_str = sb.base.to_string_lossy().into_owned();
    let added = sb.mind_env(
        &["config", "lobes", "add", "--preset", "codex", "--yes"],
        &[("HOME", &home_str)],
    );
    assert!(added.success, "preset add --yes failed: {}", added.stderr);

    // The skill IS backfilled into the codex lobe (<base>/.agents/skills/review).
    assert!(
        std::fs::symlink_metadata(sb.base.join(".agents/skills/review")).is_ok(),
        "the skill must be backfilled into the codex (skill-only) lobe"
    );
    // The rule is NOT linked: codex preset is skill-only and excludes rules.
    assert!(
        std::fs::symlink_metadata(sb.base.join(".agents/rules/style.md")).is_err(),
        "the rule must NOT be backfilled into a skill-only lobe (HARN-1/HARN-7)"
    );
}

// HARN-7: adding a lobe that is ALREADY configured (no-op path) does NOT trigger
// backfill; only newly-added lobes receive the backfill offer.
#[test]
fn harn7_no_op_lobe_add_does_not_backfill() {
    // spec: HARN-7
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("existing-lobe");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();

    // First add: newly-added lobe receives backfill with --yes.
    let first = sb.mind(&["config", "lobes", "add", "--yes", &new_lobe_str]);
    assert!(first.success, "{}", first.stderr);
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "first add must backfill the skill"
    );

    // Remove the link so we can detect if a second add re-creates it.
    std::fs::remove_file(new_lobe.join("skills/review")).unwrap();

    // Second add (same path) is a no-op: lobe already configured.
    let second = sb.mind(&["config", "lobes", "add", "--yes", &new_lobe_str]);
    assert!(second.success, "{}", second.stderr);
    assert!(
        second.stdout.contains("already configured"),
        "must report lobe already configured: {}",
        second.stdout
    );
    // The link was NOT recreated: no-op add does not trigger backfill.
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_err(),
        "no-op add must not backfill items into an already-configured lobe"
    );
}

// U41/HARN-15: `config lobes add --preset gemini` when `~/.gemini` does not
// exist yet must CREATE the resolved lobe path immediately (not merely record
// a config entry that never links and later gets pruned by `introspect
// --fix`). The already-installed skill is backfilled right away (HARN-17), and
// a follow-up `introspect --fix` reports no outstanding issue with the entry
// still intact.
#[test]
fn harn15_preset_add_creates_missing_lobe_dir_backfills_and_stays_clean() {
    // spec: HARN-15
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // A fresh HOME with no `.gemini` marker at all -- the U41 scenario (adding
    // the lobe before Gemini CLI is installed).
    let home = sb.base.join("fresh-home");
    std::fs::create_dir_all(&home).unwrap();
    assert!(
        std::fs::symlink_metadata(home.join(".gemini")).is_err(),
        "sanity: ~/.gemini must not exist before the add"
    );

    let home_str = home.to_string_lossy().into_owned();
    let added = sb.mind_env(
        &["config", "lobes", "add", "--preset", "gemini"],
        &[("HOME", &home_str)],
    );
    assert!(added.success, "preset add failed: {}", added.stderr);

    // HARN-15: the resolved lobe path itself must now exist on disk, not just
    // as a config entry.
    let lobe_path = home.join(".gemini/config");
    assert!(
        lobe_path.is_dir(),
        "HARN-15: the resolved lobe path must be created immediately: {}",
        added.stdout
    );

    // HARN-17: the already-installed skill is backfilled immediately.
    assert!(
        std::fs::symlink_metadata(lobe_path.join("skills/review")).is_ok(),
        "HARN-17: the installed skill must be backfilled into the gemini lobe: {}",
        added.stdout
    );

    // A follow-up `introspect --fix` must report the lobe clean (reachable,
    // nothing to repair) rather than pruning it as vanished.
    let intro = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(intro.success, "introspect --fix failed: {}", intro.stderr);
    let iv = parse_json(&intro.stdout);
    let issues = iv["issues"].as_array().expect("issues array");
    assert!(
        issues.is_empty(),
        "introspect --fix must report no outstanding issue for a reachable, \
         fully-backfilled preset lobe: {}",
        intro.stdout
    );

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&listed.stdout);
    let lobe_path_str = lobe_path.to_string_lossy().into_owned();
    assert!(
        lv["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(lobe_path_str.as_str())),
        "the gemini lobe entry must remain in config, not pruned as vanished: {}",
        listed.stdout
    );
}

// HARN-16: when a configured lobe is unreachable (its parent directory does
// not exist) at install time, the per-item fan-out skips it and prints a
// ONE-TIME note naming both remedies -- once per process, not once per
// installed item.
#[test]
fn harn16_unreachable_lobe_prints_note_once_per_process() {
    // spec: HARN-16
    let sb = Sandbox::new();
    let vanished_project = sb.base.join("vanished-project");
    // Deliberately do NOT create vanished_project: its `.windsurf` lobe is
    // unreachable from the moment it is configured.
    let unreachable_lobe = vanished_project.join(".windsurf");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        unreachable_lobe.display()
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    // Install both items in one invocation (a glob) so a multi-item install
    // exercises the per-PROCESS dedup, not merely a per-item skip.
    let learn = sb.mind(&["learn", "*"]);
    assert!(learn.success, "learn failed: {}", learn.stderr);

    let occurrences = learn.stdout.matches("is unreachable").count();
    assert_eq!(
        occurrences, 1,
        "HARN-16: the unreachable-lobe note must print exactly once per \
         process, not once per skipped item: {}",
        learn.stdout
    );
    assert!(
        learn.stdout.contains("config lobes remove"),
        "the note must name the config-remove remedy: {}",
        learn.stdout
    );
}

/// Mirrors `crate::error::shell_quote` (HOOK-106/CLI-225). Reproduced here
/// (not imported) because an integration test is a separate crate from the
/// binary and cannot reach a `pub(crate)` item.
fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

// HARN-16 / CLI-225: the unreachable-lobe note's `mind config lobes remove
// <path>` remedy embeds a path taken straight from user config
// (`~/.mind/config.toml`), not restricted against shell metacharacters, so it
// must be shell-quoted before printing.
#[test]
fn harn16_unreachable_lobe_note_shell_quotes_a_metachar_path() {
    // spec: HARN-16, CLI-225
    let sb = Sandbox::new();
    // A directory name carrying a `'`/`;`/`$(...)` -- all valid on a Linux
    // filesystem in a single path component -- whose parent is never created,
    // so the lobe is unreachable from the moment it is configured.
    let vanished_project = sb.base.join("it's a $(vanished); project");
    let unreachable_lobe = vanished_project.join(".windsurf");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        unreachable_lobe.display()
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    let learn = sb.mind(&["learn", "*"]);
    assert!(learn.success, "learn failed: {}", learn.stderr);

    let path_str = unreachable_lobe.to_string_lossy().into_owned();
    let quoted = shell_quote(&path_str);
    assert!(
        learn
            .stdout
            .contains(&format!("mind config lobes remove {quoted}")),
        "the remedy must shell-quote the unreachable lobe's path: {}",
        learn.stdout
    );
    assert!(
        !learn
            .stdout
            .contains(&format!("mind config lobes remove {path_str}")),
        "the raw path must never be spliced in unquoted: {}",
        learn.stdout
    );
}

// HARN-17: `link-project` in a fresh project backfills already-installed items
// immediately (no introspect --fix note), matching `config lobes add`.
#[test]
fn harn17_link_project_backfills_existing_items_immediately() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let proj = sb.base.join("freshproj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    let r = sb.mind(&["link-project", &proj_str]);
    assert!(r.success, "link-project failed: {}", r.stderr);

    assert!(
        !r.stdout.contains("mind introspect --fix"),
        "HARN-17: link-project's backfill is unconditional; no introspect \
         note must be printed: {}",
        r.stdout
    );
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/skills/review")).is_ok(),
        "HARN-17: the already-installed skill must be linked immediately by \
         link-project: {}",
        r.stdout
    );
}

// HARN-17: a pre-existing foreign file at a backfill target is reported (the
// `LinkOccupied` failure, naming the `--force` remedy) rather than clobbered.
#[test]
fn harn17_backfill_reports_foreign_target_without_clobbering() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("foreign-lobe");
    let skills_dir = new_lobe.join("skills");
    std::fs::create_dir_all(&skills_dir).unwrap();
    let foreign_target = skills_dir.join("review");
    let foreign_content = b"not managed by mind";
    std::fs::write(&foreign_target, foreign_content).unwrap();

    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(added.success, "lobe add failed: {}", added.stderr);

    // The foreign file must be reported, naming --force, and NOT clobbered.
    assert!(
        added.stdout.contains("--force"),
        "a blocked backfill target must name the --force remedy: {}",
        added.stdout
    );
    let meta = std::fs::symlink_metadata(&foreign_target).unwrap();
    assert!(
        !meta.file_type().is_symlink(),
        "the foreign file must NOT be clobbered into a symlink"
    );
    assert_eq!(
        std::fs::read(&foreign_target).unwrap(),
        foreign_content,
        "the foreign file's content must be untouched"
    );
}

// HARN-8: when a foreign file at the expected link's parent directory blocks link
// creation during `introspect --fix`, the fix emits a `missing-lobe-link` finding
// but still exits 0 and does not abort processing of other items or lobes.
#[test]
fn harn8_introspect_fix_clobber_reports_finding_and_continues() {
    // spec: HARN-8
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // Register a second lobe by editing config directly rather than through
    // `config lobes add`: since HARN-17 that command backfills immediately, it
    // would create `new_lobe/skills/` as a real directory before this test gets
    // a chance to plant the blocking FILE at that same path.
    let new_lobe = sb.base.join("blocked-lobe");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        new_lobe.display()
    ));

    // Plant a regular FILE at `new_lobe/skills` so that mkdir_p inside
    // ensure_link fails with ENOTDIR when it tries to create the skills/ dir.
    std::fs::create_dir_all(&new_lobe).unwrap();
    std::fs::write(new_lobe.join("skills"), "blocking file").unwrap();

    // introspect --fix must report the clobber but still exit 0.
    let run = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(
        run.success,
        "introspect --fix must not abort on a clobber conflict: {}",
        run.stderr
    );

    let v = parse_json(&run.stdout);
    let issues = v["issues"].as_array().expect("issues array");
    assert!(
        issues.iter().any(|i| i["kind"] == "missing-lobe-link"),
        "a blocked link must produce a missing-lobe-link finding: {}",
        run.stdout
    );

    // The skill is still NOT linked (creation failed).
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_err(),
        "the blocked link must remain absent after --fix"
    );

    // The original skill symlink in claude_home must survive the clobber error
    // and remain intact -- only the new blocked lobe is affected. spec: HARN-8
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "the original claude_home skill symlink must be intact after a blocked lobe error (HARN-8)"
    );
}

// HARN-8: `introspect --fix` must report exactly ONE `missing-lobe-link` finding per
// blocked link -- the error propagated from `link_into_new_lobes`, and no additional
// redundant finding from a second `symlink_metadata` check.
//
#[test]
fn harn8_introspect_fix_reports_exactly_one_finding_per_blocked_link() {
    // spec: HARN-8
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // Register a second lobe directly in config (see the comment in
    // harn8_introspect_fix_clobber_reports_finding_and_continues: `config lobes
    // add` now backfills immediately per HARN-17, which would pre-create the
    // `skills/` directory this test needs to plant a blocking file at).
    let new_lobe = sb.base.join("blocked-lobe-count");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        new_lobe.display()
    ));

    // Plant a regular FILE at `new_lobe/skills` so mkdir_p fails with ENOTDIR.
    std::fs::create_dir_all(&new_lobe).unwrap();
    std::fs::write(new_lobe.join("skills"), "blocking file").unwrap();

    let run = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(
        run.success,
        "introspect --fix must not abort: {}",
        run.stderr
    );

    let v = parse_json(&run.stdout);
    let issues = v["issues"].as_array().expect("issues array");
    let count = issues
        .iter()
        .filter(|i| i["kind"] == "missing-lobe-link")
        .count();
    assert_eq!(
        count, 1,
        "exactly one missing-lobe-link finding per blocked link, got {count}: {}",
        run.stdout
    );
}

// HARN-8: when a recorded link is in the manifest but absent from disk (broken
// symlink), `introspect` (without --fix) fires BOTH `missing-link` and
// `missing-lobe-link` for that link. This documents the current behavior: the
// first fires from the manifest-vs-disk check; the second fires from the HARN-8
// lobe-coverage check (on-disk test fails). With `--fix`, relink restores the
// symlink and neither finding fires on a re-run.
#[test]
fn harn8_broken_recorded_link_fires_both_findings_without_fix() {
    // spec: HARN-8
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // Delete the skill symlink from disk; it remains in the manifest.
    // The link is a symlink, so remove_file removes the link itself (not the store).
    std::fs::remove_file(sb.claude_home.join("skills/review")).unwrap();

    // Without --fix: both missing-link and missing-lobe-link fire for the same path.
    let intro = sb.mind(&["introspect", "--json"]);
    let iv = parse_json(&intro.stdout);
    let issues = iv["issues"].as_array().expect("issues array");
    assert!(
        issues.iter().any(|i| i["kind"] == "missing-link"),
        "a broken recorded link must fire a missing-link finding: {}",
        intro.stdout
    );
    assert!(
        issues.iter().any(|i| i["kind"] == "missing-lobe-link"),
        "a broken recorded link also fires missing-lobe-link (on-disk check, HARN-8): {}",
        intro.stdout
    );

    // With --fix: relink restores the symlink; a re-run finds no issues.
    let fixed = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(fixed.success, "{}", fixed.stderr);
    let fv = parse_json(&fixed.stdout);
    let fixed_issues = fv["issues"].as_array().expect("issues array");
    assert!(
        fixed_issues.is_empty(),
        "after --fix no issues must remain for a broken recorded link: {}",
        fixed.stdout
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "the symlink must be restored by --fix"
    );
}

// HARN-8: the real user scenario -- items installed with the implicit default
// (no lobes in config), then lobes added, then `introspect --fix` backfills
// them. The `link_rel` recovery falls back to `default_link_rel` because
// the recorded links are in claude_home, which is NOT in agent_homes() once an
// explicit lobe list is configured.
#[test]
fn introspect_fix_backfills_after_implicit_default_install() {
    // spec: HARN-8
    let sb = Sandbox::new();
    // NOTE: no write_config here -- install goes to the implicit claude_home default.
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "skill must be linked into implicit claude_home"
    );

    // Register a new lobe by editing config directly rather than through
    // `config lobes add`: since HARN-17 that command backfills immediately, so
    // this test (which exercises introspect --fix's OWN backfill capability,
    // independent of an add-time backfill) models a lobe added by any means
    // that skips it (e.g. hand-edited config).
    let new_lobe = sb.base.join("newlobe");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        new_lobe.display()
    ));

    // introspect --fix must create the missing link in the new lobe.
    let fixed = sb.mind(&["introspect", "--fix"]);
    assert!(fixed.success, "introspect --fix failed: {}", fixed.stderr);
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "introspect --fix must create the missing lobe link: {}",
        fixed.stdout
    );

    // A re-run must be clean.
    let intro = sb.mind(&["introspect", "--json"]);
    let iv = parse_json(&intro.stdout);
    let issues = iv["issues"].as_array().expect("issues array");
    assert!(
        !issues.iter().any(|i| i["kind"] == "missing-lobe-link"),
        "after --fix no missing-lobe-link must remain: {}",
        intro.stdout
    );
}

// HARN-9: when the first explicit lobe is added to an empty lobes config,
// claude_home is auto-preserved so that new installs still reach it.
#[test]
fn first_lobe_add_preserves_claude_home() {
    // spec: HARN-9
    let sb = Sandbox::new();
    // No write_config: lobes config starts empty (implicit claude_home default).
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let new_lobe = sb.base.join("newlobe");
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    assert!(
        sb.mind(&["config", "lobes", "add", &new_lobe_str]).success,
        "lobe add must succeed"
    );

    // Install an item after the lobe add.
    assert!(
        sb.mind(&["learn", "review"]).success,
        "learn after lobe-add failed"
    );

    // Item must be in BOTH claude_home (preserved implicit default) and new_lobe.
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "new install must reach claude_home after first lobe-add"
    );
    assert!(
        std::fs::symlink_metadata(new_lobe.join("skills/review")).is_ok(),
        "new install must reach the explicitly-added lobe"
    );
}

// HARN-9: `config lobes add` when claude_home itself is the path does not
// create a duplicate entry.
#[test]
fn lobe_add_claude_home_no_duplicate() {
    // spec: HARN-9
    let sb = Sandbox::new();
    let ch = sb.claude_home.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", &ch]);
    assert!(
        added.success,
        "lobe add claude_home failed: {}",
        added.stderr
    );

    // lobe list must show exactly one entry (not claude_home twice).
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&listed.stdout);
    let lobes = lv["lobes"].as_array().expect("lobes array");
    assert_eq!(
        lobes.len(),
        1,
        "adding claude_home must not create a duplicate: {}",
        listed.stdout
    );
}

// HARN-9: `config lobes add --preset gemini` on an explicit empty lobes config
// (`lobes = []`) auto-prepends claude_home before saving the new lobe. This
// exercises the `cfg.lobes.is_empty()` branch -- distinct from the no-config-file
// case, which goes through `ensure_config` and already has claude_home in the list.
#[test]
fn preset_add_preserves_claude_home_on_empty_lobes_config() {
    // spec: HARN-9
    let sb = Sandbox::new();
    // Explicit empty lobes list to trigger the cfg.lobes.is_empty() HARN-9 branch.
    sb.write_config("lobes = []\n");

    // Pin HOME so the gemini preset resolves hermetically under the sandbox.
    let home_str = sb.base.to_string_lossy().into_owned();
    let added = sb.mind_env(
        &["config", "lobes", "add", "--preset", "gemini"],
        &[("HOME", &home_str)],
    );
    assert!(added.success, "preset add failed: {}", added.stderr);

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let lobes = v["lobes"].as_array().expect("lobes array");

    // Must have two saved entries: claude_home (auto-prepended) + gemini preset.
    assert_eq!(
        lobes.len(),
        2,
        "claude_home must be auto-prepended before the gemini preset on empty config: {}",
        listed.stdout
    );
    let ch = sb.claude_home.to_string_lossy().into_owned();
    assert!(
        lobes.iter().any(|l| {
            // bare entries serialize as plain JSON strings
            l.as_str() == Some(ch.as_str()) || l["path"].as_str() == Some(ch.as_str())
        }),
        "claude_home must appear as first entry in the saved lobe list: {}",
        listed.stdout
    );
}

// HARN-9: `config lobes detect --yes` on an explicit empty lobes config
// (`lobes = []`) auto-prepends claude_home before saving the detected lobes.
// Mirrors the preset path but exercises the `lobe_detect` HARN-9 branch.
#[test]
fn detect_yes_preserves_claude_home_on_empty_lobes_config() {
    // spec: HARN-9
    let sb = Sandbox::new();
    // Explicit empty lobes list to trigger the cfg.lobes.is_empty() HARN-9 branch.
    sb.write_config("lobes = []\n");

    // Create a .gemini marker dir under the detect base so the gemini preset is found.
    let detect_home = sb.base.join("detect");
    std::fs::create_dir_all(detect_home.join(".gemini")).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();
    let added = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(added.success, "detect --yes failed: {}", added.stderr);

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let lobes = v["lobes"].as_array().expect("lobes array");

    // Must have two saved entries: claude_home (auto-prepended) + detected gemini lobe.
    assert_eq!(
        lobes.len(),
        2,
        "claude_home must be auto-prepended by detect --yes on empty config: {}",
        listed.stdout
    );
    let ch = sb.claude_home.to_string_lossy().into_owned();
    assert!(
        lobes.iter().any(|l| {
            // bare entries serialize as plain JSON strings
            l.as_str() == Some(ch.as_str()) || l["path"].as_str() == Some(ch.as_str())
        }),
        "claude_home must appear in the saved lobe list after detect: {}",
        listed.stdout
    );
}

// HARN-11 / CLI-198: `link-project <dir>` (default preset = windsurf) registers a
// project-scoped windsurf lobe at `<dir>/.windsurf`, then a `learn` fans the skill
// into it. Rules (Claude-only) must NOT appear in the windsurf lobe (HARN-10).
#[test]
fn link_project_adds_windsurf_lobe_and_fans_skill() {
    // spec: HARN-11 CLI-198
    let sb = Sandbox::new();
    let proj = sb.base.join("myproject");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // `mind link-project <proj>` -- no --preset means windsurf by default (HARN-11).
    let r = sb.mind(&["link-project", &proj_str]);
    assert!(r.success, "link-project failed: {}", r.stderr);

    // Config must record the windsurf lobe at <proj>/.windsurf with kinds=[skill].
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let ws_entry = v["lobes"]
        .as_array()
        .expect("lobes array")
        .iter()
        .find(|l| l["path"].as_str() == Some(ws_path.as_str()))
        .unwrap_or_else(|| {
            panic!(
                "windsurf lobe at {ws_path} must be in config: {}",
                listed.stdout
            )
        });
    let kinds: Vec<&str> = ws_entry["kinds"]
        .as_array()
        .expect("kinds array")
        .iter()
        .map(|k| k.as_str().unwrap())
        .collect();
    assert_eq!(
        kinds,
        vec!["skill"],
        "windsurf lobe must be skill-only (HARN-10)"
    );

    // Gitignore guidance must appear in output for project-scoped lobes (HARN-11).
    assert!(
        r.stdout.contains("gitignore") || r.stdout.contains(".gitignore"),
        "link-project must print gitignore guidance: {}",
        r.stdout
    );

    // Meld + learn: skill and rule both installed.
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");
    assert!(sb.mind(&["learn", "style"]).success, "learn rule");

    // Skill must be linked into the windsurf lobe.
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/skills/review")).is_ok(),
        "skill must fan into the windsurf project lobe"
    );
    // Rule must NOT be linked into the windsurf lobe (skill-only).
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/rules")).is_err()
            && std::fs::symlink_metadata(proj.join(".windsurf/rules/style.md")).is_err(),
        "rule must NOT land in the windsurf lobe (skill-only, HARN-10)"
    );
}

// HARN-10 / CLI-199: `config lobes add <proj> --preset windsurf` is equivalent to
// `link-project <proj>`, and `--subdir <rel>` creates a skill-only lobe at
// `<proj>/<rel>`. A missing base directory returns a LobeBaseMissing error.
#[test]
fn config_lobes_add_with_preset_and_subdir() {
    // spec: HARN-10 CLI-199
    let sb = Sandbox::new();
    let proj = sb.base.join("proj2");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // `config lobes add <proj> --preset windsurf` = alias for link-project.
    let r = sb.mind(&["config", "lobes", "add", &proj_str, "--preset", "windsurf"]);
    assert!(
        r.success,
        "config lobes add --preset windsurf failed: {}",
        r.stderr
    );
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        v["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "config lobes add --preset windsurf must register the windsurf lobe: {}",
        listed.stdout
    );

    // `--subdir .cursor` creates a skill-only lobe at <proj>/.cursor (HARN-10).
    let proj2 = sb.base.join("proj3");
    std::fs::create_dir_all(&proj2).unwrap();
    let proj2_str = proj2.to_string_lossy().into_owned();
    let r2 = sb.mind(&["config", "lobes", "add", &proj2_str, "--subdir", ".cursor"]);
    assert!(
        r2.success,
        "config lobes add --subdir failed: {}",
        r2.stderr
    );
    let cursor_path = proj2.join(".cursor").to_string_lossy().into_owned();
    let listed2 = sb.mind(&["config", "lobes", "list", "--json"]);
    let v2 = parse_json(&listed2.stdout);
    let cursor_entry = v2["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .find(|l| l["path"].as_str() == Some(cursor_path.as_str()))
        .unwrap_or_else(|| panic!("cursor lobe must be in config: {}", listed2.stdout));
    assert_eq!(
        cursor_entry["kinds"]
            .as_array()
            .unwrap()
            .iter()
            .map(|k| k.as_str().unwrap())
            .collect::<Vec<_>>(),
        vec!["skill"],
        "subdir lobe must be skill-only"
    );

    // A missing base returns LobeBaseMissing -- the binary must exit non-zero.
    let missing = sb.mind(&[
        "config",
        "lobes",
        "add",
        "/nonexistent/proj/xyz",
        "--preset",
        "windsurf",
    ]);
    assert!(!missing.success, "missing base must fail");
    assert!(
        missing.stderr.contains("nonexistent")
            || missing.stderr.contains("not found")
            || missing.stderr.contains("does not exist")
            || missing.stderr.contains("missing"),
        "error must mention the missing path: {}",
        missing.stderr
    );
}

// HARN-10 / CLI-198: `link-project` with no explicit dir defaults to cwd (windsurf
// preset).
#[test]
fn link_project_defaults_to_cwd() {
    // spec: HARN-10 CLI-198
    let sb = Sandbox::new();
    let proj = sb.base.join("proj-cwd");
    std::fs::create_dir_all(&proj).unwrap();
    // Canonicalize: link-project records the cwd as `current_dir()` reports it,
    // which macOS resolves through the /var -> /private/var symlink. Compare
    // against the same canonical form so the path string matches on every OS.
    let proj = std::fs::canonicalize(&proj).unwrap();

    // Run link-project with cwd = proj and no positional dir argument.
    let r = sb.run_cwd(&["link-project"], &[], Some(&proj));
    assert!(r.success, "link-project (cwd) failed: {}", r.stderr);

    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        v["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "link-project with no dir must use cwd/.windsurf: {}",
        listed.stdout
    );
}

// HARN-12: `--snapshot` on `link-project` writes frozen real-file copies to
// `<proj>/.windsurf/...`, registers NO config entry, and a subsequent `forget`
// leaves the frozen copy intact.
#[test]
fn snapshot_writes_real_files_no_lobe_registered() {
    // spec: HARN-12
    let sb = Sandbox::new();
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let proj = sb.base.join("snapproj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // Snapshot: write real files, no managed lobe entry.
    let r = sb.mind(&["link-project", &proj_str, "--snapshot"]);
    assert!(r.success, "link-project --snapshot failed: {}", r.stderr);
    assert!(
        r.stdout.contains("frozen") || r.stdout.contains("wrote"),
        "snapshot must report frozen files: {}",
        r.stdout
    );

    // The skill dir must exist as a REAL directory (not a symlink).
    let skill_dir = proj.join(".windsurf/skills/review");
    let md = std::fs::metadata(&skill_dir);
    assert!(
        md.is_ok(),
        "skill dir must exist after snapshot: {}",
        r.stdout
    );
    // On Linux, `metadata` follows symlinks; a symlink to a dir has `is_dir()` too.
    // Use `symlink_metadata` to distinguish real dirs from symlinks.
    let sym_md = std::fs::symlink_metadata(&skill_dir).unwrap();
    assert!(
        !sym_md.file_type().is_symlink(),
        "snapshot must write a real dir, not a symlink"
    );

    // Config must NOT have a windsurf lobe entry (no managed registration).
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    assert!(
        !v["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "snapshot must NOT register a managed lobe: {}",
        listed.stdout
    );

    // `forget review` must succeed and the frozen copy must REMAIN (unmanaged).
    let forget = sb.mind(&["forget", "review", "--yes"]);
    assert!(forget.success, "forget failed: {}", forget.stderr);
    assert!(
        skill_dir.exists(),
        "snapshot copy must survive forget (it is not a managed link)"
    );
}

// HARN-12: `config lobes remove <path> --snapshot` converts managed symlinks in
// the lobe to frozen real-file copies and drops the config entry.
#[test]
fn lobe_remove_snapshot_converts_symlinks_to_real_files() {
    // spec: HARN-12
    let sb = Sandbox::new();
    let proj = sb.base.join("rmsnap");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // Register the lobe, meld+learn so there are symlinks inside it.
    assert!(sb.mind(&["link-project", &proj_str]).success);
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    // learn with --yes so backfill fires for the new lobe.
    assert!(
        sb.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );

    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let skill_link = proj.join(".windsurf/skills/review");

    // Symlink must be present before removal.
    assert!(
        std::fs::symlink_metadata(&skill_link).is_ok(),
        "skill symlink must exist in the windsurf lobe before remove"
    );
    let pre_sym_md = std::fs::symlink_metadata(&skill_link).unwrap();
    assert!(
        pre_sym_md.file_type().is_symlink(),
        "pre-remove: the skill entry must be a symlink"
    );

    // Remove with --snapshot: converts and drops.
    let r = sb.mind(&["config", "lobes", "remove", &ws_path, "--snapshot"]);
    assert!(r.success, "lobe remove --snapshot failed: {}", r.stderr);
    assert!(
        r.stdout.contains("frozen") || r.stdout.contains("real"),
        "remove --snapshot must report frozen links: {}",
        r.stdout
    );

    // The entry is gone from config.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        !v["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "windsurf lobe must be gone from config after remove --snapshot: {}",
        listed.stdout
    );

    // The skill dir is now a real directory, not a symlink.
    assert!(
        skill_link.exists(),
        "skill dir must still exist after remove --snapshot"
    );
    let post_sym_md = std::fs::symlink_metadata(&skill_link).unwrap();
    assert!(
        !post_sym_md.file_type().is_symlink(),
        "remove --snapshot must convert the symlink to a real file/dir"
    );
}

// HARN-13: `introspect` reports a `vanished-lobe` finding when a configured lobe's
// parent dir no longer exists, but does NOT auto-fix it.
#[test]
fn introspect_reports_vanished_lobe() {
    // spec: HARN-13
    let sb = Sandbox::new();
    let proj = sb.base.join("vanished-proj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // Register a lobe and install items so there are manifest links inside it.
    assert!(sb.mind(&["link-project", &proj_str]).success);
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(
        sb.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );

    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let skill_link = proj.join(".windsurf/skills/review");
    assert!(
        std::fs::symlink_metadata(&skill_link).is_ok(),
        "skill link must exist before vanishing the dir"
    );

    // Vanish the project directory.
    std::fs::remove_dir_all(&proj).unwrap();

    // `introspect` (no --fix) must report the vanished-lobe finding without error.
    let r = sb.mind(&["introspect", "--json"]);
    assert!(
        r.success,
        "introspect must succeed even with a vanished lobe: {}",
        r.stderr
    );
    let v = parse_json(&r.stdout);
    let issues = v["issues"].as_array().expect("issues array");
    assert!(
        issues
            .iter()
            .any(|i| i["kind"].as_str() == Some("vanished-lobe")),
        "introspect must report vanished-lobe finding: {}",
        r.stdout
    );
    let vanished = issues
        .iter()
        .find(|i| i["kind"].as_str() == Some("vanished-lobe"))
        .unwrap();
    assert_eq!(
        vanished["target"].as_str(),
        Some(ws_path.as_str()),
        "vanished-lobe target must be the windsurf lobe path"
    );

    // Config must still have the vanished lobe (no --fix, no pruning).
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&listed.stdout);
    assert!(
        lv["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "config must retain the vanished lobe entry until --fix: {}",
        listed.stdout
    );
}

// HARN-13: `introspect --fix` prunes a vanished lobe from config and strips its
// links from the manifest.
#[test]
fn introspect_fix_prunes_vanished_lobe() {
    // spec: HARN-13
    let sb = Sandbox::new();
    let proj = sb.base.join("vanished-fix");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    assert!(sb.mind(&["link-project", &proj_str]).success);
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(
        sb.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );

    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();

    // Confirm the manifest has a link under the windsurf lobe before vanishing.
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    assert!(
        manifest["items"]["skill:review"]["links"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l.as_str().map(|s| s.starts_with(&ws_path)).unwrap_or(false)),
        "manifest must record a link inside the windsurf lobe before fix"
    );

    // Vanish the project directory.
    std::fs::remove_dir_all(&proj).unwrap();

    // `introspect --fix` must prune the config entry and strip the manifest links.
    let r = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(r.success, "introspect --fix must succeed: {}", r.stderr);

    // Config must no longer contain the vanished lobe.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&listed.stdout);
    assert!(
        !lv["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "config must NOT contain the vanished lobe after --fix: {}",
        listed.stdout
    );

    // Manifest must no longer have links under the vanished lobe path.
    let manifest_after: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let links_after = manifest_after["items"]["skill:review"]["links"]
        .as_array()
        .unwrap();
    assert!(
        !links_after
            .iter()
            .any(|l| l.as_str().map(|s| s.starts_with(&ws_path)).unwrap_or(false)),
        "manifest must not retain links under the vanished lobe after --fix: {manifest_after:#?}"
    );
}

// HARN-18: a single `introspect --fix` run that prunes a vanished lobe must not
// ALSO report that same lobe as an outstanding issue: the exit summary counts
// only what remains after the fix pass.
#[test]
fn harn18_fixed_vanished_lobe_is_not_also_an_outstanding_issue() {
    // spec: HARN-18
    let sb = Sandbox::new();
    let proj = sb.base.join("vanished-harn18");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    assert!(sb.mind(&["link-project", &proj_str]).success);
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(
        sb.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );

    // Vanish the project directory so its `.windsurf` lobe becomes unreachable.
    std::fs::remove_dir_all(&proj).unwrap();

    // The JSON `issues` array from THIS SAME run must be empty: the pruned
    // vanished-lobe finding must not survive into the reported issue list.
    let json_run = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(
        json_run.success,
        "introspect --fix failed: {}",
        json_run.stderr
    );
    let v = parse_json(&json_run.stdout);
    let issues = v["issues"].as_array().expect("issues array");
    assert!(
        issues.is_empty(),
        "HARN-18: a vanished lobe pruned in this run must not remain as an \
         outstanding issue: {}",
        json_run.stdout
    );

    // Re-verify with a fresh, equivalent scenario in PLAIN-TEXT mode: the human
    // summary must say "all good" (repaired, not outstanding), never
    // "issue(s) found" for the lobe this same run just pruned.
    let sb2 = Sandbox::new();
    let proj2 = sb2.base.join("vanished-harn18-text");
    std::fs::create_dir_all(&proj2).unwrap();
    let proj2_str = proj2.to_string_lossy().into_owned();
    assert!(sb2.mind(&["link-project", &proj2_str]).success);
    assert!(sb2.mind(&["meld", &sb2.source_spec()]).success);
    assert!(
        sb2.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );
    std::fs::remove_dir_all(&proj2).unwrap();

    let text_run = sb2.mind(&["introspect", "--fix"]);
    assert!(text_run.success, "{}", text_run.stderr);
    assert!(
        text_run
            .stdout
            .contains("pruned vanished lobe(s) from config"),
        "the repair must still be reported: {}",
        text_run.stdout
    );
    assert!(
        !text_run.stdout.contains("issue(s) found"),
        "HARN-18: a fully-repaired run must not report an outstanding issue \
         count: {}",
        text_run.stdout
    );
}

// HARN-5: when a project-scoped preset (windsurf) is detected, `config lobes
// detect` prints guidance to run `mind link-project` but does NOT add a lobe
// (even with --yes). The JSON output includes a `guidance` field.
#[test]
fn detect_project_scoped_preset_prints_guidance_not_add() {
    // spec: HARN-5
    let sb = Sandbox::new();
    let detect_home = sb.base.join("detect-ws");
    // windsurf detection marker is .codeium/windsurf.
    std::fs::create_dir_all(detect_home.join(".codeium/windsurf")).unwrap();
    let detect_str = detect_home.to_string_lossy().into_owned();

    // Non-TTY without --yes: no mutation, guidance printed.
    let r = sb.mind_env(
        &["config", "lobes", "detect"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(r.success, "detect failed: {}", r.stderr);
    assert!(
        r.stdout.contains("link-project"),
        "detect of windsurf must print link-project guidance: {}",
        r.stdout
    );

    // Config must still be empty (no windsurf lobe added).
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let has_windsurf = v["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .any(|l| l["path"].as_str().is_some_and(|p| p.ends_with(".windsurf")));
    assert!(
        !has_windsurf,
        "detect must NOT add a project-scoped windsurf lobe: {}",
        listed.stdout
    );

    // --yes must also NOT add the windsurf lobe (project-scoped).
    let r_yes = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(r_yes.success, "detect --yes failed: {}", r_yes.stderr);
    let listed2 = sb.mind(&["config", "lobes", "list", "--json"]);
    let v2 = parse_json(&listed2.stdout);
    let has_windsurf2 = v2["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .any(|l| l["path"].as_str().is_some_and(|p| p.ends_with(".windsurf")));
    assert!(
        !has_windsurf2,
        "detect --yes must NOT auto-add a project-scoped preset: {}",
        listed2.stdout
    );

    // JSON output must include windsurf in `detected` with scope=project and a
    // non-empty `guidance` array.
    let r_json = sb.mind_env(
        &["config", "lobes", "detect", "--json"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(r_json.success, "detect --json failed: {}", r_json.stderr);
    let jv = parse_json(&r_json.stdout);
    assert!(
        jv["detected"]
            .as_array()
            .unwrap()
            .iter()
            .any(|d| d["preset"] == "windsurf" && d["scope"] == "project"),
        "JSON detected must include windsurf with scope=project: {}",
        r_json.stdout
    );
    assert!(
        jv["guidance"]
            .as_array()
            .map(|a| !a.is_empty())
            .unwrap_or(false),
        "JSON must include a non-empty guidance array for project-scoped presets: {}",
        r_json.stdout
    );
}

// HARN-12: `--snapshot` refuses to clobber a pre-existing FOREIGN target (one mind
// did not place) without `--force`, leaving it intact; with `--force` it overwrites
// the foreign target with the frozen skill copy.
#[test]
fn snapshot_force_overwrites_foreign_target() {
    // spec: HARN-12
    let sb = Sandbox::new();
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let proj = sb.base.join("forcesnap");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // Plant a foreign FILE exactly where the frozen skill dir would land.
    let target = proj.join(".windsurf/skills/review");
    std::fs::create_dir_all(target.parent().unwrap()).unwrap();
    std::fs::write(&target, "foreign content").unwrap();

    // Without --force: the collision is refused and the foreign file is untouched.
    let refused = sb.mind(&["link-project", &proj_str, "--snapshot"]);
    assert!(
        !refused.success,
        "snapshot must refuse a foreign target without --force: stdout={} stderr={}",
        refused.stdout, refused.stderr
    );
    assert_eq!(
        std::fs::read_to_string(&target).unwrap(),
        "foreign content",
        "the foreign file must be left intact when the snapshot is refused"
    );

    // With --force: the frozen skill dir overwrites the foreign file.
    let forced = sb.mind(&["link-project", &proj_str, "--snapshot", "--force"]);
    assert!(
        forced.success,
        "snapshot --force must overwrite the foreign target: {}",
        forced.stderr
    );
    assert!(
        target.join("SKILL.md").is_file(),
        "with --force the frozen skill dir must replace the foreign file: {}",
        forced.stdout
    );
    // And it is a REAL directory, not a symlink (snapshot writes real files).
    let md = std::fs::symlink_metadata(&target).unwrap();
    assert!(
        !md.file_type().is_symlink() && md.file_type().is_dir(),
        "the frozen skill must be a real directory after --force"
    );
}

// HARN-11: re-adding an already-registered lobe is an idempotent no-op. The text
// no-op path ("already configured") is covered elsewhere; this pins the `--json`
// output shape (action=lobe-add, outcome=no-op), and that nothing is duplicated.
#[test]
fn lobe_re_add_json_reports_no_op() {
    // spec: HARN-11
    let sb = Sandbox::new();
    let proj = sb.base.join("reproj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // First add via link-project (windsurf) registers <proj>/.windsurf.
    assert!(
        sb.mind(&["link-project", &proj_str]).success,
        "first link-project must succeed"
    );

    // Re-add the SAME lobe through the equivalent `config lobes add ... --preset
    // windsurf --json`: it must report a no-op, not a second entry.
    let second = sb.mind(&[
        "config", "lobes", "add", &proj_str, "--preset", "windsurf", "--json",
    ]);
    assert!(
        second.success,
        "re-adding a registered lobe must succeed: {}",
        second.stderr
    );
    let v = parse_json(&second.stdout);
    assert_eq!(v["action"], "lobe-add", "{}", second.stdout);
    assert_eq!(
        v["outcome"], "no-op",
        "re-adding an already-registered lobe must be a no-op: {}",
        second.stdout
    );

    // The lobe list still shows exactly one windsurf entry.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&listed.stdout);
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let count = lv["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|l| l["path"].as_str() == Some(ws_path.as_str()))
        .count();
    assert_eq!(
        count, 1,
        "no-op re-add must not duplicate the lobe: {}",
        listed.stdout
    );
}

// HARN-9: `link-project` as the FIRST explicit lobe add on an otherwise-default
// (implicit ~/.claude) config auto-preserves claude_home, so a later install still
// reaches ~/.claude in addition to the new project lobe.
#[test]
fn link_project_first_add_preserves_claude_home() {
    // spec: HARN-9
    let sb = Sandbox::new();
    // No write_config: the lobes config is the implicit claude_home default.
    let proj = sb.base.join("firstlink");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    assert!(
        sb.mind(&["link-project", &proj_str]).success,
        "first link-project must succeed"
    );
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // The skill must reach BOTH claude_home (auto-preserved) and the project lobe.
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "claude_home must be preserved as an explicit lobe after the first link-project"
    );
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/skills/review")).is_ok(),
        "the skill must reach the project windsurf lobe"
    );
}

// HARN-10: the windsurf skill-only `kinds` filter rejects BOTH an agent and a tool
// (existing tests only checked a rule). Installing a skill + agent + tool must
// materialize ONLY the skill into the windsurf project lobe.
#[test]
fn windsurf_skill_only_rejects_agent_and_tool() {
    // spec: HARN-10
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let base = std::env::temp_dir().join(format!("mind-ws-kinds-{}-{n}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    let source = base.join("agents");
    write(
        &source.join("skills/review/SKILL.md"),
        "---\nname: review\ndescription: review\n---\n# review\n",
    );
    write(
        &source.join("helper.md"),
        "---\nname: helper\ndescription: an agent\n---\n# helper agent\n",
    );
    write(&source.join("toolkit/run.sh"), "#!/bin/sh\necho hi\n");
    write(
        &source.join("mind.toml"),
        "[source]\ndescription = \"multi-kind source\"\n\n\
         [[items]]\nkind = \"skill\"\nname = \"review\"\npath = \"skills/review\"\n\n\
         [[items]]\nkind = \"agent\"\nname = \"helper\"\npath = \"helper.md\"\n\n\
         [[items]]\nkind = \"tool\"\nname = \"toolkit\"\npath = \"toolkit\"\nlink = \"tools/toolkit\"\n",
    );
    git(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
    git(&source, &["config", "user.email", "t@t"]);
    git(&source, &["config", "user.name", "t"]);
    git(&source, &["add", "-A"]);
    git(&source, &["commit", "-qm", "initial"]);

    let mind_home = base.join("mind");
    let claude_home = base.join("claude");
    std::fs::create_dir_all(&mind_home).unwrap();
    let proj = base.join("proj");
    std::fs::create_dir_all(&proj).unwrap();

    let run = |args: &[&str]| -> Run {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_mind"));
        cmd.args(args)
            .env("MIND_HOME", &mind_home)
            .env("CLAUDE_HOME", &claude_home)
            .env_remove("MIND_AGENT_HOMES")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let out = cmd.output().expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    };

    // Register the windsurf project lobe, meld, then learn all three kinds.
    assert!(run(&["link-project", proj.to_str().unwrap()]).success);
    assert!(run(&["meld", source.to_str().unwrap()]).success);
    assert!(run(&["learn", "review"]).success, "learn skill");
    let la = run(&["learn", "helper"]);
    assert!(la.success, "learn agent failed: {}", la.stderr);
    let lt = run(&["learn", "toolkit"]);
    assert!(lt.success, "learn tool failed: {}", lt.stderr);

    // Only the skill lands in the windsurf lobe.
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/skills/review")).is_ok(),
        "skill must land in the windsurf lobe"
    );
    // The agent must NOT (skill-only lobe rejects agents).
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/agents")).is_err()
            && std::fs::symlink_metadata(proj.join(".windsurf/agents/helper.md")).is_err(),
        "an agent must NOT land in a skill-only windsurf lobe (HARN-10)"
    );
    // The tool (even with an explicit link) must NOT.
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/tools")).is_err()
            && std::fs::symlink_metadata(proj.join(".windsurf/tools/toolkit")).is_err(),
        "a tool must NOT land in a skill-only windsurf lobe (HARN-10)"
    );

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

// CLI-198: `link-project --json` (managed, non-snapshot) emits a well-formed
// lobe-add mutation result and does NOT leak the prose gitignore note into stdout.
#[test]
fn link_project_json_reports_mutation() {
    // spec: CLI-198
    let sb = Sandbox::new();
    let proj = sb.base.join("jsonproj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    let r = sb.mind(&["link-project", &proj_str, "--json"]);
    assert!(r.success, "link-project --json failed: {}", r.stderr);
    let v = parse_json(&r.stdout);
    assert_eq!(v["action"], "lobe-add", "{}", r.stdout);
    assert_eq!(v["outcome"], "added", "{}", r.stdout);
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    assert_eq!(
        v["target"].as_str(),
        Some(ws_path.as_str()),
        "target must be the windsurf lobe path: {}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("gitignore"),
        "JSON mode must not emit the prose gitignore note: {}",
        r.stdout
    );
}

// HARN-14: `--snapshot --json` emits a machine-readable MutationResult (action
// lobe-add, outcome snapshot, count + installed keys), freezes the files, and
// registers no managed lobe.
#[test]
fn snapshot_json_reports_frozen_result() {
    // spec: HARN-14
    let sb = Sandbox::new();
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let proj = sb.base.join("snapjson");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    let r = sb.mind(&["link-project", &proj_str, "--snapshot", "--json"]);
    assert!(r.success, "snapshot --json failed: {}", r.stderr);

    // The JSON is a well-formed snapshot MutationResult.
    let v = parse_json(&r.stdout);
    assert_eq!(v["schema"], 1, "schema version: {}", r.stdout);
    assert_eq!(v["action"], "lobe-add", "action: {}", r.stdout);
    assert_eq!(v["outcome"], "snapshot", "outcome: {}", r.stdout);
    assert_eq!(v["count"], 1, "one item frozen: {}", r.stdout);
    let installed: Vec<&str> = v["installed"]
        .as_array()
        .expect("installed array")
        .iter()
        .map(|k| k.as_str().unwrap())
        .collect();
    assert_eq!(
        installed,
        vec!["skill:review"],
        "installed keys: {}",
        r.stdout
    );
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    assert_eq!(
        v["target"], ws_path,
        "target is the lobe path: {}",
        r.stdout
    );

    // The freeze actually happened: a real (non-symlink) skill dir exists.
    let skill_dir = proj.join(".windsurf/skills/review");
    let md = std::fs::symlink_metadata(&skill_dir).expect("frozen skill dir must exist");
    assert!(
        !md.file_type().is_symlink() && md.file_type().is_dir(),
        "snapshot must write a real dir under --json too"
    );

    // No managed lobe registered (snapshot never writes a config entry).
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let lv = parse_json(&listed.stdout);
    assert!(
        !lv["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(ws_path.as_str())),
        "snapshot must not register a managed lobe even under --json: {}",
        listed.stdout
    );
}

// HARN-14: `--snapshot --json` with nothing installed reports outcome `no-op`,
// count 0, and an empty installed list.
#[test]
fn snapshot_json_no_items_reports_no_op() {
    // spec: HARN-14
    let sb = Sandbox::new();
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let proj = sb.base.join("emptysnap");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    let r = sb.mind(&["link-project", &proj_str, "--snapshot", "--json"]);
    assert!(r.success, "empty snapshot --json failed: {}", r.stderr);
    let v = parse_json(&r.stdout);
    assert_eq!(v["outcome"], "no-op", "outcome: {}", r.stdout);
    assert_eq!(v["count"], 0, "count zero: {}", r.stdout);
    assert!(
        v["installed"].as_array().is_none_or(|a| a.is_empty()),
        "installed empty: {}",
        r.stdout
    );
}

// HARN-14: `config lobes remove --snapshot --json` reports outcome `detached`
// with the frozen link count; a plain remove stays `removed` with no count.
#[test]
fn remove_snapshot_json_reports_detached_count() {
    // spec: HARN-14
    let sb = Sandbox::new();
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let proj = sb.base.join("detachjson");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();
    assert!(
        sb.mind(&["link-project", &proj_str, "--yes"]).success,
        "managed link-project"
    );
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();

    let r = sb.mind(&[
        "config",
        "lobes",
        "remove",
        &ws_path,
        "--snapshot",
        "--json",
    ]);
    assert!(r.success, "remove --snapshot --json failed: {}", r.stderr);
    let v = parse_json(&r.stdout);
    assert_eq!(v["action"], "lobe-remove", "action: {}", r.stdout);
    assert_eq!(v["outcome"], "detached", "outcome: {}", r.stdout);
    assert_eq!(v["count"], 1, "one link frozen: {}", r.stdout);
}

// HARN-12: `--snapshot` when nothing is installed is a no-op note, not an error,
// and it creates no skill directory.
#[test]
fn snapshot_no_items_is_noop_not_error() {
    // spec: HARN-12
    let sb = Sandbox::new();
    let proj = sb.base.join("emptysnap");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    // Nothing has been learned; snapshot must succeed with a no-op note.
    let r = sb.mind(&["link-project", &proj_str, "--snapshot"]);
    assert!(
        r.success,
        "snapshot with nothing installed must succeed: {}",
        r.stderr
    );
    assert!(
        r.stdout.contains("no installed items"),
        "empty snapshot must print the no-items note: {}",
        r.stdout
    );
    assert!(
        std::fs::symlink_metadata(proj.join(".windsurf/skills")).is_err(),
        "no skills dir must be created when there is nothing to snapshot"
    );
}

// CLI-198: running `link-project <same dir>` twice is idempotent: the second run
// succeeds, reports "already configured", and does not duplicate the config entry.
#[test]
fn link_project_twice_is_idempotent() {
    // spec: CLI-198
    let sb = Sandbox::new();
    let proj = sb.base.join("twiceproj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    assert!(
        sb.mind(&["link-project", &proj_str]).success,
        "first link-project must succeed"
    );
    let second = sb.mind(&["link-project", &proj_str]);
    assert!(
        second.success,
        "second link-project (same dir) must succeed: {}",
        second.stderr
    );
    assert!(
        second.stdout.contains("already configured"),
        "second link-project must report the lobe already configured: {}",
        second.stdout
    );

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let count = v["lobes"]
        .as_array()
        .unwrap()
        .iter()
        .filter(|l| l["path"].as_str() == Some(ws_path.as_str()))
        .count();
    assert_eq!(
        count, 1,
        "the windsurf lobe must appear exactly once after two link-projects: {}",
        listed.stdout
    );
}

// STO-16: a RELATIVE project base given to `config lobes add ... --preset windsurf`
// is resolved to an absolute path in the saved config (resolved against cwd).
#[test]
fn lobe_add_relative_base_resolves_absolute() {
    // spec: STO-16
    let sb = Sandbox::new();
    let proj = sb.base.join("relproj");
    std::fs::create_dir_all(&proj).unwrap();

    // Run with cwd = sb.base and a RELATIVE base "relproj".
    let r = sb.run_cwd(
        &["config", "lobes", "add", "relproj", "--preset", "windsurf"],
        &[],
        Some(&sb.base),
    );
    assert!(r.success, "relative-base add failed: {}", r.stderr);

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    let has_abs = v["lobes"].as_array().unwrap().iter().any(|l| {
        l["path"]
            .as_str()
            .map(|p| p.starts_with('/') && p.ends_with("relproj/.windsurf"))
            .unwrap_or(false)
    });
    assert!(
        has_abs,
        "a relative base must resolve to an absolute windsurf lobe path (STO-16): {}",
        listed.stdout
    );
}

// HARN-12: `config lobes remove --snapshot` on a lobe holding MULTIPLE items freezes
// every managed link to a real file AND leaves the ~/.mind store copies intact (the
// freeze copies FROM the store, it must not consume it).
#[test]
fn lobe_remove_snapshot_multiple_items_keeps_store() {
    // spec: HARN-12
    let n = COUNTER.fetch_add(1, Ordering::SeqCst);
    let base = std::env::temp_dir().join(format!("mind-rmsnap-multi-{}-{n}", std::process::id()));
    let _ = std::fs::remove_dir_all(&base);
    let source = base.join("agents");
    write(
        &source.join("skills/one/SKILL.md"),
        "---\nname: one\ndescription: skill one\n---\n# one\n",
    );
    write(
        &source.join("skills/two/SKILL.md"),
        "---\nname: two\ndescription: skill two\n---\n# two\n",
    );
    git(&source, &["-c", "init.defaultBranch=main", "init", "-q"]);
    git(&source, &["config", "user.email", "t@t"]);
    git(&source, &["config", "user.name", "t"]);
    git(&source, &["add", "-A"]);
    git(&source, &["commit", "-qm", "initial"]);

    let mind_home = base.join("mind");
    let claude_home = base.join("claude");
    std::fs::create_dir_all(&mind_home).unwrap();
    let proj = base.join("proj");
    std::fs::create_dir_all(&proj).unwrap();

    let run = |args: &[&str]| -> Run {
        let mut cmd = Command::new(env!("CARGO_BIN_EXE_mind"));
        cmd.args(args)
            .env("MIND_HOME", &mind_home)
            .env("CLAUDE_HOME", &claude_home)
            .env_remove("MIND_AGENT_HOMES")
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let out = cmd.output().expect("run mind");
        Run {
            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
            success: out.status.success(),
        }
    };

    assert!(run(&["link-project", proj.to_str().unwrap()]).success);
    assert!(run(&["meld", source.to_str().unwrap()]).success);
    assert!(run(&["learn", "one"]).success, "learn one");
    assert!(run(&["learn", "two"]).success, "learn two");

    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();
    let link_one = proj.join(".windsurf/skills/one");
    let link_two = proj.join(".windsurf/skills/two");
    assert!(
        std::fs::symlink_metadata(&link_one)
            .unwrap()
            .file_type()
            .is_symlink()
            && std::fs::symlink_metadata(&link_two)
                .unwrap()
                .file_type()
                .is_symlink(),
        "both skills must be symlinked into the windsurf lobe before remove"
    );

    // Capture the store paths so we can assert they survive the freeze.
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let store_one = manifest["items"]["skill:one"]["store"]
        .as_str()
        .unwrap()
        .to_string();
    let store_two = manifest["items"]["skill:two"]["store"]
        .as_str()
        .unwrap()
        .to_string();

    let r = run(&["config", "lobes", "remove", &ws_path, "--snapshot"]);
    assert!(r.success, "remove --snapshot failed: {}", r.stderr);

    // Both links are now REAL directories, not symlinks.
    for link in [&link_one, &link_two] {
        let md = std::fs::symlink_metadata(link).unwrap();
        assert!(
            !md.file_type().is_symlink() && md.file_type().is_dir(),
            "remove --snapshot must convert {link:?} to a real dir"
        );
        assert!(
            link.join("SKILL.md").is_file(),
            "the frozen copy at {link:?} must contain the skill file"
        );
    }

    // The store copies must remain intact (the freeze copies FROM the store).
    assert!(
        mind_home.join(&store_one).join("SKILL.md").is_file(),
        "store copy for skill:one must survive the freeze"
    );
    assert!(
        mind_home.join(&store_two).join("SKILL.md").is_file(),
        "store copy for skill:two must survive the freeze"
    );

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

// ---------------------------------------------------------------------------
// Independent certification of HARN-15..18 (commit 34ff13d). The tests below
// target the branches the implementation's own tests do not discriminate.
// ---------------------------------------------------------------------------

// HARN-15: the lobe directory is created by the ADD itself, not as a side effect
// of the HARN-17 backfill.
//
// This is the discriminating case for the mkdir_p: with items installed, the
// backfill's `ensure_link` does `mkdir_p(link.parent())`, which creates the lobe
// dir on its way to `<lobe>/skills/<name>`. So a test that installs an item
// first cannot tell "the add created the dir" from "the backfill created it",
// and stays green even if the HARN-15 mkdir_p is deleted. With an EMPTY manifest
// the backfill returns immediately and the only thing that can create the
// directory is the HARN-15 mkdir_p.
#[test]
fn harn15_lobe_add_creates_the_dir_with_nothing_installed() {
    // spec: HARN-15
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));

    let new_lobe = sb.base.join("empty-manifest-lobe");
    assert!(
        std::fs::symlink_metadata(&new_lobe).is_err(),
        "sanity: the lobe path must not exist before the add"
    );
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();

    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(added.success, "lobe add failed: {}", added.stderr);

    assert!(
        new_lobe.is_dir(),
        "HARN-15: registering a lobe must create its directory even when there \
         is nothing to backfill (nothing else can create it): {}",
        added.stdout
    );

    // And the freshly created lobe must be reachable, so a following
    // `introspect --fix` does not prune it as vanished (HARN-13).
    let intro = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(intro.success, "introspect --fix failed: {}", intro.stderr);
    let iv = parse_json(&intro.stdout);
    assert!(
        !iv["issues"]
            .as_array()
            .unwrap()
            .iter()
            .any(|i| i["kind"].as_str() == Some("vanished-lobe")),
        "a lobe created at add time must not be reported vanished: {}",
        intro.stdout
    );
    assert!(
        new_lobe.is_dir(),
        "the lobe dir must survive an `introspect --fix` pass"
    );
}

// HARN-15 boundary: creating the RESOLVED lobe path must not relax the
// LobeBaseMissing guard (HARN-10) on an EXPLICIT base. A mistyped base is still
// refused, and the refusal creates nothing at all: neither the base, nor the
// preset/subdir path under it, nor a config entry.
#[test]
fn harn15_missing_explicit_base_is_refused_and_creates_nothing() {
    // spec: HARN-15
    // spec: HARN-10
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));

    let missing = sb.base.join("no-such-base");
    let missing_str = missing.to_string_lossy().into_owned();

    // Three entry points share `resolve_lobe`; all three must refuse.
    for args in [
        vec![
            "config",
            "lobes",
            "add",
            &missing_str,
            "--preset",
            "windsurf",
        ],
        vec![
            "config",
            "lobes",
            "add",
            &missing_str,
            "--subdir",
            ".cursor",
        ],
        vec!["link-project", &missing_str],
    ] {
        let r = sb.mind(&args);
        assert!(!r.success, "a missing explicit base must fail: {args:?}");
        assert!(
            std::fs::symlink_metadata(&missing).is_err(),
            "HARN-15 must not create a mistyped BASE directory ({args:?}): {}",
            r.stderr
        );
    }

    // Nothing was registered either.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        !v["lobes"].as_array().unwrap().iter().any(|l| l["path"]
            .as_str()
            .is_some_and(|p| p.contains("no-such-base"))),
        "a refused add must leave no config entry behind: {}",
        listed.stdout
    );
}

// HARN-15 is scoped to the MANAGED path: `--snapshot` registers no lobe, so it
// must not create the target directory either. A snapshot with nothing to freeze
// leaves the filesystem exactly as it found it.
#[test]
fn harn15_snapshot_add_creates_no_lobe_dir_and_no_config_entry() {
    // spec: HARN-15
    // spec: HARN-12
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));

    let snap = sb.base.join("snapshot-target");
    let snap_str = snap.to_string_lossy().into_owned();

    let r = sb.mind(&["config", "lobes", "add", &snap_str, "--snapshot"]);
    assert!(r.success, "snapshot add failed: {}", r.stderr);
    assert!(
        std::fs::symlink_metadata(&snap).is_err(),
        "HARN-15's mkdir is confined to the managed path; --snapshot must not \
         create the target dir: {}",
        r.stdout
    );

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        !v["lobes"].as_array().unwrap().iter().any(|l| l["path"]
            .as_str()
            .is_some_and(|p| p.contains("snapshot-target"))),
        "--snapshot must register no config entry: {}",
        listed.stdout
    );
}

// HARN-16: the note is deduplicated PER LOBE PATH, not globally. Two unreachable
// lobes must produce two notes (one each), and each must name BOTH remedies. A
// dedup keyed on a single bool would print one note and swallow the second
// lobe's; the existing single-lobe test cannot see that.
#[test]
fn harn16_note_is_per_lobe_and_names_both_remedies() {
    // spec: HARN-16
    let sb = Sandbox::new();
    let gone_a = sb.base.join("gone-a").join(".windsurf");
    let gone_b = sb.base.join("gone-b").join(".windsurf");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        gone_a.display(),
        gone_b.display()
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    // Two items in one invocation: 4 (item, lobe) skips, but only 2 notes.
    let learn = sb.mind(&["learn", "*"]);
    assert!(learn.success, "learn failed: {}", learn.stderr);

    assert_eq!(
        learn.stdout.matches("is unreachable").count(),
        2,
        "HARN-16: one note per unreachable LOBE (2 lobes x 2 items = 2 notes): {}",
        learn.stdout
    );
    for lobe in [&gone_a, &gone_b] {
        let s = lobe.to_string_lossy().into_owned();
        assert_eq!(
            learn
                .stdout
                .matches(&format!("lobe '{s}' is unreachable"))
                .count(),
            1,
            "each unreachable lobe must be named exactly once: {}",
            learn.stdout
        );
    }
    assert!(
        learn.stdout.contains("create the missing directory"),
        "the note must name the create-the-directory remedy: {}",
        learn.stdout
    );
    assert!(
        learn.stdout.contains("config lobes remove"),
        "the note must name the drop-the-lobe remedy: {}",
        learn.stdout
    );

    // Nothing was linked into either unreachable lobe, and the manifest records
    // no link there (the note is advisory, not a repair).
    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let a = gone_a.to_string_lossy().into_owned();
    assert!(
        !manifest["items"]["skill:review"]["links"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l.as_str().is_some_and(|s| s.starts_with(&a))),
        "an unreachable lobe must contribute no manifest link: {manifest:#?}"
    );
}

// HARN-16 x a kinds filter: a lobe that does not admit the item's kind is
// filtered out BEFORE the reachability check, so installing a rule must not
// warn about an unreachable SKILL-ONLY lobe (that lobe would never have
// received the rule even if it were reachable).
#[test]
fn harn16_no_note_for_an_unreachable_lobe_that_excludes_the_kind() {
    // spec: HARN-16
    let sb = Sandbox::new();
    let gone = sb.base.join("gone-skillonly").join(".windsurf");
    sb.write_config(&format!(
        "lobes = [\"{}\", {{ path = \"{}\", kinds = [\"skill\"] }}]\n",
        sb.claude_home.display(),
        gone.display()
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    let learn = sb.mind(&["learn", "style"]); // a RULE
    assert!(learn.success, "learn rule failed: {}", learn.stderr);
    assert!(
        !learn.stdout.contains("is unreachable"),
        "a skill-only lobe is excluded by the kinds filter before the \
         reachability check, so installing a rule must not warn: {}",
        learn.stdout
    );
}

// HARN-17: `--force` is the ONLY way past the foreign-target guard, and it does
// get past it. Without --force the same command leaves the file alone (covered
// by harn17_backfill_reports_foreign_target_without_clobbering); with --force the
// target becomes mind's symlink and the manifest records it.
#[test]
fn harn17_force_overrides_the_foreign_target_guard() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("forced-lobe");
    std::fs::create_dir_all(new_lobe.join("skills")).unwrap();
    let foreign_target = new_lobe.join("skills/review");
    std::fs::write(&foreign_target, b"not managed by mind").unwrap();

    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", "--force", &new_lobe_str]);
    assert!(added.success, "forced lobe add failed: {}", added.stderr);
    assert!(
        !added.stdout.contains("could not link"),
        "--force must not report a blocked target: {}",
        added.stdout
    );

    let md = std::fs::symlink_metadata(&foreign_target).unwrap();
    assert!(
        md.file_type().is_symlink(),
        "--force must replace the foreign file with mind's symlink"
    );
    let target = std::fs::read_link(&foreign_target).unwrap();
    assert!(
        target.starts_with(sb.mind_home.join("store")),
        "the forced link must point into the store: {target:?}"
    );

    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let expected = foreign_target.to_string_lossy().into_owned();
    assert!(
        manifest["items"]["skill:review"]["links"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l.as_str() == Some(expected.as_str())),
        "a forced link must be recorded in the manifest: {manifest:#?}"
    );
}

// HARN-17: a blocked target must not corrupt the manifest and must not abort the
// rest of the backfill. One item is blocked by a foreign file; the other item
// must still be linked, the blocked link must NOT be recorded (recording it
// would make `forget` delete the user's file and `introspect` believe the item
// is covered), and the pre-existing link must survive.
#[test]
fn harn17_blocked_backfill_keeps_manifest_honest_and_continues() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");
    assert!(sb.mind(&["learn", "style"]).success, "learn rule");

    let new_lobe = sb.base.join("partial-lobe");
    std::fs::create_dir_all(new_lobe.join("skills")).unwrap();
    let foreign_target = new_lobe.join("skills/review");
    let foreign_content = b"user content, not mind's";
    std::fs::write(&foreign_target, foreign_content).unwrap();

    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(
        added.success,
        "a blocked target is a warning, not a failure: {}",
        added.stderr
    );

    // The foreign file is untouched.
    assert_eq!(
        std::fs::read(&foreign_target).unwrap(),
        foreign_content,
        "the foreign file's content must be untouched"
    );

    // The OTHER item still landed: one blocked target does not abort the pass.
    let rule_link = new_lobe.join("rules/style.md");
    assert!(
        std::fs::symlink_metadata(&rule_link).is_ok(),
        "a blocked target for one item must not stop the next item from linking: {}",
        added.stdout
    );

    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let blocked = foreign_target.to_string_lossy().into_owned();
    let skill_links: Vec<&str> = manifest["items"]["skill:review"]["links"]
        .as_array()
        .unwrap()
        .iter()
        .map(|l| l.as_str().unwrap())
        .collect();
    assert!(
        !skill_links.contains(&blocked.as_str()),
        "a link that was NOT created must never be recorded: {skill_links:?}"
    );
    assert!(
        skill_links
            .iter()
            .any(|l| l.starts_with(&sb.claude_home.to_string_lossy().into_owned())),
        "the pre-existing claude_home link must survive the partial backfill: {skill_links:?}"
    );
    let rule_links: Vec<&str> = manifest["items"]["rule:style"]["links"]
        .as_array()
        .unwrap()
        .iter()
        .map(|l| l.as_str().unwrap())
        .collect();
    let rule_link_str = rule_link.to_string_lossy().into_owned();
    assert!(
        rule_links.contains(&rule_link_str.as_str()),
        "the link that WAS created must be recorded: {rule_links:?}"
    );

    // The gap is visible to introspect (it is a real missing-lobe-link), and a
    // following `introspect --fix` still refuses to clobber the foreign file.
    let intro = sb.mind(&["introspect", "--json"]);
    let iv = parse_json(&intro.stdout);
    assert!(
        iv["issues"]
            .as_array()
            .unwrap()
            .iter()
            .any(|i| i["kind"].as_str() == Some("missing-lobe-link")
                && i["target"].as_str() == Some("skill:review")),
        "the blocked link must surface as a missing-lobe-link finding: {}",
        intro.stdout
    );
    let fixed = sb.mind(&["introspect", "--fix"]);
    assert!(fixed.success, "introspect --fix failed: {}", fixed.stderr);
    assert_eq!(
        std::fs::read(&foreign_target).unwrap(),
        foreign_content,
        "`introspect --fix` has no --force, so it must not clobber the file either"
    );
}

// HARN-17: a foreign SYMLINK (pointing outside the store) is guarded exactly like
// a regular file. `ensure_unoccupied` treats "ours" as "a symlink into the store
// root", so a symlink to anywhere else is the user's and must survive.
#[test]
fn harn17_foreign_symlink_at_target_is_not_followed_or_replaced() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let elsewhere = sb.base.join("user-owned-review");
    std::fs::create_dir_all(&elsewhere).unwrap();
    let new_lobe = sb.base.join("symlinked-lobe");
    std::fs::create_dir_all(new_lobe.join("skills")).unwrap();
    let target = new_lobe.join("skills/review");
    std::os::unix::fs::symlink(&elsewhere, &target).unwrap();

    let new_lobe_str = new_lobe.to_string_lossy().into_owned();
    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(added.success, "lobe add failed: {}", added.stderr);

    assert_eq!(
        std::fs::read_link(&target).unwrap(),
        elsewhere,
        "a symlink that does not point into the store is the user's and must \
         be left pointing where it pointed: {}",
        added.stdout
    );
    assert!(
        added.stdout.contains("--force"),
        "the blocked target must be reported with the --force remedy: {}",
        added.stdout
    );
}

// HARN-17 at the `config lobes detect` call site, which has no `--force` to
// plumb and passes `false`: a detected lobe whose target is already occupied by
// a foreign file must be reported, never clobbered. `detect --yes` is the one
// backfill entry point a user can trigger without naming a path, so a clobber
// here would be the least expected.
#[test]
fn harn17_detect_backfill_does_not_clobber_a_foreign_target() {
    // spec: HARN-17
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    // A detection base with a `.gemini` marker, and a foreign file exactly where
    // the gemini lobe would link the installed skill.
    let detect_home = sb.base.join("detect-foreign");
    let lobe = detect_home.join(".gemini/config");
    std::fs::create_dir_all(lobe.join("skills")).unwrap();
    let foreign_target = lobe.join("skills/review");
    let foreign_content = b"user content in the gemini home";
    std::fs::write(&foreign_target, foreign_content).unwrap();

    let detect_str = detect_home.to_string_lossy().into_owned();
    let r = sb.mind_env(
        &["config", "lobes", "detect", "--yes"],
        &[("MIND_DETECT_HOME", &detect_str)],
    );
    assert!(r.success, "detect --yes failed: {}", r.stderr);

    let md = std::fs::symlink_metadata(&foreign_target).unwrap();
    assert!(
        !md.file_type().is_symlink(),
        "detect's backfill must not turn a foreign file into a symlink"
    );
    assert_eq!(
        std::fs::read(&foreign_target).unwrap(),
        foreign_content,
        "detect's backfill must leave foreign content untouched"
    );
    assert!(
        r.stdout.contains("--force"),
        "the blocked target must be reported with the --force remedy: {}",
        r.stdout
    );

    let manifest: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(sb.mind_home.join("manifest.json")).unwrap())
            .unwrap();
    let blocked = foreign_target.to_string_lossy().into_owned();
    assert!(
        !manifest["items"]["skill:review"]["links"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l.as_str() == Some(blocked.as_str())),
        "a link that was not created must not be recorded: {manifest:#?}"
    );
}

// HARN-15 failure mode: the lobe path already exists as a FILE, so the mkdir_p
// cannot succeed. The add must fail cleanly and BEFORE the config is written --
// the mkdir_p runs ahead of `cfg.save`, so a half-registered lobe pointing at a
// file can never be persisted -- and the user's file must be left alone.
#[test]
fn harn15_lobe_path_occupied_by_a_file_fails_without_registering() {
    // spec: HARN-15
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));

    let occupied = sb.base.join("a-file-not-a-lobe");
    std::fs::write(&occupied, b"i am a file").unwrap();
    let occupied_str = occupied.to_string_lossy().into_owned();

    let r = sb.mind(&["config", "lobes", "add", &occupied_str]);
    assert!(
        !r.success,
        "a lobe path occupied by a file must fail, not silently register: {}",
        r.stdout
    );
    assert_eq!(
        std::fs::read(&occupied).unwrap(),
        b"i am a file",
        "the user's file must be untouched"
    );

    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        !v["lobes"]
            .as_array()
            .unwrap()
            .iter()
            .any(|l| l["path"].as_str() == Some(occupied_str.as_str())),
        "a failed mkdir must leave no config entry: {}",
        listed.stdout
    );
}

// HARN-17: the backfill has no interactive branch left at all.
//
// The TTY arm of HARN-17 ("an interactive TTY ... never prompts") cannot be
// driven from an integration test: `hook::is_tty()` reads
// `std::io::stdin().is_terminal()` and has no env seam, and the test harness
// gives the child a pipe. What CAN be asserted is the structural fact that
// makes all three invocation modes identical: `backfill_new_lobes` contains no
// TTY check, no confirmation prompt, and no `introspect --fix` deferral, so
// there is no branch for a terminal to select. Re-introducing any of them fails
// this test.
#[test]
fn harn17_backfill_has_no_interactive_or_deferral_branch() {
    // spec: HARN-17
    let src = std::fs::read_to_string(
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src/commands.rs"),
    )
    .expect("read src/commands.rs");
    let start = src
        .find("fn backfill_new_lobes(")
        .expect("backfill_new_lobes must exist in src/commands.rs");
    let body = &src[start..];
    let end = body.find("\n}\n").expect("end of backfill_new_lobes");
    let body = &body[..end];
    // Anchor: prove the slice really is the function body, so the negative
    // assertions below cannot pass vacuously on an empty or mis-sliced range.
    assert!(
        body.contains("link_into_new_lobes"),
        "the sliced body must be backfill_new_lobes itself:\n{body}"
    );

    for forbidden in [
        "is_tty",
        "confirm_default_yes",
        "confirm(",
        "introspect --fix",
    ] {
        assert!(
            !body.contains(forbidden),
            "HARN-17: the backfill must be unconditional in every mode, but its \
             body mentions `{forbidden}`:\n{body}"
        );
    }
}

// HARN-18: dropping the repaired finding must drop ONLY that finding. The
// implementation's own test asserts an empty issue list on an otherwise-clean
// run, which a blanket `issues.clear()` regression would also satisfy. Here a
// second, genuinely unrepaired issue is present: it must survive, and the
// vanished-lobe finding must not.
#[test]
fn harn18_repaired_finding_is_dropped_without_hiding_the_rest() {
    // spec: HARN-18
    let sb = Sandbox::new();
    let proj = sb.base.join("harn18-mixed");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    assert!(sb.mind(&["link-project", &proj_str]).success);
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(
        sb.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );

    let ws_path = proj.join(".windsurf").to_string_lossy().into_owned();

    // Issue 1 (repairable in this run): the project directory vanishes.
    std::fs::remove_dir_all(&proj).unwrap();
    // Issue 2, raised BEFORE the HARN-18 filter runs (a broken mind.toml makes
    // the source unscannable): this is the finding a blanket "clear everything"
    // regression would swallow, since the filter sits between it and the rest.
    std::fs::write(sb.source.join("mind.toml"), "this is not = = valid toml\n").unwrap();
    // Issue 3, raised AFTER the filter (the installed item drifts from its
    // source), which `introspect --fix` reports but never silently upgrades.
    std::fs::write(
        sb.source.join("skills/review/SKILL.md"),
        "---\nname: review\ndescription: Review the diff for bugs\n---\n# review skill (edited)\n",
    )
    .unwrap();

    let r = sb.mind(&["introspect", "--fix", "--json"]);
    assert!(r.success, "introspect --fix failed: {}", r.stderr);
    let v = parse_json(&r.stdout);
    let issues = v["issues"].as_array().expect("issues array");

    assert!(
        !issues
            .iter()
            .any(|i| i["kind"].as_str() == Some("vanished-lobe")
                && i["target"].as_str() == Some(ws_path.as_str())),
        "HARN-18: the lobe pruned in this run must not also be reported: {}",
        r.stdout
    );
    assert!(
        issues
            .iter()
            .any(|i| i["kind"].as_str() == Some("source-scan-failed")),
        "HARN-18 drops only the REPAIRED finding; a finding raised BEFORE the \
         filter must survive it: {}",
        r.stdout
    );

    // The human summary counts exactly the surviving issues, and still reports
    // the repair.
    let sb2 = Sandbox::new();
    let proj2 = sb2.base.join("harn18-mixed-text");
    std::fs::create_dir_all(&proj2).unwrap();
    let proj2_str = proj2.to_string_lossy().into_owned();
    assert!(sb2.mind(&["link-project", &proj2_str]).success);
    assert!(sb2.mind(&["meld", &sb2.source_spec()]).success);
    assert!(
        sb2.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );
    std::fs::remove_dir_all(&proj2).unwrap();
    std::fs::write(sb2.source.join("mind.toml"), "this is not = = valid toml\n").unwrap();

    let text = sb2.mind(&["introspect", "--fix"]);
    assert!(text.success, "{}", text.stderr);
    assert!(
        text.stdout.contains("pruned vanished lobe(s) from config"),
        "the repair must still be reported: {}",
        text.stdout
    );
    assert!(
        text.stdout.contains("issue(s) found"),
        "a run with a surviving issue must still report a count: {}",
        text.stdout
    );
    assert!(
        !text.stdout.contains("parent dir is gone"),
        "the repaired vanished-lobe line must not be printed as outstanding: {}",
        text.stdout
    );
}

// HARN-18 boundary: without `--fix` nothing is repaired, so nothing may be
// dropped. The vanished-lobe finding must still be reported AND counted. This
// pins that the HARN-18 filter is gated on the repair actually happening; a
// regression that filtered unconditionally would silently hide a real problem.
#[test]
fn harn18_without_fix_the_vanished_lobe_is_still_counted() {
    // spec: HARN-18
    let sb = Sandbox::new();
    let proj = sb.base.join("harn18-nofix");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    assert!(sb.mind(&["link-project", &proj_str]).success);
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(
        sb.mind(&["learn", "review", "--yes"]).success,
        "learn skill"
    );
    std::fs::remove_dir_all(&proj).unwrap();

    let r = sb.mind(&["introspect"]);
    assert!(r.success, "introspect failed: {}", r.stderr);
    assert!(
        r.stdout.contains("parent dir is gone"),
        "without --fix the vanished lobe must be reported: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("issue(s) found"),
        "without --fix the vanished lobe must be COUNTED: {}",
        r.stdout
    );
}

// HARN-16 under `--json`: the one-time unreachable-lobe note runs on the
// ordinary install path, ahead of `learn`'s JSON result. `learn --json` must
// still emit a single JSON document on stdout, or every machine consumer breaks
// the moment a configured lobe becomes unreachable. `note_unreachable_lobe_once`
// routes through `render::note`, which sends it to stderr under `--json`
// (CLI-217).
#[test]
fn harn16_unreachable_note_keeps_json_stdout_parseable() {
    // spec: HARN-16 CLI-217
    let sb = Sandbox::new();
    let gone = sb.base.join("gone-json").join(".windsurf");
    sb.write_config(&format!(
        "lobes = [\"{}\", \"{}\"]\n",
        sb.claude_home.display(),
        gone.display()
    ));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    let learn = sb.mind(&["learn", "review", "--json"]);
    assert!(learn.success, "learn --json failed: {}", learn.stderr);
    assert!(
        serde_json::from_str::<serde_json::Value>(learn.stdout.trim()).is_ok(),
        "stdout under --json must be a single JSON document; the HARN-16 note \
         must be suppressed or routed to stderr: {}",
        learn.stdout
    );
    // CLI-217 routes the note, it does not delete it: it is still reported, on
    // stderr. Deleting it would satisfy the assertion above and lose HARN-16.
    assert!(
        learn.stderr.contains("is unreachable"),
        "the HARN-16 note must still be emitted, on stderr: {}",
        learn.stderr
    );
}

// HARN-17 under `--json`: a blocked backfill target reports a `could not link
// ...` line, and `lobe_add_resolved` runs the backfill BEFORE `print_json`, so
// the same stdout-purity question applies to the foreign-target path. This is
// the exact path HARN-17 added (unconditional backfill under --json), so the
// guard and the reporting arrived together; `render::warn` puts the line on
// stderr under `--json` (CLI-217).
#[test]
fn harn17_blocked_backfill_keeps_json_stdout_parseable() {
    // spec: HARN-17 CLI-217
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("json-blocked-lobe");
    std::fs::create_dir_all(new_lobe.join("skills")).unwrap();
    std::fs::write(new_lobe.join("skills/review"), b"user content").unwrap();
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();

    let added = sb.mind(&["config", "lobes", "add", "--json", &new_lobe_str]);
    assert!(added.success, "lobe add --json failed: {}", added.stderr);
    assert!(
        serde_json::from_str::<serde_json::Value>(added.stdout.trim()).is_ok(),
        "stdout under --json must be a single JSON document; the blocked-target \
         warning must be suppressed or routed to stderr: {}",
        added.stdout
    );
    // As with HARN-16: routed, not deleted. A blocked target is the one thing
    // this JSON result does not carry, so losing the line loses the signal.
    assert!(
        added.stderr.contains("could not link"),
        "the blocked-target warning must still be emitted, on stderr: {}",
        added.stderr
    );
}

// HARN-17 x CLI-217, the half the `--json` test cannot see: `render::warn` is
// the only warn-marked caller of the new routing, and the routing is
// stdout-in-text-mode. Every existing assertion about this line reads either
// stderr (under --json) or a substring of the underlying error ("--force"), so
// a `render::warn` that always wrote to stderr, or that dropped the `!` marker
// the rest of mind's warnings carry, would pass all of them: this line would
// quietly leave the stream the user is reading, or lose the marker that tells
// them it is a warning and not part of the report.
#[test]
fn harn17_blocked_backfill_warning_is_marked_and_on_stdout_in_text_mode() {
    // spec: HARN-17 CLI-217
    let sb = Sandbox::new();
    sb.write_config(&format!("lobes = [\"{}\"]\n", sb.claude_home.display()));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    assert!(sb.mind(&["learn", "review"]).success, "learn skill");

    let new_lobe = sb.base.join("text-blocked-lobe");
    std::fs::create_dir_all(new_lobe.join("skills")).unwrap();
    std::fs::write(new_lobe.join("skills/review"), b"user content").unwrap();
    let new_lobe_str = new_lobe.to_string_lossy().into_owned();

    let added = sb.mind(&["config", "lobes", "add", &new_lobe_str]);
    assert!(added.success, "lobe add failed: {}", added.stderr);
    assert!(
        added.stdout.contains("! could not link"),
        "in text mode the blocked-target warning belongs on STDOUT, carrying the \
         warn marker: stdout={} stderr={}",
        added.stdout,
        added.stderr
    );
    assert!(
        !added.stderr.contains("could not link"),
        "text mode must not route the warning to stderr: {}",
        added.stderr
    );
}

// ---- HARN-20/HARN-21: selective (`--local`) lobe mode --------------------

/// A source melded and a config with TWO all-kinds lobes: the sandbox Claude
/// home, and a project lobe living under `<base>/proj`. Returns (project dir,
/// project lobe path). The project dir is created so it can serve as a cwd and
/// so the lobe's parent is reachable (STO-56).
fn setup_project_lobe(sb: &Sandbox) -> (PathBuf, PathBuf) {
    let proj = sb.base.join("proj");
    let local_lobe = proj.join("locallobe");
    std::fs::create_dir_all(&proj).unwrap();
    sb.write_config(&format!(
        "lobes = [\"{claude}\", \"{local}\"]\n",
        claude = sb.claude_home.display(),
        local = local_lobe.display(),
    ));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    (proj, local_lobe)
}

// HARN-20: `learn --local` run inside a registered project lobe links the item
// into ONLY that lobe, not the global fan-out set (the Claude home is untouched).
#[test]
fn local_learn_links_only_into_the_project_lobe() {
    // spec: HARN-20
    // spec: HARN-21
    let sb = Sandbox::new();
    let (proj, local_lobe) = setup_project_lobe(&sb);

    let learned = sb.run_cwd(&["learn", "review", "--local"], &[], Some(&proj));
    assert!(
        learned.success,
        "learn --local inside a project lobe must succeed: {}",
        learned.stderr
    );

    assert!(
        std::fs::symlink_metadata(local_lobe.join("skills/review")).is_ok(),
        "the skill must link into the project lobe"
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "--local must NOT fan the skill into the global Claude home: stderr={}",
        learned.stderr
    );
}

// HARN-21: `--local` from a directory with no registered project lobe under it is
// an error naming the fix, not a silent fall-back to the global fan-out.
#[test]
fn local_learn_outside_any_lobe_is_an_error() {
    // spec: HARN-21
    let sb = Sandbox::new();
    let (_proj, local_lobe) = setup_project_lobe(&sb);

    // An unrelated cwd: neither the Claude home nor the project lobe lives under it.
    let elsewhere = sb.base.join("elsewhere");
    std::fs::create_dir_all(&elsewhere).unwrap();

    let learned = sb.run_cwd(&["learn", "review", "--local"], &[], Some(&elsewhere));
    assert!(
        !learned.success,
        "--local outside a registered project lobe must fail: {}",
        learned.stdout
    );
    assert!(
        learned
            .stderr
            .contains("no registered project lobe lives under this directory"),
        "the error must explain that the cwd is not inside a project lobe: {}",
        learned.stderr
    );
    // Nothing was installed anywhere.
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err()
            && std::fs::symlink_metadata(local_lobe.join("skills/review")).is_err(),
        "a refused --local install must link nothing"
    );
}

// HARN-20: a plain (no-flag) `learn` still fans out into every configured lobe,
// including the project lobe. `--local` narrows that; its absence does not.
#[test]
fn global_learn_still_fans_out_to_all_lobes() {
    // spec: HARN-20
    let sb = Sandbox::new();
    let (_proj, local_lobe) = setup_project_lobe(&sb);

    // Run from an unrelated cwd so no availability note is even considered.
    let elsewhere = sb.base.join("elsewhere");
    std::fs::create_dir_all(&elsewhere).unwrap();
    let learned = sb.run_cwd(&["learn", "review"], &[], Some(&elsewhere));
    assert!(learned.success, "global learn failed: {}", learned.stderr);

    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok(),
        "global learn must link into the Claude home"
    );
    assert!(
        std::fs::symlink_metadata(local_lobe.join("skills/review")).is_ok(),
        "global learn must also fan into the project lobe"
    );
}

// HARN-21: a global home never qualifies as the project lobe an invocation is
// "inside", even when the naive containment test would match it.
//
// spec/harness-lobes.md (HARN-21) says "A global home lives under `~`, not
// under an arbitrary project cwd, so it does not qualify" for `--local`'s
// containment test. The regression this guards: when the cwd is the PARENT of
// the only configured (global) lobe -- exactly the case the spec text
// describes, cwd = `~`, lobe = `~/.claude` -- `~/.claude` satisfies
// `starts_with(cwd)`, so a naive test would treat the global home as "the
// project lobe the cwd sits inside" and silently narrow the `--local` install
// to it. `detect_local_lobe` excludes the resolved default/global home, so this
// must instead be REFUSED with the same actionable error as
// `local_learn_outside_any_lobe_is_an_error`.
#[test]
fn local_learn_from_global_lobes_parent_dir_refuses() {
    // spec: HARN-21
    let sb = Sandbox::new();
    // Default config: the single global lobe is `claude_home`, no project lobe
    // registered anywhere. `sb.base` is `claude_home`'s parent directory --
    // i.e. what a real invocation from `$HOME` looks like when only `~/.claude`
    // is configured.
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let learned = sb.run_cwd(&["learn", "review", "--local"], &[], Some(&sb.base));

    // Per HARN-21's spec text the global home does not qualify as a project
    // lobe, so `--local` from its parent directory must be refused, not narrowed
    // to that global home.
    assert!(
        !learned.success,
        "--local from the global lobe's parent directory must be refused, not \
         narrowed to the global home: stdout={} stderr={}",
        learned.stdout, learned.stderr
    );
    assert!(
        learned
            .stderr
            .contains("no registered project lobe lives under this directory"),
        "the error must explain that the cwd is not inside a project lobe: {}",
        learned.stderr
    );
    // Nothing was linked into the global home (the refused install is a no-op).
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "a refused --local install must not link into the global home: {}",
        learned.stderr
    );
}

// HARN-21: when the cwd contains TWO registered lobes at different nesting
// depths, the deeper one (more path components, i.e. the outer/shallow lobe's
// own subdirectory) wins over the shallower one -- pinning down
// `detect_local_lobe`'s tie-break, which is otherwise untested.
#[test]
fn local_learn_picks_the_deeper_of_two_qualifying_lobes() {
    // spec: HARN-21
    let sb = Sandbox::new();
    let proj = sb.base.join("proj");
    let shallow = proj.join("shallowlobe");
    let deep = proj.join("shallowlobe").join("nested").join("deeplobe");
    // The lobe's parent directory must exist (STO-56) for it to be reachable.
    std::fs::create_dir_all(deep.parent().unwrap()).unwrap();
    sb.write_config(&format!(
        "lobes = [\"{claude}\", \"{shallow}\", \"{deep}\"]\n",
        claude = sb.claude_home.display(),
        shallow = shallow.display(),
        deep = deep.display(),
    ));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let learned = sb.run_cwd(&["learn", "review", "--local"], &[], Some(&proj));
    assert!(learned.success, "{}", learned.stderr);
    assert!(
        learned
            .stderr
            .contains(&deep.to_string_lossy().into_owned()),
        "the note must name the deeper (winning) lobe: {}",
        learned.stderr
    );

    assert!(
        std::fs::symlink_metadata(deep.join("skills/review")).is_ok(),
        "the deeper lobe must receive the link"
    );
    assert!(
        std::fs::symlink_metadata(shallow.join("skills/review")).is_err(),
        "the shallower (losing) lobe must NOT receive the link"
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "the global lobe must not receive the link either"
    );
}

// HARN-20: `--local` combined with `--json` must still scope to exactly one
// lobe, and the scoping note (normally on stderr) must be suppressed --
// stdout carries only the JSON result envelope.
#[test]
fn local_learn_json_scopes_to_one_lobe_and_suppresses_the_note() {
    // spec: HARN-20
    let sb = Sandbox::new();
    let (proj, local_lobe) = setup_project_lobe(&sb);

    let learned = sb.run_cwd(&["--json", "learn", "review", "--local"], &[], Some(&proj));
    assert!(learned.success, "{} {}", learned.stdout, learned.stderr);

    let v = parse_json(&learned.stdout);
    assert_eq!(v["schema"], 1, "{}", learned.stdout);

    assert!(
        std::fs::symlink_metadata(local_lobe.join("skills/review")).is_ok(),
        "--local --json must still link into the project lobe"
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "--local --json must NOT fan into the global Claude home"
    );
    assert!(
        !learned.stderr.contains("--local"),
        "the --local scoping note must be suppressed under --json: {}",
        learned.stderr
    );
}

// HARN-20: `meld --local` (as distinct from `learn --local`) also scopes its
// install fan-out to only the project lobe. Driven under `--json` so the
// install-all offer runs silently instead of needing a TTY confirm.
#[test]
fn local_meld_json_links_only_into_the_project_lobe() {
    // spec: HARN-20
    let sb = Sandbox::new();
    let proj = sb.base.join("proj");
    let local_lobe = proj.join("locallobe");
    std::fs::create_dir_all(&proj).unwrap();
    sb.write_config(&format!(
        "lobes = [\"{claude}\", \"{local}\"]\n",
        claude = sb.claude_home.display(),
        local = local_lobe.display(),
    ));

    let spec = sb.source_spec();
    let melded = sb.run_cwd(
        &["--json", "--yes", "meld", &spec, "--local"],
        &[],
        Some(&proj),
    );
    assert!(melded.success, "{} {}", melded.stdout, melded.stderr);

    assert!(
        std::fs::symlink_metadata(local_lobe.join("skills/review")).is_ok(),
        "meld --local must link into the project lobe: {}",
        melded.stdout
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "meld --local must NOT fan into the global Claude home"
    );
}

// HARN-20: a plain (no-flag) `learn` run inside a registered project lobe
// prints the "you could use --local" advisory note on stderr, but stays
// non-interactive (still fans out to every lobe) and the note is suppressed
// under `--json`.
#[test]
fn plain_learn_inside_a_project_lobe_prints_the_local_availability_note() {
    // spec: HARN-20
    let sb = Sandbox::new();
    let (proj, local_lobe) = setup_project_lobe(&sb);

    let learned = sb.run_cwd(&["learn", "review"], &[], Some(&proj));
    assert!(learned.success, "{}", learned.stderr);
    assert!(
        learned.stderr.contains("--local"),
        "a plain learn inside a registered project lobe must advertise \
         --local on stderr: {}",
        learned.stderr
    );
    // Still fans out to every configured lobe (the note is advisory only).
    assert!(std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_ok());
    assert!(std::fs::symlink_metadata(local_lobe.join("skills/review")).is_ok());

    // Under --json the note is suppressed entirely (LIFE-45 / HARN-20: json
    // output is non-interactive and its stderr carries no interleaved prose).
    let json_run = sb.run_cwd(&["--json", "learn", "review"], &[], Some(&proj));
    assert!(json_run.success, "{}", json_run.stderr);
    assert!(
        !json_run.stderr.contains("--local"),
        "the availability note must be suppressed under --json: {}",
        json_run.stderr
    );
}

// HARN-21: a home-rooted global preset lobe (e.g. `~/.gemini/config`) must NOT
// qualify as the project lobe an invocation is "inside" when the cwd sits AT
// (not just above) the home directory. This exercises the
// `lp.starts_with(home) && home.starts_with(cwd)` branch of
// `detect_local_lobe` directly -- distinct from
// `local_learn_from_global_lobes_parent_dir_refuses`, which only ever hits the
// `lp == global_home` branch because its sole configured lobe IS the resolved
// default home. Here the configured lobe is a SEPARATE, home-rooted, non-default
// lobe (like a `--preset gemini` add), so only the home-rooted exclusion can be
// responsible for the refusal.
#[test]
fn local_learn_from_home_rooted_preset_lobe_refuses() {
    // spec: HARN-21
    let sb = Sandbox::new();
    let home_dir = sb.base.join("home");
    let gemini_lobe = home_dir.join(".gemini").join("config");
    std::fs::create_dir_all(&home_dir).unwrap();
    sb.write_config(&format!(
        "lobes = [\"{claude}\", \"{gemini}\"]\n",
        claude = sb.claude_home.display(),
        gemini = gemini_lobe.display(),
    ));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let home_str = home_dir.to_string_lossy().into_owned();
    let learned = sb.run_cwd(
        &["learn", "review", "--local"],
        &[("HOME", home_str.as_str())],
        Some(&home_dir),
    );

    assert!(
        !learned.success,
        "--local from a home-rooted preset lobe's home directory must be \
         refused, not narrowed to that preset lobe: stdout={} stderr={}",
        learned.stdout, learned.stderr
    );
    assert!(
        learned
            .stderr
            .contains("no registered project lobe lives under this directory"),
        "the error must explain that the cwd is not inside a project lobe: {}",
        learned.stderr
    );
    assert!(
        std::fs::symlink_metadata(gemini_lobe.join("skills/review")).is_err(),
        "a refused --local install must not link into the home-rooted preset \
         lobe: {}",
        learned.stderr
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "a refused --local install must not link into the global home either"
    );
}

// HARN-21 (inverse of the above, guarding against over-exclusion): a genuine
// PROJECT lobe that happens to live under the home directory, with the cwd
// genuinely BELOW the home directory (not at or above it), must still be
// detected and receive the `--local` install. "A real project lobe placed
// under `~` ... is unaffected: the cwd is below `~`, not at or above it, so
// the home-rooted exclusion does not fire" (spec/harness-lobes.md HARN-21).
#[test]
fn local_learn_project_lobe_under_home_dir_is_still_detected() {
    // spec: HARN-21
    let sb = Sandbox::new();
    let home_dir = sb.base.join("home");
    let proj = home_dir.join("dev").join("proj");
    let local_lobe = proj.join("locallobe");
    std::fs::create_dir_all(&proj).unwrap();
    sb.write_config(&format!(
        "lobes = [\"{claude}\", \"{local}\"]\n",
        claude = sb.claude_home.display(),
        local = local_lobe.display(),
    ));
    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let home_str = home_dir.to_string_lossy().into_owned();
    let learned = sb.run_cwd(
        &["learn", "review", "--local"],
        &[("HOME", home_str.as_str())],
        Some(&proj),
    );

    assert!(
        learned.success,
        "a genuine project lobe under the home directory, with cwd below the \
         home directory, must still be detected: {}",
        learned.stderr
    );
    assert!(
        std::fs::symlink_metadata(local_lobe.join("skills/review")).is_ok(),
        "the project lobe under the home directory must receive the link"
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "--local must NOT fan the skill into the global Claude home"
    );
}

// HARN-21: the global-home exclusion must key off the RESOLVED default home
// (`MIND_DEFAULT_LOBE`, which per CLI-170 takes precedence over `CLAUDE_HOME`),
// not just `CLAUDE_HOME`. With no `lobes` configured, `agent_homes()` falls
// back to `[claude_home]`, and `claude_home` is resolved from
// `MIND_DEFAULT_LOBE` here even though `CLAUDE_HOME` is also set (to a
// different, unused path) by the test harness on every invocation.
#[test]
fn local_learn_mind_default_lobe_as_global_home_is_excluded() {
    // spec: HARN-21
    // spec: CLI-170
    let sb = Sandbox::new();
    let default_lobe_dir = sb.base.join("customdefault");
    std::fs::create_dir_all(&default_lobe_dir).unwrap();
    let default_str = default_lobe_dir.to_string_lossy().into_owned();
    // `meld` (like every command) calls `ensure_config`, which persists a
    // default `lobes = [self.default_lobe()]` entry to config.toml on first
    // touch (using whatever env is in effect for THAT invocation). Meld with
    // the same MIND_DEFAULT_LOBE so the persisted default lobe is the one
    // under test, rather than accidentally locking in a stale CLAUDE_HOME
    // value from an earlier untagged invocation.
    assert!(
        sb.mind_env(
            &["meld", &sb.source_spec()],
            &[("MIND_DEFAULT_LOBE", default_str.as_str())]
        )
        .success
    );

    let learned = sb.run_cwd(
        &["learn", "review", "--local"],
        &[("MIND_DEFAULT_LOBE", default_str.as_str())],
        Some(&sb.base),
    );

    assert!(
        !learned.success,
        "--local from the MIND_DEFAULT_LOBE-resolved global home's parent \
         directory must be refused, not narrowed to that home: stdout={} \
         stderr={}",
        learned.stdout, learned.stderr
    );
    assert!(
        learned
            .stderr
            .contains("no registered project lobe lives under this directory"),
        "the error must explain that the cwd is not inside a project lobe: {}",
        learned.stderr
    );
    assert!(
        std::fs::symlink_metadata(default_lobe_dir.join("skills/review")).is_err(),
        "a refused --local install must not link into the MIND_DEFAULT_LOBE \
         home: {}",
        learned.stderr
    );
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("skills/review")).is_err(),
        "a refused --local install must not link into the (unused) CLAUDE_HOME \
         either"
    );
}

// HARN-22/HARN-23: a configured agent home whose own directory is a dangling
// symlink otherwise fails deep inside install with a bare `File exists` (the
// link itself exists, so `create_dir_all` refuses) that names neither the
// link nor its missing target. This is the exact user-facing path HARN-22
// exists for; unlike the unit-level `mkdir_p` coverage in `src/paths.rs`, this
// drives the real `learn` command end-to-end so a future change to where the
// lobe directory gets created (which would silently move the failure back to
// a bare `File exists`) is caught here even if the unit test stays green.
#[cfg(unix)]
#[test]
fn learn_into_a_lobe_whose_directory_is_a_dangling_symlink_names_the_broken_link() {
    // spec: HARN-22
    // spec: HARN-23
    let sb = Sandbox::new();
    let broken_lobe = sb.base.join("brokenlobe");
    let missing_target = sb.base.join("gone");
    std::os::unix::fs::symlink(&missing_target, &broken_lobe).unwrap();

    // Configure ONLY the broken lobe, so `learn` cannot succeed by fanning
    // into some other, healthy lobe.
    sb.write_config(&format!("lobes = [\"{}\"]\n", broken_lobe.display()));

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);

    let learned = sb.mind(&["learn", "review"]);
    assert!(
        !learned.success,
        "learn into a lobe whose directory is a dangling symlink must fail: \
         stdout={} stderr={}",
        learned.stdout, learned.stderr
    );
    assert!(
        learned.stderr.contains("brokenlobe"),
        "the error must name the broken link: {}",
        learned.stderr
    );
    assert!(
        learned.stderr.contains("gone"),
        "the error must name the link's (missing) target: {}",
        learned.stderr
    );
    assert!(
        !learned.stderr.contains("os error 17") && !learned.stderr.contains("File exists"),
        "must not surface the OS's bare File-exists errno as the reported cause: {}",
        learned.stderr
    );

    // Confirm via `--json` that the structured error kind is exactly
    // `broken-symlink-path`, not a generic `io`.
    let learned_json = sb.mind(&["learn", "review", "--json"]);
    assert!(!learned_json.success);
    let v = parse_json(&learned_json.stdout);
    assert_eq!(
        v["error"]["kind"], "broken-symlink-path",
        "expected the broken-symlink-path error kind: {v}"
    );
}

// WF-13: a project lobe carrying no `kinds` filter needs no special handling
// for a workflow -- the harness reads project workflows from
// `<project>/.claude/workflows/`, exactly where such a lobe already links one
// by WF-10. The failure mode this closes is a project lobe that DOES carry a
// kinds filter: `--subdir` and every harness preset (windsurf included, per
// the preset table in paths.rs) admit skills only, and
// `a_skills_only_lobe_admits_no_workflows` (tests/cli_workflows.rs) proves
// that filter is live. `link-project`'s own
// default (the windsurf preset) and its `--subdir` form are both skill-only,
// so neither exercises the no-filter path; the bare `config lobes add <path>`
// form is the one with no kinds restriction (`Lobe::all_kinds`, paths.rs),
// which is what registers the project lobe here.
#[test]
fn wf13_project_lobe_with_no_kinds_filter_admits_a_workflow() {
    // spec: WF-13
    let sb = Sandbox::new();
    write(
        &sb.source.join("workflows/deploy.js"),
        "export const meta = {\n  name: 'deploy',\n  description: 'Deploy it',\n}\n",
    );
    git(&sb.source, &["add", "-A"]);
    git(&sb.source, &["commit", "-qm", "add workflow"]);

    let proj = sb.base.join("proj");
    std::fs::create_dir_all(&proj).unwrap();
    let lobe = proj.join(".claude");
    let lobe_str = lobe.to_string_lossy().into_owned();

    let added = sb.mind(&["config", "lobes", "add", &lobe_str]);
    assert!(added.success, "config lobes add failed: {}", added.stderr);

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    let learned = sb.mind(&["learn", "workflow:deploy"]);
    assert!(
        learned.success,
        "learn workflow: {}\n{}",
        learned.stdout, learned.stderr
    );

    assert!(
        std::fs::symlink_metadata(proj.join(".claude/workflows/deploy.js")).is_ok(),
        "a project lobe with no kinds filter must link the workflow (WF-13): {}",
        learned.stdout
    );
}

// WF-13 (the negative half): `link-project` can never produce a lobe that
// admits a workflow. Both of its forms carry a `kinds` filter -- the default
// windsurf preset (the `paths.rs` preset table, `kinds: &[ItemKind::Skill]`)
// and `--subdir` (`paths.rs`, `kinds: Some(vec![ItemKind::Skill])`) -- and
// there is no `claude` preset to opt out with. So a workflow learned while a
// project lobe is registered lands in the default Claude lobe and NOWHERE in
// the project.
//
// The `--subdir .claude` case is the load-bearing one: it points the project
// lobe at exactly the directory the harness reads project workflows from, so
// the workflow's absence there cannot be explained away as a path mismatch.
// The skill assertions are the control -- both lobes are live and receiving
// links at the moment the workflow is refused.
#[test]
fn wf13_link_project_lobe_never_links_a_workflow() {
    // spec: WF-13 WF-12
    let sb = Sandbox::new();
    write(
        &sb.source.join("workflows/deploy.js"),
        "export const meta = {\n  name: 'deploy',\n  description: 'Deploy it',\n}\n",
    );
    git(&sb.source, &["add", "-A"]);
    git(&sb.source, &["commit", "-qm", "add workflow"]);

    // Form 1: the default preset (windsurf).
    let ws_proj = sb.base.join("ws-proj");
    std::fs::create_dir_all(&ws_proj).unwrap();
    let ws_str = ws_proj.to_string_lossy().into_owned();
    let r1 = sb.mind(&["link-project", &ws_str]);
    assert!(r1.success, "link-project failed: {}", r1.stderr);

    // Form 2: `--subdir .claude` -- the harness's own project workflow dir.
    let sd_proj = sb.base.join("sd-proj");
    std::fs::create_dir_all(&sd_proj).unwrap();
    let sd_str = sd_proj.to_string_lossy().into_owned();
    let r2 = sb.mind(&["link-project", &sd_str, "--subdir", ".claude"]);
    assert!(r2.success, "link-project --subdir failed: {}", r2.stderr);

    assert!(sb.mind(&["meld", &sb.source_spec()]).success);
    let learned = sb.mind(&["learn", "workflow:deploy"]);
    assert!(
        learned.success,
        "learn workflow: {}\n{}",
        learned.stdout, learned.stderr
    );
    let learned_skill = sb.mind(&["learn", "review"]);
    assert!(
        learned_skill.success,
        "learn skill: {}\n{}",
        learned_skill.stdout, learned_skill.stderr
    );

    // Control: the skill fans into BOTH project lobes, so they are registered
    // and live.
    assert!(
        std::fs::symlink_metadata(ws_proj.join(".windsurf/skills/review")).is_ok(),
        "the windsurf project lobe must receive the skill: {}",
        learned_skill.stdout
    );
    assert!(
        std::fs::symlink_metadata(sd_proj.join(".claude/skills/review")).is_ok(),
        "the --subdir project lobe must receive the skill: {}",
        learned_skill.stdout
    );

    // spec: WF-13 -- and neither receives the workflow.
    assert!(
        std::fs::symlink_metadata(ws_proj.join(".windsurf/workflows/deploy.js")).is_err(),
        "a link-project (windsurf preset) lobe must not link a workflow"
    );
    assert!(
        std::fs::symlink_metadata(ws_proj.join(".windsurf/workflows")).is_err(),
        "a link-project (windsurf preset) lobe must not even create workflows/"
    );
    assert!(
        std::fs::symlink_metadata(sd_proj.join(".claude/workflows/deploy.js")).is_err(),
        "a link-project --subdir lobe must not link a workflow even when it is \
         rooted at the harness's own project workflow directory"
    );
    assert!(
        std::fs::symlink_metadata(sd_proj.join(".claude/workflows")).is_err(),
        "a link-project --subdir lobe must not even create workflows/"
    );

    // Control: the unfiltered default Claude lobe did receive it, so the
    // absences above are the kinds filter and not a failed install.
    assert!(
        std::fs::symlink_metadata(sb.claude_home.join("workflows/deploy.js")).is_ok(),
        "the default (unfiltered) lobe must link the workflow: {}",
        learned.stdout
    );
}

// WF-13: there is no `claude` preset, so a caller cannot ask `link-project`
// for a lobe that admits a workflow by naming the Claude harness. The verb
// fails rather than quietly resolving to something skill-only.
#[test]
fn wf13_link_project_has_no_claude_preset() {
    // spec: WF-13
    let sb = Sandbox::new();
    let proj = sb.base.join("claude-proj");
    std::fs::create_dir_all(&proj).unwrap();
    let proj_str = proj.to_string_lossy().into_owned();

    let r = sb.mind(&["--json", "link-project", &proj_str, "--preset", "claude"]);
    assert!(
        !r.success,
        "`--preset claude` must fail, not resolve: stdout={} stderr={}",
        r.stdout, r.stderr
    );
    let err = parse_json(&r.stdout);
    assert_eq!(
        err["error"]["kind"], "unknown-preset",
        "`claude` must be an unknown preset, not a silently skill-only one: {err}"
    );
    // Nothing registered, so nothing can later link a workflow here.
    let listed = sb.mind(&["config", "lobes", "list", "--json"]);
    let v = parse_json(&listed.stdout);
    assert!(
        !v["lobes"].as_array().unwrap().iter().any(|l| l["path"]
            .as_str()
            .is_some_and(|p| p.contains("claude-proj"))),
        "a failed preset add must register no lobe: {}",
        listed.stdout
    );
}

// UNM-9: an unmanaged workflow whose filename strips to an unsafe name
// (`...js` -> `..`) is skipped with a warning; the scan and `recall` still
// succeed and a well-formed sibling is still listed.
#[test]
fn unm9_recall_skips_an_unsafe_named_unmanaged_workflow() {
    // spec: UNM-9
    let sb = Sandbox::new();
    let body = "export const meta = {\n  name: 'deploy',\n  description: 'Deploy it',\n}\n";
    write(&sb.claude_home.join("workflows/...js"), body);
    write(&sb.claude_home.join("workflows/deploy.js"), body);

    let r = sb.mind(&["recall"]);
    assert!(
        r.success,
        "recall must succeed despite the unsafe entry: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        r.stderr.contains("skipping unmanaged workflow"),
        "the unsafe entry must be reported as skipped: {}",
        r.stderr
    );
    assert!(
        r.stdout.contains("deploy"),
        "the well-formed sibling must still be listed: {}",
        r.stdout
    );
}