mushroomdb-cli 0.6.12

CLI binary for mushroomdb: start, shell, and server commands
Documentation
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
//! `mushroomdb install` / `uninstall` — wire the /mushroom skill, the MCP
//! server, the prompt hooks and the git hooks into an assistant.
//!
//! # Design notes
//!
//! - Idempotent: running install twice is a no-op (exit 0).
//! - Non-destructive: refuses to overwrite user files install didn't create.
//! - Manifest-driven uninstall: tracks every file, key, hook, ignore line and
//!   external registration it wrote; removes exactly that.
//! - The only network access is the optional pre-warm, which is a best-effort
//!   warm cache and never fails the install.
//!
//! # User-scope MCP config location (verified 2026-09-02 by live inspection)
//!
//! Claude Code user-level MCP servers live in `~/.claude.json` under the
//! top-level `"mcpServers"` key. This was verified empirically on a live
//! Claude Code install: `~/.claude/settings.json` holds env/permissions/hooks
//! but NO mcpServers key. Cursor uses `~/.cursor/mcp.json` (same format as
//! project-level `.cursor/mcp.json`). Codex keeps its own config and is
//! written through the `codex` CLI rather than by editing a file.

use crate::CliError;
use serde::{Deserialize, Serialize};
use std::ffi::{OsStr, OsString};
use std::fs;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};

// Template files embedded at compile time. Files live inside the crates/cli
// package so `cargo package` includes them in the published tarball.
// Path is relative to this source file (crates/cli/src/install.rs).
const SKILL_TEMPLATE: &str = include_str!("../skills/mushroom/SKILL.md");
const CURSOR_RULES_TEMPLATE: &str = include_str!("../skills/mushroom/cursor-rules.mdc");

/// Placeholder string replaced with the real db path in embedded templates.
const DB_PATH_PLACEHOLDER: &str = "{{DB_PATH}}";

/// Placeholder string replaced with the command that invokes mushroomdb.
/// Substituted with [`McpCommand::shell`], which is already shell-quoted, so
/// the templates must leave it unquoted.
const BIN_PLACEHOLDER: &str = "{{BIN}}";

/// The MCP server name we write. Must not be changed without a migration.
pub(crate) const SERVER_NAME: &str = "mushroomdb";

/// The binary name looked up on PATH and used as the bare MCP command.
const BIN_NAME: &str = "mushroomdb";

/// The npm package the `npx` form runs. Same name as the binary.
const NPM_PACKAGE: &str = "mushroomdb";

/// The version an `npx` entry pins: the one that wrote it.
const CRATE_VERSION: &str = env!("CARGO_PKG_VERSION");

/// How long the optional pre-warm may take before it is abandoned. A cold
/// `npx` download of a native package is slow on a slow link, and the whole
/// point is to pay that cost here rather than at the assistant's first prompt.
const PREWARM_TIMEOUT_SECS: u64 = 180;

/// The Node runtime a resolved launcher is handed to. Looked up on PATH: any
/// machine with `npx` has it, since npm ships with Node.
const NODE_BIN: &str = "node";

/// The flag the npm launcher answers with the vendored native binary's path.
const PRINT_BINARY_FLAG: &str = "--print-binary";

/// The flag the npm launcher answers with its own absolute path.
const PRINT_LAUNCHER_FLAG: &str = "--print-launcher";

// ---------------------------------------------------------------------------
// How the server is invoked
// ---------------------------------------------------------------------------

/// How the MCP server entry (and the skill's bootstrap commands) invoke
/// mushroomdb.
///
/// The assistant host spawns the MCP server by `command`, so that command has
/// to resolve from *its* process, not from the shell install ran in. A bare
/// name only works when it resolves on the host's PATH, and the one case where
/// that is provable is when the `mushroomdb` PATH resolves to is this very
/// executable. Everything else — npm's Node shim, a different build, a local
/// `target/release` binary, no hit at all — pins the published package and
/// lets `npx` fetch it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpCommand {
    /// `npx -y mushroomdb@<version> …` — the fallback when the package cannot
    /// be located, and the only form that works from a machine where nothing
    /// is installed globally.
    Npx { version: String },
    /// The published package's own native binary, located once at install time
    /// and run directly. The fast form, and what a hook gets whenever the
    /// package has been fetched.
    ///
    /// Everything else in this enum that reaches the published package ends up
    /// running this exact file; the difference is what it costs to get there.
    /// Measured warm, `--version` end to end: `npx` 514 ms, `node <launcher>`
    /// 118 ms, this 7 ms. Node's own startup is nearly all of the difference —
    /// the launcher script's only job is to spawn this binary — and a hook pays
    /// it on every prompt and every edit.
    NativeBinary {
        /// Absolute path to the vendored executable.
        binary: PathBuf,
        /// The version it was resolved from; re-resolved on upgrade.
        version: String,
    },
    /// `node <launcher.js> …` — the same published package reached through its
    /// npm shim. The fallback for an install whose native binary could not be
    /// located (a postinstall that never fetched it, say): still resolved once
    /// rather than on every invocation, just through a Node startup.
    NodeLauncher {
        /// Absolute path to the package's `bin` script.
        launcher: PathBuf,
        /// The version it was resolved from; re-resolved on upgrade.
        version: String,
    },
    /// An absolute path the user named with `--command`.
    Explicit(PathBuf),
    /// `mushroomdb` resolves on PATH *and* is this executable: the bare name
    /// is safe and follows upgrades.
    OnPath,
}

impl McpCommand {
    /// The `npx` form pinned to the version of the binary writing it.
    #[must_use]
    pub fn npx() -> Self {
        McpCommand::Npx {
            version: CRATE_VERSION.to_string(),
        }
    }

    /// The program to exec and the arguments that come before the subcommand.
    fn program(&self) -> (String, Vec<String>) {
        match self {
            McpCommand::Npx { version } => (
                "npx".to_string(),
                vec!["-y".to_string(), format!("{NPM_PACKAGE}@{version}")],
            ),
            McpCommand::NativeBinary { binary, .. } => {
                (binary.to_string_lossy().into_owned(), Vec::new())
            }
            McpCommand::NodeLauncher { launcher, .. } => (
                NODE_BIN.to_string(),
                vec![launcher.to_string_lossy().into_owned()],
            ),
            McpCommand::Explicit(p) => (p.to_string_lossy().into_owned(), Vec::new()),
            McpCommand::OnPath => (BIN_NAME.to_string(), Vec::new()),
        }
    }

    /// The MCP server entry: `{"command": …, "args": [… , sub, db]}`.
    ///
    /// Nothing here is shell-quoted. An MCP host spawns the command with an
    /// argv, so a path with a space in it is one element and quoting it would
    /// make the quotes part of the filename.
    #[must_use]
    pub fn json_entry(&self, sub: &str, db: &str) -> serde_json::Value {
        let (command, mut args) = self.program();
        args.push(sub.to_string());
        args.push(db.to_string());
        serde_json::json!({ "command": command, "args": args })
    }

    /// The same invocation as a command *prefix* for a POSIX shell, already
    /// quoted where quoting is needed.
    ///
    /// Hook entries and the skill's copy-paste lines are read by a shell, so
    /// an explicit path — and a resolved binary or launcher path, which lives
    /// wherever npm put it — has to survive a space in it. The bare name and
    /// the `npx` form contain no metacharacters and are left as they read.
    #[must_use]
    pub fn shell(&self) -> String {
        let (command, args) = self.program();
        let mut out = match self {
            McpCommand::Explicit(_) | McpCommand::NativeBinary { .. } => sh_quote(&command),
            _ => command,
        };
        for a in args {
            out.push(' ');
            match self {
                McpCommand::NodeLauncher { .. } => out.push_str(&sh_quote(&a)),
                _ => out.push_str(&a),
            }
        }
        out
    }

    /// The full argv, for handing to another CLI that registers servers.
    fn argv(&self, sub: &str, db: &str) -> Vec<String> {
        let (command, mut args) = self.program();
        args.push(sub.to_string());
        args.push(db.to_string());
        let mut out = vec![command];
        out.extend(args);
        out
    }
}

/// Decide how the MCP entry should invoke mushroomdb, from an explicit
/// `--command` (if any) and the real environment.
///
/// `explicit` is `install`'s `--command` flag; `enable` has no such flag and
/// always passes `None`, so it re-derives whatever `install` would choose
/// right now rather than replaying what an earlier install or `disable`
/// recorded.
#[must_use]
pub fn detect_mcp_command(explicit: Option<&Path>) -> McpCommand {
    if let Some(path) = explicit {
        return McpCommand::Explicit(path.to_path_buf());
    }
    match std::env::current_exe() {
        Ok(exe) => classify_mcp_command(std::env::var_os("PATH").as_deref(), &exe),
        // Cannot locate ourselves — the pinned package always resolves.
        Err(_) => McpCommand::npx(),
    }
}

/// Pure classifier behind [`detect_mcp_command`]: decide whether the
/// `mushroomdb` that PATH resolves to is the executable now running.
///
/// A file named `mushroomdb` on PATH is not enough. `npx mushroomdb install`
/// prepends `~/.npm/_npx/<hash>/node_modules/.bin` to PATH, and the
/// `mushroomdb` there is npm's Node shim (`#!/usr/bin/env node`), not our
/// native binary; `npm i -g mushroomdb` installs the same shim. Treating that
/// as "on PATH" wrote a bare `mushroomdb` command that resolved only inside
/// the npx-spawned shell, so the MCP server and recall hook died with ENOENT
/// everywhere else (the v0.5.0 bug).
///
/// So: take the first PATH hit — that is what a bare name would resolve to —
/// and canonicalize both it and `current_exe`. Equal paths mean the bare name
/// runs this very executable, including via a symlink (how `cargo install` and
/// Homebrew expose it), which is the one case where the bare name is safe and
/// survives upgrades. Anything else means pinning the published package.
#[must_use]
pub fn classify_mcp_command(path_var: Option<&OsStr>, current_exe: &Path) -> McpCommand {
    // What a bare `mushroomdb` would resolve to: the first PATH entry holding
    // a file by that name (`is_file` follows symlinks, so links count).
    let Some(hit) = path_var.and_then(|p| {
        std::env::split_paths(p)
            .map(|dir| dir.join(BIN_NAME))
            .find(|candidate| candidate.is_file())
    }) else {
        return McpCommand::npx();
    };

    // Identity, not name. Canonicalizing resolves symlinks and `..`, so a link
    // to us compares equal; if either side cannot be resolved we cannot prove
    // it is us, and the pinned package is the answer that always works.
    match (fs::canonicalize(&hit), fs::canonicalize(current_exe)) {
        (Ok(on_path), Ok(running)) if on_path == running => McpCommand::OnPath,
        _ => McpCommand::npx(),
    }
}

// ---------------------------------------------------------------------------
// How the store is named
// ---------------------------------------------------------------------------

/// The argument every written command uses in place of a store path when the
/// store is to be resolved at run time.
pub const AUTO_ARG: &str = "--auto";

/// How the config an install writes names the store.
///
/// A project install writes `--auto`, not a path. The MCP entry, the three
/// settings hooks and the three git hook blocks then resolve the store when
/// they run — `$CLAUDE_PROJECT_DIR/mushroom-memory`, else `mushroom-memory` at
/// the root of the working tree they were run in.
///
/// The reason is `git worktree`. Those config files live in the repository and
/// get committed, so an absolute path baked into them follows a new worktree
/// across and points every hook there at the *other* checkout's store: the
/// graph then describes files that are not the ones being edited. Resolving at
/// run time gives each working tree its own store, which is the only answer
/// that is right in both checkouts.
///
/// `--db <path>` opts out and pins an absolute path; user scope always pins
/// `~/.mushroomdb/memory`, since `--auto` inside any checkout would resolve to
/// that project instead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoreRef {
    /// Where the store actually is for the checkout install ran in. Every
    /// local decision — the `.gitignore` line, the skill's prose, the
    /// pre-flight conflict check — needs a real directory whichever form is
    /// written into the config.
    path: PathBuf,
    /// Whether written config says `--auto` rather than that path.
    auto: bool,
    /// Whether `--auto` resolves to this same store in this checkout. Always
    /// true when `auto` is. Also true for a `--db` that happens to name the
    /// default store, so an upgrade over an `--auto` install replaces its
    /// hooks instead of running both.
    auto_equivalent: bool,
}

impl StoreRef {
    /// A store the config names `--auto`, living at `path` for this checkout.
    #[must_use]
    pub fn auto(path: impl Into<PathBuf>) -> Self {
        let path = path.into();
        StoreRef {
            path,
            auto: true,
            auto_equivalent: true,
        }
    }

    /// A store the config names by absolute path.
    #[must_use]
    pub fn pinned(path: impl Into<PathBuf>) -> Self {
        StoreRef {
            path: path.into(),
            auto: false,
            auto_equivalent: false,
        }
    }

    /// Mark a pinned store as the one `--auto` also resolves to here.
    #[must_use]
    pub fn also_auto(mut self) -> Self {
        self.auto_equivalent = true;
        self
    }

    /// Where the store is on this machine, right now.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Whether written config resolves the store at run time.
    #[must_use]
    pub fn is_auto(&self) -> bool {
        self.auto
    }

    /// The argument written into an MCP entry's `args` array: `--auto`, or the
    /// path. Not shell-quoted — an MCP host spawns an argv, where quotes would
    /// become part of the filename.
    #[must_use]
    pub fn arg(&self) -> String {
        if self.auto {
            AUTO_ARG.to_string()
        } else {
            self.path.to_string_lossy().into_owned()
        }
    }

    /// The same argument for a command line a shell reads, quoted where
    /// quoting is needed. `--auto` needs none; a path may contain a space.
    #[must_use]
    pub fn shell_arg(&self) -> String {
        if self.auto {
            AUTO_ARG.to_string()
        } else {
            sh_quote(&self.path.to_string_lossy())
        }
    }

    /// How the summary line describes the store.
    fn describe(&self) -> String {
        if self.auto {
            format!("{AUTO_ARG} (resolves to {})", self.path.display())
        } else {
            format!("{} (pinned)", self.path.display())
        }
    }

    /// Every command tail a hook of ours for `sub` may end with, for this
    /// store: the path spelling always, and the `--auto` spelling when that
    /// resolves here too.
    ///
    /// Both are needed because an upgrade must recognise what the *previous*
    /// version wrote. 0.6.0 wrote an absolute path; this version writes
    /// `--auto`; either one left behind alongside the other means two recall
    /// digests on every prompt.
    fn hook_tails(&self, sub: &str) -> Vec<String> {
        let mut out = vec![format!(" {sub} {}", sh_quote(&self.path.to_string_lossy()))];
        if self.auto_equivalent {
            out.push(format!(" {sub} {AUTO_ARG}"));
        }
        out
    }

    /// Whether an existing config argument names this same store: the same
    /// spelling, the same path, or `--auto` where `--auto` means this store.
    ///
    /// This is what makes an upgrade an upgrade rather than a conflict — a
    /// 0.6.0 entry naming `<project>/mushroom-memory` is the store `--auto`
    /// now resolves to, so it is rewritten rather than refused.
    fn names_same_store(&self, existing_arg: &str) -> bool {
        if existing_arg == AUTO_ARG {
            return self.auto_equivalent;
        }
        Path::new(existing_arg) == self.path
    }
}

// ---------------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------------

/// Which assistant platform(s) to wire up.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Platform {
    ClaudeCode,
    Cursor,
    Codex,
    All,
}

impl Platform {
    pub fn parse(s: &str) -> Result<Self, String> {
        match s {
            "claude-code" => Ok(Platform::ClaudeCode),
            "cursor" => Ok(Platform::Cursor),
            "codex" => Ok(Platform::Codex),
            "all" => Ok(Platform::All),
            other => Err(format!(
                "--platform must be claude-code | cursor | codex | all, got: {other}"
            )),
        }
    }

    pub(crate) fn label(&self) -> &'static str {
        match self {
            Platform::ClaudeCode => "claude-code",
            Platform::Cursor => "cursor",
            Platform::Codex => "codex",
            Platform::All => "all",
        }
    }
}

/// Where the install lives: alongside one repository, or once for the user.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
    Project,
    User,
}

impl Scope {
    pub(crate) fn label(self) -> &'static str {
        match self {
            Scope::Project => "project",
            Scope::User => "user",
        }
    }
}

/// Which door an install opens onto the graph.
///
/// A session reaches the same store either way; what differs is what it costs
/// to get there. An MCP tool's schema is fetched before its first call, so the
/// first question costs a discovery round trip; a plain command through `Bash`
/// costs none, at the price of the assistant having to know the invocation —
/// which is exactly what the skill teaches.
///
/// Only the Claude Code install honours this: it is the one platform that gets
/// a skill, and a skill is the only thing that can teach a binary. Cursor and
/// Codex are registered as MCP servers whatever is asked for, and
/// [`install_platform`] says so rather than dropping the flag in silence.
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
#[serde(rename_all = "lowercase")]
pub enum Delivery {
    /// The skill teaches the binary; no MCP server is registered.
    Cli,
    /// Today's install: an MCP entry, and a skill that teaches its tools.
    Mcp,
    /// Both doors, and a skill that names both.
    #[default]
    Both,
}

impl Delivery {
    /// Parse a `--delivery` value.
    pub fn parse(s: &str) -> Result<Self, String> {
        match s {
            "cli" => Ok(Delivery::Cli),
            "mcp" => Ok(Delivery::Mcp),
            "both" => Ok(Delivery::Both),
            other => Err(format!("--delivery must be cli | mcp | both, got: {other}")),
        }
    }

    pub(crate) fn label(self) -> &'static str {
        match self {
            Delivery::Cli => "cli",
            Delivery::Mcp => "mcp",
            Delivery::Both => "both",
        }
    }

    /// Whether this delivery registers an MCP server.
    pub(crate) fn wires_mcp(self) -> bool {
        !matches!(self, Delivery::Cli)
    }
}

/// Options parsed from `mushroomdb install [flags]` or `mushroomdb uninstall [flags]`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InstallOpts {
    /// Which platform to wire up. `None` = auto-detect.
    pub platform: Option<Platform>,
    /// Project or user scope. `None` = auto: project inside a git checkout.
    pub scope: Option<Scope>,
    /// Database directory. `None` = use the scope default.
    pub db: Option<PathBuf>,
    /// `--command <path>`: invoke this binary instead of `npx`/the bare name.
    pub command: Option<PathBuf>,
    /// Write the `post-commit` / `post-checkout` / `post-merge` sync hooks.
    pub git_hooks: bool,
    /// Run `npx -y mushroomdb@<v> --version` once so the first real spawn is
    /// not a cold download.
    pub prewarm: bool,
    /// `--delivery cli|mcp|both`: which door the Claude Code install opens.
    pub delivery: Delivery,
    /// `--intercept-grep`: also write the experimental `PreToolUse` hook that
    /// redirects a `Grep` for a known symbol name to `explore`. Off by
    /// default — it is the one hook of ours that can block a tool call.
    pub intercept_grep: bool,
    /// `--impact-before-edit`: also write the experimental `PreToolUse` hook
    /// that puts a file's blast radius in front of an edit. Off by default.
    pub impact_before_edit: bool,
    /// `--enrich-grep`: also write the experimental `PostToolUse` hook that
    /// appends what the graph knows about the symbols a `Grep` matched. Off by
    /// default.
    pub enrich_grep: bool,
    /// `--always-load`: mark the registered server `alwaysLoad` so the host
    /// keeps its tools in context rather than deferring them. Off by default,
    /// and meaningless on a `--delivery cli` install, which registers none.
    pub always_load: bool,
}

/// Options parsed from `mushroomdb enable [flags]` or `mushroomdb disable [flags]`.
///
/// Deliberately narrower than [`InstallOpts`]: neither command takes `--db`,
/// `--command` or `--no-git-hooks` — they act on whatever an existing install
/// already recorded, not on a fresh choice of store or binary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToggleOpts {
    /// Which platform to act on. `None` = auto-detect, same as `install`.
    pub platform: Option<Platform>,
    /// Project or user scope. `None` = auto: project inside a git checkout.
    pub scope: Option<Scope>,
}

/// The store directory an install with no `--db` uses.
#[must_use]
pub fn default_db(scope: Scope, project_root: &Path, home: &Path) -> PathBuf {
    match scope {
        Scope::Project => project_root.join("mushroom-memory"),
        Scope::User => home.join(".mushroomdb").join("memory"),
    }
}

/// Whether this platform's host guarantees `--auto` resolves to this project.
///
/// Only Claude Code does. It sets `$CLAUDE_PROJECT_DIR` for both MCP servers
/// and hook processes, so the first resolution step always answers, whatever
/// working directory the process happens to have.
///
/// Cursor and Codex set no such variable. `--auto` there would rest entirely
/// on the host spawning the server inside the checkout, and if it did not,
/// resolution would fall through to `~/.mushroomdb/memory`: an empty store,
/// with the `.gitignore` line and the rules file both naming a different
/// directory, and nothing anywhere reporting an error. The assistant would
/// simply see a graph with nothing in it. So those two get the path.
///
/// The worktree argument is weaker for them in any case. `.mcp.json` and the
/// three settings hooks are Claude Code's, and they are what a `git worktree`
/// carries across; a Cursor install's committed artifact is one rules file
/// that names the store in prose.
fn resolves_at_runtime(platform: &Platform) -> bool {
    match platform {
        Platform::ClaudeCode => true,
        Platform::Cursor | Platform::Codex => false,
        // `expand_platform` never produces it; false is the safe reading.
        Platform::All => false,
    }
}

/// How each requested platform will name the store, in the order they were
/// asked for.
fn platform_stores(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    db: Option<&Path>,
    platforms: &[Platform],
) -> Vec<(Platform, StoreRef)> {
    platforms
        .iter()
        .map(|p| {
            (
                p.clone(),
                store_ref(project_root, home, scope, db, resolves_at_runtime(p)),
            )
        })
        .collect()
}

/// The summary's `store` line(s).
///
/// One line when every platform names the store the same way, which is every
/// single-platform install and most `--platform all` ones. When they differ —
/// Claude Code resolving `--auto` beside a Cursor entry that cannot — each is
/// labelled, because "which one is pinned" is exactly what a reader needs.
fn describe_stores(stores: &[(Platform, StoreRef)]) -> String {
    let all_same = stores.windows(2).all(|w| w[0].1 == w[1].1);
    match stores.first() {
        None => String::new(),
        Some((_, first)) if all_same => format!("  store  {}\n", first.describe()),
        _ => stores
            .iter()
            .map(|(p, s)| format!("  store  {}: {}\n", p.label(), s.describe()))
            .collect(),
    }
}

/// The store the *repository* wiring names: the `.gitignore` line and the
/// three git hook blocks.
///
/// `--auto` is safe here on its own terms, whatever platform asked for the
/// install: git runs a hook with the working tree it acted on as the working
/// directory, so the store resolves from that tree with no assistant, and no
/// `$CLAUDE_PROJECT_DIR`, involved. It is written when any installed platform
/// writes it, so the git hooks and the assistant's own config agree — and
/// pinned otherwise, so a Cursor-only install is one store spelled one way.
fn repo_store_ref(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    db: Option<&Path>,
    platforms: &[Platform],
) -> StoreRef {
    let runtime_ok = platforms.iter().any(resolves_at_runtime);
    store_ref(project_root, home, scope, db, runtime_ok)
}

/// How one platform will name the store in everything written for it.
///
/// `--auto` is written only where it provably resolves to the same directory:
/// the default store, in project scope, inside a git checkout, for a host that
/// resolves it (`runtime_ok`, from [`resolves_at_runtime`]). The checkout
/// condition is what makes the fallback safe — a hook that never receives
/// `$CLAUDE_PROJECT_DIR` still finds the store by walking up to the working
/// tree root, and there is no working tree root to find without it. Everywhere
/// else the path is pinned, because a wrong `--auto` would silently build a
/// second store under the home directory and report nothing.
fn store_ref(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    db: Option<&Path>,
    runtime_ok: bool,
) -> StoreRef {
    let default = default_db(scope, project_root, home);
    let Some(pinned) = db.map(|d| absolutise(d, project_root)) else {
        if runtime_ok && scope == Scope::Project && project_root.join(".git").exists() {
            return StoreRef::auto(default);
        }
        // Pinned, but `--auto` would still name this same directory in project
        // scope — so a `--auto` entry an earlier build wrote here is this
        // install's to rewrite rather than a conflicting one to refuse.
        let pinned = StoreRef::pinned(default);
        return if scope == Scope::Project {
            pinned.also_auto()
        } else {
            pinned
        };
    };
    // A `--db` naming the very store `--auto` resolves to is still pinned —
    // the user asked for a path — but an `--auto` hook from an earlier install
    // points at the same place and is this install's to replace.
    let auto_here = default_db(Scope::Project, project_root, home);
    if pinned == auto_here {
        return StoreRef::pinned(pinned).also_auto();
    }
    StoreRef::pinned(pinned)
}

/// Resolve the scope, and say whether it was inferred.
///
/// A git checkout is a project: its store belongs beside it, is ignored by the
/// repository, and its hooks fire on its commits. Anywhere else there is no
/// project to scope to, so the install is the user's.
pub(crate) fn resolve_scope(project_root: &Path, requested: Option<Scope>) -> (Scope, bool) {
    match requested {
        Some(s) => (s, false),
        None if project_root.join(".git").exists() => (Scope::Project, true),
        None => (Scope::User, true),
    }
}

// ---------------------------------------------------------------------------
// External programs
// ---------------------------------------------------------------------------

/// The world outside the two directories install is given: the programs it
/// shells out to (`codex`, `npx`) and how long it will wait for them.
///
/// Carried explicitly rather than read from the process environment at the
/// point of use, so a test can point PATH at a directory of stand-ins without
/// mutating global state that its neighbours share.
#[derive(Debug, Clone)]
pub struct Externals {
    /// PATH used to resolve external programs. `None` resolves nothing.
    pub path: Option<OsString>,
    /// Budget for the pre-warm.
    pub prewarm_timeout: Duration,
}

impl Externals {
    /// The real process environment.
    #[must_use]
    pub fn from_env() -> Self {
        Self::with_path(std::env::var_os("PATH"))
    }

    /// The same, with an explicit PATH.
    #[must_use]
    pub fn with_path(path: Option<OsString>) -> Self {
        Self {
            path,
            prewarm_timeout: Duration::from_secs(PREWARM_TIMEOUT_SECS),
        }
    }

    /// The first executable named `program` on this PATH.
    pub(crate) fn which(&self, program: &str) -> Option<PathBuf> {
        let path = self.path.as_ref()?;
        std::env::split_paths(path)
            .map(|dir| dir.join(program))
            .find(|c| is_executable(c))
    }
}

fn is_executable(path: &Path) -> bool {
    let Ok(meta) = fs::metadata(path) else {
        return false;
    };
    if !meta.is_file() {
        return false;
    }
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        meta.permissions().mode() & 0o111 != 0
    }
    #[cfg(not(unix))]
    {
        true
    }
}

/// Run `bin` to completion, returning its stderr (trimmed) on a non-zero exit.
fn run_and_capture(bin: &Path, args: &[String]) -> Result<(), String> {
    let out = std::process::Command::new(bin)
        .args(args)
        .output()
        .map_err(|e| format!("cannot run {}: {e}", bin.display()))?;
    if out.status.success() {
        return Ok(());
    }
    let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
    let detail = if stderr.is_empty() {
        String::new()
    } else {
        format!(": {stderr}")
    };
    Err(format!(
        "{} {} exited with {}{detail}",
        bin.display(),
        args.join(" "),
        out.status
    ))
}

/// Run `bin`, giving up after `timeout`. Output is discarded — only the exit
/// status matters — so the child cannot block on a pipe nobody drains.
fn run_with_timeout(bin: &Path, args: &[String], timeout: Duration) -> Result<(), String> {
    let mut child = std::process::Command::new(bin)
        .args(args)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map_err(|e| format!("cannot run {}: {e}", bin.display()))?;
    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait() {
            Ok(Some(status)) if status.success() => return Ok(()),
            Ok(Some(status)) => return Err(format!("exited with {status}")),
            Ok(None) => {}
            Err(e) => return Err(format!("cannot wait for {}: {e}", bin.display())),
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            return Err(format!("timed out after {}s", timeout.as_secs()));
        }
        std::thread::sleep(Duration::from_millis(25));
    }
}

/// Run `bin`, capturing stdout and giving up after `timeout`.
///
/// The pipe is drained on another thread so a child that writes more than a
/// pipe buffer cannot deadlock against the timeout loop watching it.
fn capture_with_timeout(bin: &Path, args: &[String], timeout: Duration) -> Result<String, String> {
    let mut child = std::process::Command::new(bin)
        .args(args)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map_err(|e| format!("cannot run {}: {e}", bin.display()))?;
    let mut stdout = child.stdout.take().expect("stdout is piped");
    let (tx, rx) = std::sync::mpsc::channel::<String>();
    std::thread::spawn(move || {
        use std::io::Read as _;
        let mut out = String::new();
        let _ = stdout.read_to_string(&mut out);
        let _ = tx.send(out);
    });
    let deadline = Instant::now() + timeout;
    loop {
        match child.try_wait() {
            Ok(Some(status)) if status.success() => {
                return Ok(rx.recv_timeout(Duration::from_secs(1)).unwrap_or_default());
            }
            Ok(Some(status)) => return Err(format!("exited with {status}")),
            Ok(None) if Instant::now() >= deadline => {
                let _ = child.kill();
                let _ = child.wait();
                return Err(format!("timed out after {}s", timeout.as_secs()));
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(25)),
            Err(e) => return Err(format!("cannot wait for {}: {e}", bin.display())),
        }
    }
}

/// Ask the published package where something of its own is, once.
///
/// `flag` is [`PRINT_BINARY_FLAG`] or [`PRINT_LAUNCHER_FLAG`]; the package
/// answers with an absolute path and exits. Writing that path into the hooks
/// takes the whole npx resolution — cache check, version resolve, an extra Node
/// process — off the per-prompt and per-edit path.
///
/// Chosen over `npm root -g` (only finds a *global* install, which the npx
/// route never makes) and over `npm exec --offline` (still pays npm's own
/// startup on every call). Asking the package itself is the one answer that is
/// correct for however it was installed, and it is the same fetch the pre-warm
/// already ran, so it costs an install nothing extra.
///
/// Every failure is recoverable: the caller falls back a step.
fn ask_package(version: &str, flag: &str, ext: &Externals) -> Result<PathBuf, String> {
    let npx = ext
        .which("npx")
        .ok_or_else(|| "npx is not on PATH".to_string())?;
    let args = vec![
        "-y".to_string(),
        format!("{NPM_PACKAGE}@{version}"),
        flag.to_string(),
    ];
    let out = capture_with_timeout(&npx, &args, ext.prewarm_timeout)?;
    // The last non-blank line: npm is entitled to print notices before it.
    let path = out
        .lines()
        .map(str::trim)
        .rfind(|l| !l.is_empty())
        .ok_or_else(|| format!("{NPM_PACKAGE}@{version} {flag} printed nothing"))?;
    let path = PathBuf::from(path);
    if !path.is_absolute() {
        return Err(format!("{} is not an absolute path", path.display()));
    }
    if !path.is_file() {
        return Err(format!("{} does not exist", path.display()));
    }
    Ok(path)
}

/// Turn an `npx` command into a resolved, directly-runnable one, so the hooks
/// it writes do not spawn `npx` on every invocation.
///
/// Three rungs, best first:
///
/// 1. **The native binary** (`--print-binary`). What every other form ends up
///    running anyway, reached without a Node startup in front of it.
/// 2. **`node <launcher>`** (`--print-launcher`). For a package whose vendored
///    binary was never fetched, and only when `node` is on PATH to run it.
/// 3. **`npx`**, unchanged, with a warning saying the hooks will be slow.
///
/// Returns the command to write; the one-line warning for the summary when
/// every rung failed; and whether the package was fetched on the way, which
/// tells the caller the separate pre-warm has nothing left to do. Anything
/// other than the `npx` form is already a direct path and is handed back
/// untouched.
fn resolve_fast_command(cmd: &McpCommand, ext: &Externals) -> (McpCommand, Option<String>, bool) {
    let McpCommand::Npx { version } = cmd else {
        return (cmd.clone(), None, false);
    };
    // Asking the package anything downloads it first, so one question warms
    // the cache exactly as the pre-warm's `--version` would. If `npx` is not
    // there to ask, nothing was fetched and the pre-warm's own report of that
    // is worth having.
    let fetched = ext.which("npx").is_some();
    let binary_err = match ask_package(version, PRINT_BINARY_FLAG, ext) {
        Ok(binary) => {
            return (
                McpCommand::NativeBinary {
                    binary,
                    version: version.clone(),
                },
                None,
                fetched,
            )
        }
        Err(e) => e,
    };
    // No binary. The launcher is the same package one Node startup away, and
    // it is only worth writing if `node` is there to run it.
    if ext.which(NODE_BIN).is_some() {
        if let Ok(launcher) = ask_package(version, PRINT_LAUNCHER_FLAG, ext) {
            return (
                McpCommand::NodeLauncher {
                    launcher,
                    version: version.clone(),
                },
                None,
                fetched,
            );
        }
    }
    (
        cmd.clone(),
        Some(format!(
            "warning: could not resolve {NPM_PACKAGE}@{version} to a path ({binary_err}) — \
             the hooks will spawn npx on every prompt and every edit"
        )),
        fetched,
    )
}

// ---------------------------------------------------------------------------
// Manifest — tracks everything install wrote so uninstall can undo it.
// ---------------------------------------------------------------------------

#[derive(Serialize, Deserialize, Default, Debug)]
struct Manifest {
    /// Files created by this install (absolute paths).
    files: Vec<PathBuf>,
    /// MCP JSON keys added by this install.
    mcp_keys: Vec<ManagedMcpKey>,
    /// Hook entries added to a settings.json by this install.
    #[serde(default)]
    hooks: Vec<ManagedHook>,
    /// Git hook files this install put its block into.
    #[serde(default)]
    git_hooks: Vec<PathBuf>,
    /// Single lines added to a file the user owns (the `.gitignore` entry).
    #[serde(default)]
    gitignore: Vec<ManagedLine>,
    /// Whether a Codex MCP server was registered through the `codex` CLI.
    #[serde(default)]
    codex: bool,
    /// Whether `disable` has turned this install off. The tracking fields
    /// above (`mcp_keys`, `hooks`, `git_hooks`, `codex`) still describe what
    /// the install owns even while disabled — `disable` does not clear them,
    /// it only takes the config off disk and sets this flag — so `uninstall`
    /// needs no disabled-aware branch of its own: every removal it attempts
    /// is already a no-op for whatever `disable` already removed.
    #[serde(default)]
    disabled: bool,
    /// The exact `mcpServers.mushroomdb` entry `disable` removed from each
    /// file, captured byte-for-byte before the removal. `enable` reads the
    /// store argument back out of these (see [`store_from_arg`]) rather than
    /// replaying the entry itself — the command it writes is re-resolved
    /// fresh, since the published package may have moved since `disable` ran.
    #[serde(default)]
    stashed_mcp: Vec<StashedMcpEntry>,
    /// The command `install` (or the last successful `enable`) was asked to
    /// write, *before* [`resolve_fast_command`] turned an `Npx` request into a
    /// concrete native-binary or launcher path. `enable` reads this back so it
    /// can tell an explicit `--command` pin apart from an `npx` resolution
    /// that happened to land on the same shape of value (an absolute path) —
    /// something the resolved JSON entry alone cannot distinguish. `None` only
    /// for a manifest written before this field existed.
    #[serde(default)]
    requested_cmd: Option<StoredCommand>,
    /// The door this install opened. `doctor` reads it so it does not report a
    /// missing MCP entry as a failure on an install that deliberately has
    /// none, and `enable` reads it so a re-enable rebuilds the same shape of
    /// install rather than silently adding a server. Defaults to `Both`, which
    /// is what every manifest written before this field existed described.
    #[serde(default)]
    delivery: Delivery,
    /// Whether this install asked for the experimental grep redirect. The
    /// hook itself is listed in `hooks` like any other, so `uninstall` and
    /// `disable` need nothing from this field; `enable` reads it to rebuild
    /// the same install that was disabled, and `doctor` to know whether a
    /// missing `PreToolUse` hook is a fault or the default. Defaults to
    /// false, which is what every manifest written before it existed means.
    #[serde(default)]
    intercept_grep: bool,
    /// Whether this install asked for the pre-edit impact hook. Read for the
    /// same three reasons as `intercept_grep`, and defaulted the same way.
    #[serde(default)]
    impact_before_edit: bool,
    /// Whether this install asked for the grep enrichment hook.
    #[serde(default)]
    enrich_grep: bool,
    /// Whether the registered server entry carries `alwaysLoad`. The key lives
    /// in the MCP JSON, which `uninstall` removes whole, so nothing needs this
    /// to undo it; `enable` reads it to put the same entry back, and `doctor`
    /// to report it.
    #[serde(default)]
    always_load: bool,
}

impl Manifest {
    /// Drop entries no version of this install may act on as written. See
    /// [`load_manifest`] for why a `.gitignore` in `files` is one of them.
    fn sanitised(mut self) -> Self {
        self.files
            .retain(|f| f.file_name() != Some(OsStr::new(".gitignore")));
        self
    }

    fn is_empty(&self) -> bool {
        self.files.is_empty()
            && self.mcp_keys.is_empty()
            && self.hooks.is_empty()
            && self.git_hooks.is_empty()
            && self.gitignore.is_empty()
            && !self.codex
    }
}

/// One `mcpServers.<server>` entry [`run_disable_with`] took out of a config
/// file, kept whole so [`entry_db`] can still read the store argument back out
/// of it later.
#[derive(Serialize, Deserialize, Debug, Clone)]
struct StashedMcpEntry {
    /// The JSON file the entry was removed from (absolute path).
    file: PathBuf,
    /// The key inside `mcpServers`.
    server: String,
    /// The entry itself, exactly as it read before removal.
    entry: serde_json::Value,
}

/// The three requestable shapes of [`McpCommand`] — the ones a caller can ask
/// for, as opposed to [`McpCommand::NativeBinary`]/[`McpCommand::NodeLauncher`],
/// which only [`resolve_fast_command`] ever produces, by resolving an `Npx`
/// request. Serializable so a manifest can carry it across a `disable`/`enable`
/// round trip.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
enum StoredCommand {
    Npx { version: String },
    Explicit(PathBuf),
    OnPath,
}

impl StoredCommand {
    /// The request behind `cmd`, or `None` for a value only resolution
    /// produces — there is nothing to remember about those beyond the `Npx`
    /// request that led to them, which is captured before resolution runs.
    fn from_mcp(cmd: &McpCommand) -> Option<Self> {
        match cmd {
            McpCommand::Npx { version } => Some(StoredCommand::Npx {
                version: version.clone(),
            }),
            McpCommand::Explicit(p) => Some(StoredCommand::Explicit(p.clone())),
            McpCommand::OnPath => Some(StoredCommand::OnPath),
            McpCommand::NativeBinary { .. } | McpCommand::NodeLauncher { .. } => None,
        }
    }

    fn into_mcp(self) -> McpCommand {
        match self {
            StoredCommand::Npx { version } => McpCommand::Npx { version },
            StoredCommand::Explicit(p) => McpCommand::Explicit(p),
            StoredCommand::OnPath => McpCommand::OnPath,
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
struct ManagedMcpKey {
    /// The JSON file the key was added to (absolute path).
    file: PathBuf,
    /// The key inside `mcpServers`.
    server: String,
}

#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
struct ManagedHook {
    /// The settings.json file the hook was added to (absolute path).
    file: PathBuf,
    /// The hook event name (e.g. `UserPromptSubmit`).
    event: String,
    /// The exact command string that was added.
    command: String,
}

/// One line this install appended to a text file the user owns.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
struct ManagedLine {
    /// The file the line was added to (absolute path).
    file: PathBuf,
    /// The exact line, without its newline.
    line: String,
    /// Whether the file itself did not exist before this install. Only such a
    /// file may be deleted on uninstall, and only if nothing is left in it.
    #[serde(default)]
    created: bool,
}

/// Claude Code hook event this install wires: fires before each prompt is
/// sent, so the recall digest lands as context ahead of the user's turn.
pub(crate) const HOOK_EVENT: &str = "UserPromptSubmit";
/// Kept short: the hook must never noticeably slow a prompt.
const HOOK_TIMEOUT_SECS: u64 = 5;

/// The second hook event: fires after a tool call, so an edit reaches the
/// graph while the assistant is still working rather than at the next commit.
pub(crate) const TOUCH_EVENT: &str = "PostToolUse";
/// The tools that change a file on disk. Anything else — a read, a search, a
/// shell command — leaves the working tree as the graph already has it.
const TOUCH_MATCHER: &str = "Edit|Write|MultiEdit";
/// Longer than the prompt hook's: re-extracting a file costs more than reading
/// a digest, and nothing is waiting on the answer. The run is `async`, so this
/// bounds a background process rather than the assistant's turn.
const TOUCH_TIMEOUT_SECS: u64 = 30;

/// The third hook event: fires once as a session opens, so the assistant knows
/// what the repository is before it is asked anything.
///
/// No matcher — a session start is not a tool call — and not `async`: the
/// point of the brief is to be there for the first turn, and the host caches
/// its output for the rest of the session, so it is read once and paid for
/// once. It shares the prompt hook's [`HOOK_TIMEOUT_SECS`] budget.
pub(crate) const BRIEF_EVENT: &str = "SessionStart";

/// The optional fourth hook event: fires *before* a tool call, so a search the
/// graph answers exactly can be turned into an `explore` before it runs.
///
/// Written only for `install --intercept-grep` (see
/// [`InstallOpts::intercept_grep`]). It is the one hook of ours that can block
/// a tool call — Claude Code reads exit 2 as "refuse this call, and give the
/// model what stderr said" — so it is opt-in, awaited rather than `async`
/// (nothing else could block the call), and on the prompt hook's short
/// [`HOOK_TIMEOUT_SECS`] budget.
pub(crate) const INTERCEPT_EVENT: &str = "PreToolUse";

/// The one tool it fires for. A `Read`, an `Edit` or a `Bash` is never
/// redirected: the graph has no better answer to those.
const INTERCEPT_MATCHER: &str = "Grep";

/// The optional fifth hook: the blast radius of a file, in front of the edit
/// that is about to change it.
///
/// Written only for `install --impact-before-edit`. It shares `PreToolUse`
/// with the redirect but is a different group, matched to the editing tools
/// rather than to `Grep`, so the two are independent: each is recognised by
/// its own subcommand word (see [`is_our_hook_command`]) and turning one off
/// leaves the other alone. It never blocks — it prints one
/// `hookSpecificOutput` object with `additionalContext` and exits 0 — but it
/// is awaited, because context that arrives after the edit is context nobody
/// read.
pub(crate) const IMPACT_EVENT: &str = "PreToolUse";

/// The tools it fires for: the ones that change a file, the same set
/// [`TOUCH_MATCHER`] names.
const IMPACT_MATCHER: &str = TOUCH_MATCHER;

/// The optional sixth hook: what the graph knows about the symbols a `Grep`
/// just matched, appended to the result.
///
/// Written only for `install --enrich-grep`. It shares `PostToolUse` with the
/// `touch` re-extraction and, like the impact hook, is a separate group with
/// its own matcher and its own subcommand word. Awaited on the short budget:
/// the facts have to reach the transcript with the tool result, and an `async`
/// hook's output arrives too late to be part of it.
pub(crate) const ENRICH_EVENT: &str = "PostToolUse";

/// The one tool it fires for.
const ENRICH_MATCHER: &str = "Grep";

/// Single-quote `s` for embedding in a POSIX shell command line, escaping
/// embedded single quotes as `'\''`. Claude Code runs a `type: "command"`
/// hook through a shell, so an unquoted path containing whitespace or shell
/// metacharacters is word-split and the hook silently receives the wrong
/// arguments — quoting keeps the command exact.
pub(crate) fn sh_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', r"'\''"))
}

/// The exact command string written into a hook entry: the resolved binary,
/// the subcommand that is that hook's body, and the store. Both outer halves
/// arrive already quoted where quoting is needed.
///
/// One function for all six hooks, because the shape is the thing every other
/// part of the installer depends on: [`is_our_hook_command`] recognises a hook
/// of ours by exactly this tail, and a second spelling of the same line would
/// be a hook nothing could later find to replace or remove.
fn hook_command(shell: &str, sub: &str, store: &StoreRef) -> String {
    format!("{shell} {sub} {}", store.shell_arg())
}

/// One `hooks.<event>` array entry in Claude Code's settings.json shape, for a
/// hook that fires on every occurrence of its event.
///
/// `SessionStart` and `UserPromptSubmit` are not tool calls, so there is
/// nothing to match on and the key is left out entirely — an empty `matcher`
/// is not the same as no matcher.
fn hook_entry(command: &str) -> serde_json::Value {
    serde_json::json!({ "hooks": [ { "type": "command", "command": command, "timeout": HOOK_TIMEOUT_SECS } ] })
}

/// One `hooks.<event>` array entry matched to a set of tools.
///
/// Four of our hooks are this shape and differ only in three values, so they
/// share one builder: two events hold two hooks of ours each (`PreToolUse` has
/// the redirect and the impact hook, `PostToolUse` has `touch` and the grep
/// enrichment), and what keeps each pair apart on disk is the matcher plus the
/// subcommand inside `command`.
///
/// `async` is written only when asked for, because the key's *absence* is what
/// makes a hook awaited, and every hook here but `touch` has to be: a hook
/// that decides after the tool call has gone through has decided nothing, and
/// context that arrives after the edit is context nobody read. `touch` is the
/// exception — nothing waits on a re-extraction — and pays for it with the
/// longer [`TOUCH_TIMEOUT_SECS`] budget.
fn matched_hook_entry(
    matcher: &str,
    command: &str,
    timeout: u64,
    run_async: bool,
) -> serde_json::Value {
    let mut hook = serde_json::json!({
        "type": "command",
        "command": command,
        "timeout": timeout,
    });
    if run_async {
        hook["async"] = serde_json::Value::Bool(true);
    }
    serde_json::json!({ "matcher": matcher, "hooks": [hook] })
}

/// True if any hook group under `event` contains a command hook equal to `command`.
pub(crate) fn settings_has_hook(root: &serde_json::Value, event: &str, command: &str) -> bool {
    root["hooks"][event]
        .as_array()
        .map(|groups| {
            groups.iter().any(|g| {
                g["hooks"]
                    .as_array()
                    .map(|hs| hs.iter().any(|h| h["command"] == command))
                    .unwrap_or(false)
            })
        })
        .unwrap_or(false)
}

/// Add one hook to `settings_file` (created if absent). Idempotent: no-op if
/// `command` is already present under `event`. Every other key in the file —
/// including other hook events and groups — is preserved. Errors out (no
/// write) rather than overwriting if `hooks` or `hooks.<event>` already exists
/// with an unexpected JSON type, or if the file's top level is not a JSON
/// object.
///
/// `entry` is the group to append, built by the caller: the two events this
/// install wires want different shapes, and only the caller knows which.
fn merge_hook_entry(
    settings_file: &Path,
    event: &str,
    command: &str,
    entry: serde_json::Value,
    manifest: &mut Manifest,
) -> Result<(), CliError> {
    let mut root: serde_json::Value = if settings_file.exists() {
        let raw = fs::read_to_string(settings_file)
            .map_err(|e| CliError(format!("cannot read {}: {e}", settings_file.display())))?;
        serde_json::from_str(&raw)
            .map_err(|e| CliError(format!("invalid JSON in {}: {e}", settings_file.display())))?
    } else {
        serde_json::json!({})
    };

    if !root.is_object() {
        return Err(CliError(format!(
            "{} is not a JSON object at its top level — refusing to add a hook",
            settings_file.display()
        )));
    }

    if settings_has_hook(&root, event, command) {
        return Ok(());
    }

    // Validate the shapes we are about to write into before touching
    // anything: a wrong-shaped `hooks` or `hooks.<event>` value belongs to
    // the user (or another tool) and must never be silently overwritten.
    match root.get("hooks") {
        None => root["hooks"] = serde_json::json!({}),
        Some(v) if v.is_object() => {}
        Some(_) => {
            return Err(CliError(format!(
                "{}: \"hooks\" is not a JSON object — refusing to overwrite it",
                settings_file.display()
            )));
        }
    }
    match root["hooks"].get(event) {
        None => root["hooks"][event] = serde_json::json!([]),
        Some(v) if v.is_array() => {}
        Some(_) => {
            return Err(CliError(format!(
                "{}: \"hooks.{event}\" is not a JSON array — refusing to overwrite it",
                settings_file.display()
            )));
        }
    }
    root["hooks"][event].as_array_mut().unwrap().push(entry);

    let parent = settings_file.parent().unwrap_or(Path::new("."));
    fs::create_dir_all(parent)
        .map_err(|e| CliError(format!("cannot create {}: {e}", parent.display())))?;
    let json = serde_json::to_string_pretty(&root)
        .map_err(|e| CliError(format!("cannot serialize settings: {e}")))?;
    fs::write(settings_file, json)
        .map_err(|e| CliError(format!("cannot write {}: {e}", settings_file.display())))?;

    manifest.hooks.push(ManagedHook {
        file: settings_file.to_path_buf(),
        event: event.into(),
        command: command.into(),
    });
    Ok(())
}

/// Remove exactly the hook groups whose only command is `command`; drop the
/// command from mixed groups; leave everything else semantically unchanged.
/// Returns whether the file was rewritten — that is, whether the hook was
/// there to remove at all.
fn remove_hook_entry(settings_file: &Path, event: &str, command: &str) -> Result<bool, CliError> {
    drop_hooks(settings_file, event, |c| c == command)
}

/// Whether `command` is one of our hook bodies for `store`, whatever binary it
/// names.
///
/// The command prefix is exactly what changes between versions — 0.5.x wrote
/// the absolute path of a copied binary, 0.6.0 an `npx` pin, 0.6.1 a resolved
/// `node <launcher>`, a developer's `--command` a build path — so identity is
/// the tail: the subcommand and the store this install is wiring. Both
/// spellings of that store count, since `--auto` replaced a written path in
/// 0.6.1 and a hook left behind in the other spelling would run alongside the
/// new one. A hook naming a *different* store belongs to a different install
/// and is not ours to touch.
pub(crate) fn is_our_hook_command(command: &str, sub: &str, store: &StoreRef) -> bool {
    store
        .hook_tails(sub)
        .iter()
        .any(|tail| command.ends_with(tail))
}

/// The same identity test for a line that does not *end* with the invocation:
/// a git hook block backgrounds it and redirects its output, so the store
/// argument sits in the middle of the line rather than at the end of it.
pub(crate) fn line_runs_for_store(line: &str, sub: &str, store: &StoreRef) -> bool {
    store.hook_tails(sub).iter().any(|tail| line.contains(tail))
}

/// Take out every hook of ours for `event` that is not the one we are about
/// to write. Returns whether anything was removed.
///
/// Without this an upgrade appends: `merge_hook_entry` matches on the exact
/// command string, so a 0.5.x entry naming `~/.mushroomdb/bin/mushroomdb` is
/// not recognised, survives, and keeps running alongside the new one — two
/// recall digests injected on every prompt.
fn remove_stale_hooks(
    settings_file: &Path,
    event: &str,
    sub: &str,
    store: &StoreRef,
    desired: &str,
) -> Result<bool, CliError> {
    drop_hooks(settings_file, event, |c| {
        c != desired && is_our_hook_command(c, sub, store)
    })
}

/// Drop every hook under `event` whose command satisfies `drop_it`, pruning
/// groups that end up empty. Returns whether the file was rewritten.
///
/// Reads `hooks.<event>` through immutable accessors first, so a settings
/// file where the user removed the `hooks` key (or `<event>`, or shaped
/// either as something other than an object/array) is left byte-for-byte
/// untouched rather than having a stray `null` written back in. Every other
/// key is preserved, though the file is re-serialized (comments are not
/// supported since `serde_json` is strict JSON).
fn drop_hooks(
    settings_file: &Path,
    event: &str,
    drop_it: impl Fn(&str) -> bool,
) -> Result<bool, CliError> {
    if !settings_file.exists() {
        return Ok(false);
    }
    let raw = fs::read_to_string(settings_file)
        .map_err(|e| CliError(format!("cannot read {}: {e}", settings_file.display())))?;
    let mut root: serde_json::Value = serde_json::from_str(&raw).map_err(|e| {
        CliError(format!(
            "corrupt settings json at {}: {e}",
            settings_file.display()
        ))
    })?;

    let Some(mut groups) = root
        .get("hooks")
        .and_then(|h| h.get(event))
        .and_then(|g| g.as_array())
        .cloned()
    else {
        // No matching (or well-shaped) event array — nothing of ours to
        // remove; leave the file exactly as it is, no write at all.
        return Ok(false);
    };

    for g in groups.iter_mut() {
        if let Some(hs) = g["hooks"].as_array_mut() {
            hs.retain(|h| !h["command"].as_str().is_some_and(&drop_it));
        }
    }
    groups.retain(|g| {
        g["hooks"]
            .as_array()
            .map(|hs| !hs.is_empty())
            .unwrap_or(true)
    });

    let before = root.clone();
    if groups.is_empty() {
        root["hooks"].as_object_mut().unwrap().remove(event);
    } else {
        root["hooks"][event] = serde_json::Value::Array(groups);
    }
    if root == before {
        // The event array held none of our commands, so there is nothing to
        // remove. Writing anyway would re-serialize a file we do not own —
        // `serde_json` is built without `preserve_order`, so the user's key
        // order and indentation would be rewritten for no reason.
        return Ok(false);
    }

    let json = serde_json::to_string_pretty(&root)
        .map_err(|e| CliError(format!("cannot serialize settings: {e}")))?;
    fs::write(settings_file, json)
        .map_err(|e| CliError(format!("cannot write {}: {e}", settings_file.display())))?;
    Ok(true)
}

// ---------------------------------------------------------------------------
// Public entry points
// ---------------------------------------------------------------------------

/// Everything the write phase needs, gathered once so the per-step functions
/// stay readable.
struct Ctx<'a> {
    project_root: &'a Path,
    home: &'a Path,
    scope: Scope,
    /// The store the repository wiring names — the `.gitignore` line and the
    /// git hook blocks. Each platform's own config gets its own [`StoreRef`],
    /// passed to the per-platform writers, because only Claude Code can
    /// resolve `--auto`; see [`repo_store_ref`] and [`resolves_at_runtime`].
    repo_store: &'a StoreRef,
    cmd: &'a McpCommand,
    ext: &'a Externals,
    git_hooks: bool,
    prewarm: bool,
    /// Which door to open — see [`Delivery`]. Read by [`install_claude_code`],
    /// which is the only writer it changes.
    delivery: Delivery,
    /// Whether to write the experimental grep redirect. Claude Code only —
    /// it is a Claude Code hook.
    intercept_grep: bool,
    /// Whether to write the experimental pre-edit impact hook. Claude Code
    /// only, for the same reason.
    impact_before_edit: bool,
    /// Whether to write the experimental grep enrichment hook. Claude Code
    /// only, for the same reason.
    enrich_grep: bool,
    /// Whether the server entry this install writes carries `alwaysLoad`.
    /// Claude Code's `.mcp.json` only: it is a Claude Code key, and a Cursor
    /// or Codex registration has no equivalent to set.
    always_load: bool,
}

/// Anchor a user-supplied path to `base` when it is relative, and drop any
/// `./` segments.
///
/// A relative `--command` or `--db` is convenient to type and wrong to store:
/// the assistant spawns the MCP server, and the hooks and git hooks run, from
/// whatever directory those processes happen to be in, not the one the install
/// was typed in. Nothing is canonicalized — resolving symlinks would rewrite
/// a path the user chose deliberately.
fn absolutise(path: &Path, base: &Path) -> PathBuf {
    let joined = if path.is_absolute() {
        path.to_path_buf()
    } else {
        base.join(path)
    };
    let mut out = PathBuf::new();
    for c in joined.components() {
        match c {
            std::path::Component::CurDir => {}
            other => out.push(other),
        }
    }
    out
}

/// Whether `p` is a program name to be looked up on PATH rather than a file to
/// be anchored: one plain component, no separator, no `.` or `..`.
///
/// `--command mushroomdb` means "whatever `mushroomdb` PATH resolves to" and
/// stays that way in both forms we write — an MCP host resolves a bare
/// `command` on PATH, and quoting a bare name in a shell does not defeat the
/// lookup either. Anchoring it would invent `<cwd>/mushroomdb`, a file that
/// need not exist, and the install would report success over a server that
/// cannot spawn.
fn is_bare_program_name(p: &Path) -> bool {
    let mut components = p.components();
    matches!(
        (components.next(), components.next()),
        (Some(std::path::Component::Normal(_)), None)
    )
}

/// Anchor a `--command` unless it is a bare program name.
fn absolutise_command(path: &Path, base: &Path) -> PathBuf {
    if is_bare_program_name(path) {
        path.to_path_buf()
    } else {
        absolutise(path, base)
    }
}

/// Install the /mushroom skill and MCP server entry for the resolved platforms.
///
/// `project_root` is the directory where project-scope config files live
/// (`.mcp.json`, `.claude/`, `.cursor/`). `home` is the user HOME directory.
/// Tests pass temp directories for both; main.rs passes real values.
pub fn run_install(
    project_root: &Path,
    home: &Path,
    opts: &InstallOpts,
) -> Result<String, CliError> {
    run_install_with(
        project_root,
        home,
        opts,
        &detect_mcp_command(opts.command.as_deref()),
        &Externals::from_env(),
    )
}

/// Like [`run_install`], but with the server command and the external
/// environment supplied by the caller instead of detected. Tests use this to
/// stay deterministic and offline; `run_install` is the real-environment
/// wrapper.
pub fn run_install_with(
    project_root: &Path,
    home: &Path,
    opts: &InstallOpts,
    cmd: &McpCommand,
    ext: &Externals,
) -> Result<String, CliError> {
    let (scope, auto_scope) = resolve_scope(project_root, opts.scope);
    // Whatever the caller handed us, what gets written resolves from anywhere:
    // an absolute path, or a name PATH answers for.
    let cmd = match cmd {
        McpCommand::Explicit(p) => McpCommand::Explicit(absolutise_command(p, project_root)),
        other => other.clone(),
    };
    // What was actually asked for, before resolution turns an `Npx` request
    // into a concrete path — `enable` reads this back later to tell an
    // explicit `--command` pin apart from a resolved `npx` path, which the
    // written JSON entry alone cannot distinguish (both are absolute paths).
    let requested_cmd = StoredCommand::from_mcp(&cmd);
    // Resolve the published package to a concrete launcher once, here, so no
    // hook has to. Skipped by `--no-prewarm`, which is the flag for "do not
    // reach the network during this install"; the `npx` form still works, it
    // is just slower on every invocation.
    let (cmd, launcher_note, package_fetched) = if opts.prewarm {
        resolve_fast_command(&cmd, ext)
    } else {
        (cmd, None, false)
    };
    let cmd = &cmd;

    let resolved = resolve_platform(project_root, home, opts.platform.as_ref())?;
    let platforms = expand_platform(&resolved);

    // Each platform names the store in its own terms: only Claude Code can be
    // relied on to resolve `--auto`. The repository wiring gets its own, since
    // git resolves it without any assistant.
    let stores = platform_stores(project_root, home, scope, opts.db.as_deref(), &platforms);
    let repo_store = repo_store_ref(project_root, home, scope, opts.db.as_deref(), &platforms);

    // Check for anything that would make this install fail halfway before
    // writing a single byte.
    for (plat, store) in &stores {
        preflight_check(project_root, home, plat, scope, store, ext)?;
    }

    let ctx = Ctx {
        project_root,
        home,
        scope,
        repo_store: &repo_store,
        cmd,
        ext,
        git_hooks: opts.git_hooks,
        prewarm: opts.prewarm && !package_fetched,
        delivery: opts.delivery,
        intercept_grep: opts.intercept_grep,
        impact_before_edit: opts.impact_before_edit,
        enrich_grep: opts.enrich_grep,
        always_load: opts.always_load,
    };

    let manifest_path = manifest_path(project_root, home, scope, &platforms);

    // Load the existing manifest so we can union it with what this run writes.
    // This covers partial-drift re-installs: if SKILL.md was edited but the MCP
    // entry is still intact, only the file is re-written this run; unioning
    // preserves the MCP key in the saved manifest so uninstall cleans it up too.
    let existing = load_manifest(&manifest_path);
    // `install` doubles as `enable` for a disabled install: it rewrites
    // everything `disable` took off disk the same as it would repair any
    // other drift, so the only extra step is clearing the flag once that
    // write lands, and saying so in the summary.
    let was_disabled = existing.disabled;
    // Turning an experiment off writes nothing new, so the manifest would
    // otherwise go on claiming a hook — or an `alwaysLoad` key — this run just
    // removed.
    let doors_changed = existing.intercept_grep != opts.intercept_grep
        || existing.impact_before_edit != opts.impact_before_edit
        || existing.enrich_grep != opts.enrich_grep
        || existing.always_load != opts.always_load;

    let mut manifest = Manifest {
        requested_cmd,
        delivery: opts.delivery,
        intercept_grep: opts.intercept_grep,
        impact_before_edit: opts.impact_before_edit,
        enrich_grep: opts.enrich_grep,
        always_load: opts.always_load,
        ..Manifest::default()
    };
    let mut notes: Vec<String> = Vec::new();
    notes.extend(launcher_note);
    if was_disabled {
        notes.push("this install was disabled — install re-enabled it".to_string());
    }
    // Deprecated in 0.6.4, removed in 0.7. The hook still installs and still
    // works; the person who asked for it is told once, by the command they ran.
    for (on, flag) in [
        (opts.intercept_grep, "--intercept-grep"),
        (opts.impact_before_edit, "--impact-before-edit"),
        (opts.enrich_grep, "--enrich-grep"),
    ] {
        if on {
            notes.push(format!(
                "deprecated  {flag} — the code-graph hooks are deprecated and are removed in 0.7"
            ));
        }
    }

    let outcome = write_everything(&ctx, &stores, &mut manifest, &mut notes);
    if let Err(e) = outcome {
        // Persist whatever was already written (an earlier platform's files,
        // a git hook) so uninstall can still clean up after a partial
        // failure. Best effort: the original error wins.
        if !manifest.is_empty() {
            let merged = union_manifests(load_manifest(&manifest_path), &manifest);
            let _ = write_manifest(&manifest_path, &merged);
        }
        return Err(e);
    }

    let anything_written = !manifest.is_empty();
    if anything_written || was_disabled || doors_changed {
        // Union this-run entries with the existing manifest (dedup by path/key).
        let mut merged = if anything_written {
            union_manifests(existing, &manifest)
        } else {
            existing
        };
        if was_disabled {
            merged.disabled = false;
            merged.stashed_mcp.clear();
        }
        // Re-installing as `cli` over an earlier install just took that
        // install's server entry off disk; the manifest must not go on
        // claiming a key that is no longer there.
        if !opts.delivery.wires_mcp() {
            merged.mcp_keys.retain(|k| has_our_server(&k.file));
        }
        // Same for each experiment: an install without the flag has just taken
        // that hook off disk, so the manifest must stop owning it.
        //
        // Matched with [`is_our_hook_command`], the same predicate the removal
        // itself used — not on the event, because the three opt-in hooks share
        // two events between them and with `touch`, and not on the subcommand
        // word alone, because a `--db` or `--command` path may contain it (a
        // store at `~/my enrich tools/memory` would otherwise make the prune
        // drop every hook it owns). Matching the whole ` <sub> <store>` tail
        // can only ever be true of the hook that is actually going away.
        merged.intercept_grep = opts.intercept_grep;
        merged.impact_before_edit = opts.impact_before_edit;
        merged.enrich_grep = opts.enrich_grep;
        merged.always_load = opts.always_load;
        for (on, sub) in [
            (opts.intercept_grep, "intercept"),
            (opts.impact_before_edit, "impact-hook"),
            (opts.enrich_grep, "enrich"),
        ] {
            if !on {
                merged.hooks.retain(|h| {
                    !stores
                        .iter()
                        .any(|(_, store)| is_our_hook_command(&h.command, sub, store))
                });
            }
        }
        write_manifest(&manifest_path, &merged)?;
    }

    let labels: Vec<&str> = platforms.iter().map(Platform::label).collect();
    let mut out = format!("mushroomdb installed ({})\n", labels.join(", "));
    out.push_str(&format!(
        "  scope  {}{}\n",
        scope.label(),
        if auto_scope { " (auto-detected)" } else { "" }
    ));
    for f in &manifest.files {
        out.push_str(&format!("  wrote  {}\n", f.display()));
    }
    for k in &manifest.mcp_keys {
        out.push_str(&format!(
            "  added  mcpServers.{} in {}\n",
            k.server,
            k.file.display()
        ));
    }
    for h in &manifest.hooks {
        out.push_str(&format!(
            "  added  {} hook in {}\n",
            h.event,
            h.file.display()
        ));
    }
    for g in &manifest.gitignore {
        out.push_str(&format!("  added  {} to {}\n", g.line, g.file.display()));
    }
    for h in &manifest.git_hooks {
        out.push_str(&format!("  added  git hook {}\n", h.display()));
    }
    if manifest.codex {
        out.push_str(&format!("  added  codex mcp server {SERVER_NAME}\n"));
    }
    if anything_written {
        out.push_str(&format!("  manifest  {}\n", manifest_path.display()));
        // The hooks and the skill both run this command; only an MCP install
        // calls it a server, so a `cli` install says what it actually wrote.
        let label = if opts.delivery.wires_mcp() {
            "mcp command"
        } else {
            "command"
        };
        out.push_str(&format!("  {label}  {}\n", cmd.shell()));
        out.push_str(&describe_stores(&stores));
    } else {
        out.push_str("  (already installed — no changes)\n");
    }
    for n in &notes {
        out.push_str(&format!("  {n}\n"));
    }
    out.push_str(&format!(
        "next: restart Claude Code in {}, then type /mushroom\n",
        project_root.display()
    ));
    Ok(out)
}

/// The whole write phase, so a failure anywhere in it still leaves the caller
/// holding the partial manifest.
fn write_everything(
    ctx: &Ctx<'_>,
    stores: &[(Platform, StoreRef)],
    manifest: &mut Manifest,
    notes: &mut Vec<String>,
) -> Result<(), CliError> {
    let platforms: Vec<Platform> = stores.iter().map(|(p, _)| p.clone()).collect();
    if let Some(w) = scope_conflict_note(ctx, &platforms) {
        notes.push(w);
    }

    for (plat, store) in stores {
        install_platform(ctx, plat, store, manifest, notes)?;
    }

    // The repository-level wiring is shared by the platforms whose config
    // lives in the repository: the store is ignored by git and the graph is
    // re-synced after commits whichever of them reads it.
    //
    // A Codex-only install is excluded. It writes nothing else project-local
    // (Codex keeps its own config, and the manifest for it lives under the
    // home directory), so an ignore line and three git hooks recorded there
    // would be removed by a `uninstall --platform codex` out from under a
    // Claude Code install that shares the repository and never recorded them.
    let repo_wiring = platforms
        .iter()
        .any(|p| matches!(p, Platform::ClaudeCode | Platform::Cursor));
    if ctx.scope == Scope::Project && repo_wiring {
        ensure_gitignore_line(ctx, manifest)?;
        if ctx.git_hooks {
            install_git_hooks(ctx, manifest)?;
        }
    }

    if let Some(w) = prewarm(ctx) {
        notes.push(w);
    }
    Ok(())
}

/// Find the manifest for an existing install, the way `uninstall`, `disable`
/// and `enable` all need to: an inferred scope that turns up nothing falls
/// back to the other one before giving up, and giving up is an error naming
/// `verb`.
///
/// An inferred scope is a guess, and guessing wrong here means telling
/// someone with a perfectly good user-scope install that they have nothing to
/// act on — 0.5.x had no scope detection, so every install made by it inside a
/// checkout is exactly that case. A scope the user stated is not
/// second-guessed. Returns the scope actually used, since a fallback changes it.
fn locate_manifest(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    auto_scope: bool,
    platforms: &[Platform],
    verb: &str,
) -> Result<(Scope, PathBuf), CliError> {
    let mut scope = scope;
    let mut path = manifest_path(project_root, home, scope, platforms);
    if auto_scope && !path.exists() {
        let other = match scope {
            Scope::Project => Scope::User,
            Scope::User => Scope::Project,
        };
        let alt = manifest_path(project_root, home, other, platforms);
        if alt.exists() {
            scope = other;
            path = alt;
        }
    }
    if !path.exists() {
        return Err(CliError(format!(
            "no install manifest found at {} — nothing to {verb}",
            path.display()
        )));
    }
    Ok((scope, path))
}

/// Uninstall: remove exactly what install wrote. Reads the manifest.
pub fn run_uninstall(
    project_root: &Path,
    home: &Path,
    opts: &InstallOpts,
) -> Result<String, CliError> {
    run_uninstall_with(project_root, home, opts, &Externals::from_env())
}

/// Like [`run_uninstall`], with the external environment supplied by the
/// caller (Codex removal shells out to the `codex` CLI).
pub fn run_uninstall_with(
    project_root: &Path,
    home: &Path,
    opts: &InstallOpts,
    ext: &Externals,
) -> Result<String, CliError> {
    let (scope, auto_scope) = resolve_scope(project_root, opts.scope);
    let resolved = resolve_platform(project_root, home, opts.platform.as_ref())?;
    let platforms = expand_platform(&resolved);

    let (scope, manifest_path) = locate_manifest(
        project_root,
        home,
        scope,
        auto_scope,
        &platforms,
        "uninstall",
    )?;
    let manifest = load_manifest(&manifest_path);

    let mut removed = Vec::new();

    // Remove MCP keys first (before files, in case files include .mcp.json).
    // Each line is printed only for a removal that happened: after an upgrade
    // the manifest also lists the commands the upgrade already replaced, and
    // claiming to have removed those would be a report of work not done.
    for key in &manifest.mcp_keys {
        if remove_mcp_key(&key.file, &key.server)? {
            removed.push(format!(
                "removed  mcpServers.{} from {}",
                key.server,
                key.file.display()
            ));
        }
    }

    // Remove hooks (before files, same reasoning as MCP keys).
    for h in &manifest.hooks {
        if remove_hook_entry(&h.file, &h.event, &h.command)? {
            removed.push(format!(
                "removed  {} hook from {}",
                h.event,
                h.file.display()
            ));
        }
    }

    // Git hooks: the marked region only, never the user's own lines.
    for h in &manifest.git_hooks {
        if remove_git_hook(h)? {
            removed.push(format!("removed  git hook block from {}", h.display()));
        }
    }

    // The ignore line, exactly as it was written. A file that exists only
    // because install created it goes too — but only when our line was all it
    // ever held; anything the user added to it since is theirs to keep.
    for g in &manifest.gitignore {
        if remove_line(&g.file, &g.line)? {
            removed.push(format!("removed  {} from {}", g.line, g.file.display()));
        }
        if g.created && g.file.exists() && file_is_blank(&g.file) {
            fs::remove_file(&g.file)
                .map_err(|e| CliError(format!("cannot remove {}: {e}", g.file.display())))?;
            removed.push(format!("removed  {}", g.file.display()));
        }
    }

    // Codex holds its own config; hand the removal back to its CLI. Not being
    // able to reach `codex` must not strand every other thing the manifest
    // lists.
    if manifest.codex {
        remove_codex(ext, &mut removed, "removed")?;
    }

    // Remove files.
    for f in &manifest.files {
        if f.exists() {
            fs::remove_file(f)
                .map_err(|e| CliError(format!("cannot remove {}: {e}", f.display())))?;
            removed.push(format!("removed  {}", f.display()));
        }
    }

    // Remove the manifest itself.
    if manifest_path.exists() {
        fs::remove_file(&manifest_path)
            .map_err(|e| CliError(format!("cannot remove manifest: {e}")))?;
    }

    let mut out = "mushroomdb uninstalled\n".to_string();
    out.push_str(&format!(
        "  scope  {}{}\n",
        scope.label(),
        if auto_scope { " (auto-detected)" } else { "" }
    ));
    for line in &removed {
        out.push_str(&format!("  {line}\n"));
    }
    Ok(out)
}

// ---------------------------------------------------------------------------
// Enable / disable — turn an install off without removing it
// ---------------------------------------------------------------------------
//
// `disable` takes the dynamic, per-assistant config off disk — the MCP entry,
// the three Claude Code hooks, the three git hook blocks, the Codex
// registration — and leaves everything a person might have customised or that
// the store depends on: the skill/rules file, the store itself, the
// `.gitignore` line. `enable` puts the config back, re-derived from whatever
// `install` would choose right now rather than replayed byte-for-byte, so an
// upgrade of the published package between the two calls is picked up instead
// of pinned to a path that may no longer resolve.
//
// Neither command clears `mcp_keys` / `hooks` / `git_hooks` / `codex` on the
// manifest — those keep describing what the install *owns*, disabled or not —
// which is what lets `uninstall` work unmodified from a disabled install: it
// already treats every removal as a no-op when there is nothing left to
// remove.

fn scope_dir(project_root: &Path, home: &Path, scope: Scope) -> PathBuf {
    match scope {
        Scope::Project => project_root.to_path_buf(),
        Scope::User => home.to_path_buf(),
    }
}

/// The `mcpServers.<server>` entry in `mcp_file`, if the file and the entry
/// both exist.
fn read_mcp_entry(mcp_file: &Path, server: &str) -> Result<Option<serde_json::Value>, CliError> {
    if !mcp_file.exists() {
        return Ok(None);
    }
    let raw = fs::read_to_string(mcp_file)
        .map_err(|e| CliError(format!("cannot read {}: {e}", mcp_file.display())))?;
    let root: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| CliError(format!("corrupt mcp json at {}: {e}", mcp_file.display())))?;
    let entry = &root["mcpServers"][server];
    Ok(if entry.is_null() {
        None
    } else {
        Some(entry.clone())
    })
}

/// Reconstruct the [`StoreRef`] an existing config argument names — the same
/// argument [`StoreRef::arg`] would have written. `enable` uses this to read
/// which store a stashed MCP entry (and the hooks wired alongside it) was for.
fn store_from_arg(arg: &str, project_root: &Path, home: &Path) -> StoreRef {
    if arg == AUTO_ARG {
        return StoreRef::auto(crate::resolve_auto_db(None, project_root, home));
    }
    let path = PathBuf::from(arg);
    if path == default_db(Scope::Project, project_root, home) {
        return StoreRef::pinned(path).also_auto();
    }
    StoreRef::pinned(path)
}

/// The store argument one of our hook commands names.
///
/// A hook command is `<binary…> <sub> <store>` and the store is its last word,
/// written by [`StoreRef::shell_arg`]: `--auto`, or the path in the single
/// quotes [`sh_quote`] puts round it. This reads that word back.
fn hook_command_store_arg(command: &str, sub: &str) -> Option<String> {
    let needle = format!(" {sub} ");
    let at = command.rfind(&needle)?;
    let arg = command[at + needle.len()..].trim();
    if arg.is_empty() {
        return None;
    }
    Some(
        match arg.strip_prefix('\'').and_then(|a| a.strip_suffix('\'')) {
            Some(inner) => inner.replace(r"'\''", "'"),
            None => arg.to_string(),
        },
    )
}

/// The store an install recorded, read back out of its `SessionStart` hook.
///
/// A `cli` install registers no MCP server, so the entry every other recovery
/// path reads the store out of does not exist; the hooks are what it wrote,
/// and they name the store the same way.
fn store_from_hooks(manifest: &Manifest, project_root: &Path, home: &Path) -> Option<StoreRef> {
    manifest
        .hooks
        .iter()
        .find(|h| h.event == BRIEF_EVENT)
        .and_then(|h| hook_command_store_arg(&h.command, "brief"))
        .map(|arg| store_from_arg(&arg, project_root, home))
}

/// What an install at this scope recorded: the door it opened, and the store
/// its hooks name. Both are `None`/`Both` when there is no manifest at all.
pub(crate) fn installed_shape(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    platforms: &[Platform],
) -> (Delivery, Option<StoreRef>) {
    let manifest = load_manifest(&manifest_path(project_root, home, scope, platforms));
    let store = store_from_hooks(&manifest, project_root, home);
    (manifest.delivery, store)
}

/// The config file `disable` would have stashed `platform`'s MCP entry from —
/// the same file [`platform_stores`]/[`install_platform`] write to. `None` for
/// Codex, whose registration is not a file this program reads.
fn platform_mcp_file(
    platform: &Platform,
    project_root: &Path,
    home: &Path,
    scope: Scope,
) -> Option<PathBuf> {
    match platform {
        Platform::ClaudeCode => Some(claude_mcp_file(project_root, home, scope)),
        Platform::Cursor => Some(cursor_mcp_file(project_root, home, scope)),
        Platform::Codex | Platform::All => None,
    }
}

/// The store `enable` should write for `platform`: whichever one that
/// platform's own stashed MCP entry named, matched by which file it was
/// stashed from — Claude Code and Cursor can disagree (only Claude Code
/// resolves `--auto`; see [`resolves_at_runtime`]), so a single stash entry
/// must never be applied to every platform. Falls back to the same default
/// `install` would pick with no `--db` when nothing was stashed for this
/// platform — always true for Codex, whose registration is not a file this
/// program reads, so a Codex install made with an explicit `--db` cannot be
/// recovered exactly and is re-registered at the default store instead.
fn recover_store_for(
    manifest: &Manifest,
    platform: &Platform,
    project_root: &Path,
    home: &Path,
    scope: Scope,
) -> StoreRef {
    platform_mcp_file(platform, project_root, home, scope)
        .and_then(|file| manifest.stashed_mcp.iter().find(|s| s.file == file))
        .and_then(|s| entry_db(&s.entry))
        .map(|arg| store_from_arg(arg, project_root, home))
        // A `cli` install stashed no entry, because it registered no server.
        // Its hooks name the store, and they are recorded too.
        .or_else(|| match platform {
            Platform::ClaudeCode => store_from_hooks(manifest, project_root, home),
            _ => None,
        })
        .unwrap_or_else(|| {
            store_ref(
                project_root,
                home,
                scope,
                None,
                resolves_at_runtime(platform),
            )
        })
}

/// The store the repository wiring (`.gitignore`, the git hook blocks) should
/// name for `enable`: whichever recovered per-platform store resolves at
/// runtime (Claude Code's, when present — same preference [`repo_store_ref`]
/// gives a fresh install), else the first platform's. Mirrors
/// [`repo_store_ref`], sourced from what was actually recovered rather than
/// recomputed independently, so it can never disagree with what
/// `install_claude_code`/`install_cursor` just wrote.
fn repo_store_for_enable(stores: &[(Platform, StoreRef)]) -> StoreRef {
    stores
        .iter()
        .find(|(p, _)| resolves_at_runtime(p))
        .or_else(|| stores.first())
        .map(|(_, s)| s.clone())
        .expect("enable always resolves at least one platform")
}

/// Turn an install off: remove the MCP entry, the three Claude Code hooks, the
/// git hook blocks and the Codex registration; leave the skill/rules file, the
/// store, and the `.gitignore` line untouched. Idempotent.
pub fn run_disable(
    project_root: &Path,
    home: &Path,
    opts: &ToggleOpts,
) -> Result<String, CliError> {
    run_disable_with(project_root, home, opts, &Externals::from_env())
}

/// Like [`run_disable`], with the external environment supplied by the caller
/// (Codex removal shells out to the `codex` CLI).
pub fn run_disable_with(
    project_root: &Path,
    home: &Path,
    opts: &ToggleOpts,
    ext: &Externals,
) -> Result<String, CliError> {
    let (scope, auto_scope) = resolve_scope(project_root, opts.scope);
    let resolved = resolve_platform(project_root, home, opts.platform.as_ref())?;
    let platforms = expand_platform(&resolved);
    let (scope, manifest_path) =
        locate_manifest(project_root, home, scope, auto_scope, &platforms, "disable")?;
    let mut manifest = load_manifest(&manifest_path);

    let dir = scope_dir(project_root, home, scope);
    if manifest.disabled {
        return Ok(format!(
            "mushroomdb is already disabled in {}\n",
            dir.display()
        ));
    }

    let mut changed = Vec::new();
    let mut stashed = Vec::new();
    for key in &manifest.mcp_keys {
        let Some(entry) = read_mcp_entry(&key.file, &key.server)? else {
            continue;
        };
        stashed.push(StashedMcpEntry {
            file: key.file.clone(),
            server: key.server.clone(),
            entry,
        });
        if remove_mcp_key(&key.file, &key.server)? {
            changed.push(format!(
                "disabled  mcpServers.{} in {}",
                key.server,
                key.file.display()
            ));
        }
    }

    for h in &manifest.hooks {
        if remove_hook_entry(&h.file, &h.event, &h.command)? {
            changed.push(format!(
                "disabled  {} hook in {}",
                h.event,
                h.file.display()
            ));
        }
    }

    for h in &manifest.git_hooks {
        if remove_git_hook(h)? {
            changed.push(format!("disabled  git hook block in {}", h.display()));
        }
    }

    if manifest.codex {
        remove_codex(ext, &mut changed, "disabled")?;
    }

    manifest.disabled = true;
    manifest.stashed_mcp = stashed;
    write_manifest(&manifest_path, &manifest)?;

    let mut out = String::new();
    for line in &changed {
        out.push_str(line);
        out.push('\n');
    }
    out.push_str(&format!(
        "mushroomdb is disabled in {}; enable with: mushroomdb enable\n",
        dir.display()
    ));
    Ok(out)
}

/// Turn a disabled install back on. Re-adds the MCP entry, the three Claude Code
/// hooks and the git hook blocks using the store a stashed entry named and the
/// command `install` would resolve right now — not a replay of what
/// `disable` took out, which may no longer be the fastest path to the
/// published package. Idempotent, and a no-op (not an error) when the install
/// is not disabled.
pub fn run_enable(project_root: &Path, home: &Path, opts: &ToggleOpts) -> Result<String, CliError> {
    run_enable_with(
        project_root,
        home,
        opts,
        &detect_mcp_command(None),
        &Externals::from_env(),
    )
}

/// Like [`run_enable`], with the server command and the external environment
/// supplied by the caller. Tests use this to stay deterministic and offline.
pub fn run_enable_with(
    project_root: &Path,
    home: &Path,
    opts: &ToggleOpts,
    cmd: &McpCommand,
    ext: &Externals,
) -> Result<String, CliError> {
    let (scope, auto_scope) = resolve_scope(project_root, opts.scope);
    let resolved = resolve_platform(project_root, home, opts.platform.as_ref())?;
    let platforms = expand_platform(&resolved);
    let (scope, manifest_path) =
        locate_manifest(project_root, home, scope, auto_scope, &platforms, "enable")?;
    let mut manifest = load_manifest(&manifest_path);

    let dir = scope_dir(project_root, home, scope);
    if !manifest.disabled {
        return Ok(format!(
            "mushroomdb is already enabled in {}\n",
            dir.display()
        ));
    }

    // Restore what was actually requested before, not the caller's
    // auto-detected `cmd` — that would silently drop an explicit `--command`
    // pin the moment it was disabled. `Npx` is re-resolved below exactly like
    // `install` would (the "current shapes" part); `Explicit` is used
    // verbatim unless the binary it names is gone, in which case this falls
    // back to the caller's `cmd` and says so. A manifest with no stash at all
    // (written before this field existed) also falls back, silently — there
    // is nothing to have dropped.
    let mut notes: Vec<String> = Vec::new();
    let base_cmd = match manifest.requested_cmd.clone() {
        Some(StoredCommand::Explicit(p)) if is_bare_program_name(&p) || p.is_file() => {
            McpCommand::Explicit(p)
        }
        Some(StoredCommand::Explicit(p)) => {
            notes.push(format!(
                "warning: the pinned command {} no longer exists — re-detected the command instead",
                p.display()
            ));
            cmd.clone()
        }
        Some(other) => other.into_mcp(),
        None => cmd.clone(),
    };
    let base_cmd = match &base_cmd {
        McpCommand::Explicit(p) => McpCommand::Explicit(absolutise_command(p, project_root)),
        other => other.clone(),
    };
    let (cmd, launcher_note, _) = resolve_fast_command(&base_cmd, ext);
    let cmd = &cmd;
    notes.extend(launcher_note);

    // Each platform's own stashed entry says which store *that* platform was
    // installed with — Claude Code and Cursor can disagree, since only Claude
    // Code resolves `--auto`. A Codex-only install stashes nothing and falls
    // back to the same default a fresh install would pick.
    let stores: Vec<(Platform, StoreRef)> = platforms
        .iter()
        .map(|p| {
            (
                p.clone(),
                recover_store_for(&manifest, p, project_root, home, scope),
            )
        })
        .collect();
    let repo_store = repo_store_for_enable(&stores);
    let had_git_hooks = !manifest.git_hooks.is_empty();

    let ctx = Ctx {
        project_root,
        home,
        scope,
        repo_store: &repo_store,
        cmd,
        ext,
        git_hooks: true,
        prewarm: false,
        // Re-enable the install that was disabled, not a different one: a
        // `cli` install has no server to put back, and its skill is the one
        // that teaches the binary.
        delivery: manifest.delivery,
        // Likewise the experiments: `enable` never adds one the install it is
        // restoring never had, and never drops one it did.
        intercept_grep: manifest.intercept_grep,
        impact_before_edit: manifest.impact_before_edit,
        enrich_grep: manifest.enrich_grep,
        always_load: manifest.always_load,
    };

    let mut fresh = Manifest::default();
    for (plat, store) in &stores {
        match plat {
            Platform::ClaudeCode => install_claude_code(&ctx, store, &mut fresh, &mut notes)?,
            Platform::Cursor => install_cursor(&ctx, store, &mut fresh, &mut notes)?,
            Platform::Codex => install_codex(&ctx, store, &mut fresh)?,
            Platform::All => unreachable!("expand_platform never produces All"),
        }
    }

    let repo_wiring = platforms
        .iter()
        .any(|p| matches!(p, Platform::ClaudeCode | Platform::Cursor));
    if had_git_hooks && scope == Scope::Project && repo_wiring {
        install_git_hooks(&ctx, &mut fresh)?;
    }

    // Fold this run's writes into the manifest: entries for files this run
    // touched replace what was there before (the command may have re-resolved
    // to a different path since `disable`); anything this run did not touch
    // — a platform this call was not asked to enable — survives untouched.
    let touched_mcp: Vec<&PathBuf> = fresh.mcp_keys.iter().map(|k| &k.file).collect();
    manifest
        .mcp_keys
        .retain(|k| !touched_mcp.contains(&&k.file));
    manifest.mcp_keys.extend(fresh.mcp_keys.iter().cloned());

    let touched_hooks: Vec<(&PathBuf, &str)> = fresh
        .hooks
        .iter()
        .map(|h| (&h.file, h.event.as_str()))
        .collect();
    manifest
        .hooks
        .retain(|h| !touched_hooks.contains(&(&h.file, h.event.as_str())));
    manifest.hooks.extend(fresh.hooks.iter().cloned());

    if !fresh.git_hooks.is_empty() {
        manifest.git_hooks = fresh.git_hooks.clone();
    }
    manifest.codex |= fresh.codex;
    for f in &fresh.files {
        if !manifest.files.contains(f) {
            manifest.files.push(f.clone());
        }
    }

    manifest.disabled = false;
    manifest.stashed_mcp.clear();
    // Remember what was actually used this round — the restored pin, the
    // fallback it took because that pin was gone, or the unresolved `Npx`
    // request (never the resolved native-binary/launcher path resolution
    // turned it into) — so the *next* `disable`/`enable` round trip starts
    // from what is actually true now rather than a permanently stale pin.
    manifest.requested_cmd = StoredCommand::from_mcp(&base_cmd);
    write_manifest(&manifest_path, &manifest)?;

    let mut out = String::new();
    for k in &fresh.mcp_keys {
        out.push_str(&format!(
            "enabled  mcpServers.{} in {}\n",
            k.server,
            k.file.display()
        ));
    }
    for h in &fresh.hooks {
        out.push_str(&format!(
            "enabled  {} hook in {}\n",
            h.event,
            h.file.display()
        ));
    }
    for g in &fresh.git_hooks {
        out.push_str(&format!("enabled  git hook {}\n", g.display()));
    }
    if fresh.codex {
        out.push_str(&format!("enabled  codex mcp server {SERVER_NAME}\n"));
    }
    for n in &notes {
        out.push_str(&format!("  {n}\n"));
    }
    out.push_str(&format!("mushroomdb is enabled in {}\n", dir.display()));
    Ok(out)
}

// ---------------------------------------------------------------------------
// Platform resolution
// ---------------------------------------------------------------------------

pub(crate) fn resolve_platform(
    project_root: &Path,
    home: &Path,
    requested: Option<&Platform>,
) -> Result<Platform, CliError> {
    if let Some(p) = requested {
        return Ok(p.clone());
    }

    // Auto-detect. Codex is never inferred: registering with it runs another
    // program, which is not something to do because a directory exists.
    let has_claude = home.join(".claude").exists() || project_root.join(".claude").exists();
    let has_cursor = project_root.join(".cursor").exists() || home.join(".cursor").exists();

    match (has_claude, has_cursor) {
        (true, true) => Ok(Platform::All),
        (true, false) => Ok(Platform::ClaudeCode),
        (false, true) => Ok(Platform::Cursor),
        (false, false) => Err(CliError(
            "cannot auto-detect platform: neither ~/.claude nor .cursor/ found.\n\
             Pass --platform claude-code, --platform cursor, --platform codex, or --platform all."
                .to_string(),
        )),
    }
}

/// `All` is the two platforms whose config this program writes itself. Codex
/// is deliberately not in it: it is wired by running the `codex` CLI, which
/// may not exist, and `--platform all` must not fail on a machine that simply
/// does not have it.
pub(crate) fn expand_platform(p: &Platform) -> Vec<Platform> {
    match p {
        Platform::All => vec![Platform::ClaudeCode, Platform::Cursor],
        other => vec![other.clone()],
    }
}

// ---------------------------------------------------------------------------
// Pre-flight conflict check (no writes)
// ---------------------------------------------------------------------------

fn preflight_check(
    project_root: &Path,
    home: &Path,
    platform: &Platform,
    scope: Scope,
    store: &StoreRef,
    ext: &Externals,
) -> Result<(), CliError> {
    match platform {
        Platform::ClaudeCode => {
            check_mcp_conflict(&claude_mcp_file(project_root, home, scope), store)
        }
        Platform::Cursor => check_mcp_conflict(&cursor_mcp_file(project_root, home, scope), store),
        // Nothing of Codex's is a file we read; what can fail early is the CLI
        // being absent, and that is worth saying before anything is written.
        Platform::Codex => codex_bin(ext).map(|_| ()),
        Platform::All => unreachable!("expand_platform never produces All"),
    }
}

pub(crate) fn claude_mcp_file(project_root: &Path, home: &Path, scope: Scope) -> PathBuf {
    match scope {
        Scope::Project => project_root.join(".mcp.json"),
        // User-scope: verified empirically on a live Claude Code install.
        // ~/.claude.json holds top-level mcpServers; ~/.claude/settings.json
        // holds env/permissions/hooks but no mcpServers key.
        Scope::User => home.join(".claude.json"),
    }
}

pub(crate) fn cursor_mcp_file(project_root: &Path, home: &Path, scope: Scope) -> PathBuf {
    match scope {
        Scope::Project => project_root.join(".cursor").join("mcp.json"),
        Scope::User => home.join(".cursor").join("mcp.json"),
    }
}

/// The store an existing entry serves: the argument straight after `mcp`,
/// which is either a path or `--auto`.
///
/// Its position moved between versions — 0.5.x wrote `["mcp", db]`, the npx
/// form writes `["-y", "mushroomdb@x.y.z", "mcp", db]`, a resolved launcher
/// writes `["<launcher>", "mcp", "--auto"]` — so the subcommand is what
/// locates it, not an index.
pub(crate) fn entry_db(entry: &serde_json::Value) -> Option<&str> {
    let args = entry["args"].as_array()?;
    let at = args.iter().position(|a| a == "mcp")?;
    args.get(at + 1)?.as_str()
}

/// Check if a MCP JSON file has a conflicting `mushroomdb` entry.
///
/// A conflict is: the file exists, has `mcpServers.mushroomdb`, and the store
/// it names differs from the one we'd write. An entry for the SAME store with
/// a different `command` — or the same store spelled the other way, which is
/// every 0.6.0 entry now that a project install writes `--auto` — is ours to
/// repair, so it is not a conflict.
fn check_mcp_conflict(mcp_file: &Path, store: &StoreRef) -> Result<(), CliError> {
    if !mcp_file.exists() {
        return Ok(());
    }
    let raw = fs::read_to_string(mcp_file)
        .map_err(|e| CliError(format!("cannot read {}: {e}", mcp_file.display())))?;
    let v: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| CliError(format!("invalid JSON in {}: {e}", mcp_file.display())))?;

    let existing = &v["mcpServers"][SERVER_NAME];
    if existing.is_null() {
        return Ok(()); // Key absent — no conflict.
    }

    let existing_db = entry_db(existing).unwrap_or("");
    if store.names_same_store(existing_db) {
        return Ok(()); // Same store — idempotent or repairable, no conflict.
    }

    Err(CliError(format!(
        "conflict: {} already has mcpServers.mushroomdb pointing to {:?}\n\
         To update it, run `mushroomdb uninstall` first, then re-install.\n\
         Or manually edit {} and remove the existing mushroomdb entry.",
        mcp_file.display(),
        existing_db,
        mcp_file.display()
    )))
}

/// A server registered in the *other* scope still shows up in the assistant,
/// and two of them pointed at two stores is a confusing place to be. Say so;
/// never touch the other scope's file.
fn scope_conflict_note(ctx: &Ctx<'_>, platforms: &[Platform]) -> Option<String> {
    if !platforms.contains(&Platform::ClaudeCode) {
        return None;
    }
    let (other, label, flag) = match ctx.scope {
        Scope::Project => (
            claude_mcp_file(ctx.project_root, ctx.home, Scope::User),
            "user",
            "--user",
        ),
        Scope::User => (
            claude_mcp_file(ctx.project_root, ctx.home, Scope::Project),
            "project",
            "--project",
        ),
    };
    if !has_our_server(&other) {
        return None;
    }
    Some(format!(
        "warning: a {label}-scope mushroomdb server also exists ({}) — \
         both will load; to remove that one run: mushroomdb uninstall {flag}",
        other.display()
    ))
}

pub(crate) fn has_our_server(mcp_file: &Path) -> bool {
    let Ok(raw) = fs::read_to_string(mcp_file) else {
        return false;
    };
    serde_json::from_str::<serde_json::Value>(&raw)
        .map(|v| !v["mcpServers"][SERVER_NAME].is_null())
        .unwrap_or(false)
}

// ---------------------------------------------------------------------------
// Per-platform installation
// ---------------------------------------------------------------------------

fn install_platform(
    ctx: &Ctx<'_>,
    platform: &Platform,
    store: &StoreRef,
    manifest: &mut Manifest,
    notes: &mut Vec<String>,
) -> Result<(), CliError> {
    // `--delivery` only has a skill to switch on Claude Code; the other two
    // are registered as MCP servers whatever was asked for. Say so — a flag
    // that does nothing is worse when it does it quietly.
    if !ctx.delivery.wires_mcp() && !matches!(platform, Platform::ClaudeCode) {
        notes.push(format!(
            "note: --delivery {} applies to claude-code only — {} was registered as an MCP server",
            ctx.delivery.label(),
            platform.label()
        ));
    }
    match platform {
        Platform::ClaudeCode => install_claude_code(ctx, store, manifest, notes),
        Platform::Cursor => install_cursor(ctx, store, manifest, notes),
        Platform::Codex => install_codex(ctx, store, manifest),
        Platform::All => unreachable!("expand_platform never produces All"),
    }
}

/// Substitute both template placeholders and keep only the delivery regions
/// this install wants. `bin_cmd` is the pre-quoted shell form, so the
/// templates carry `{{BIN}}` unquoted.
///
/// One source file describes every delivery, so the variants cannot drift: a
/// `<!-- cli -->` / `<!-- /cli -->` (or `mcp`) pair marks a block only that
/// door's reader should see, and `Both` keeps them all. The marker lines
/// themselves are never written. By convention a region opens immediately
/// after the paragraph before it and its content starts with the blank line,
/// so dropping a whole region leaves exactly one blank line behind rather than
/// a hole in the prose.
///
/// The regions are checked for well-formedness rather than trusted: an
/// unterminated `<!-- mcp -->` would silently swallow the rest of the file on
/// the `cli` variant, and a nested pair would leave the inner close re-opening
/// the outer region, so both are errors and neither can ship as a short skill
/// nobody looked at. The two conditions are the same ones the awk twin in
/// `scripts/render-plugin.sh` fails on.
///
/// Public so the skill's per-turn budget can be measured on every variant
/// without an install: what this returns is exactly what `install` writes, and
/// `scripts/render-plugin.sh` mirrors it for the plugin copy.
pub fn render_template(
    template: &str,
    db_str: &str,
    bin_cmd: &str,
    delivery: Delivery,
) -> Result<String, CliError> {
    /// `("cli", true)` for `<!-- cli -->`, `("cli", false)` for `<!-- /cli -->`.
    fn marker(line: &str) -> Option<(&'static str, bool)> {
        match line {
            "<!-- cli -->" => Some(("cli", true)),
            "<!-- mcp -->" => Some(("mcp", true)),
            "<!-- /cli -->" => Some(("cli", false)),
            "<!-- /mcp -->" => Some(("mcp", false)),
            _ => None,
        }
    }

    let mut out = String::with_capacity(template.len());
    let mut open: Option<(&str, usize)> = None;
    let mut dropping = false;
    for (i, line) in template.lines().enumerate() {
        let at = i + 1;
        match marker(line) {
            Some((name, true)) => {
                if let Some((outer, opened)) = open {
                    return Err(CliError(format!(
                        "skill template line {at}: <!-- {name} --> opens inside the \
                         <!-- {outer} --> region opened on line {opened} — delivery \
                         regions must not nest"
                    )));
                }
                open = Some((name, at));
                dropping = match name {
                    "cli" => matches!(delivery, Delivery::Mcp),
                    _ => matches!(delivery, Delivery::Cli),
                };
            }
            Some((name, false)) => {
                match open {
                    None => {
                        return Err(CliError(format!(
                            "skill template line {at}: <!-- /{name} --> closes a region \
                             that was never opened"
                        )))
                    }
                    Some((outer, opened)) if outer != name => {
                        return Err(CliError(format!(
                            "skill template line {at}: <!-- /{name} --> closes the \
                             <!-- {outer} --> region opened on line {opened}"
                        )))
                    }
                    Some(_) => {}
                }
                open = None;
                dropping = false;
            }
            None if dropping => {}
            None => {
                out.push_str(line);
                out.push('\n');
            }
        }
    }
    if let Some((name, opened)) = open {
        return Err(CliError(format!(
            "skill template: the <!-- {name} --> region opened on line {opened} is \
             never closed"
        )));
    }
    Ok(out
        .replace(DB_PATH_PLACEHOLDER, db_str)
        .replace(BIN_PLACEHOLDER, bin_cmd))
}

fn install_claude_code(
    ctx: &Ctx<'_>,
    store: &StoreRef,
    manifest: &mut Manifest,
    notes: &mut Vec<String>,
) -> Result<(), CliError> {
    let shell = ctx.cmd.shell();
    // The skill is prose a reader follows by hand, so it names the directory
    // the store is in rather than the `--auto` the machine-read config uses.
    let db_str = store.path().to_string_lossy();
    let skill_content = render_template(SKILL_TEMPLATE, &db_str, &shell, ctx.delivery)?;

    let skill_dir = match ctx.scope {
        Scope::Project => ctx
            .project_root
            .join(".claude")
            .join("skills")
            .join("mushroom"),
        Scope::User => ctx.home.join(".claude").join("skills").join("mushroom"),
    };
    let skill_file = skill_dir.join("SKILL.md");

    // Idempotent: skip if the file already has the same content.
    if !file_matches(&skill_file, &skill_content) {
        fs::create_dir_all(&skill_dir)
            .map_err(|e| CliError(format!("cannot create {}: {e}", skill_dir.display())))?;
        fs::write(&skill_file, &skill_content)
            .map_err(|e| CliError(format!("cannot write {}: {e}", skill_file.display())))?;
        manifest.files.push(skill_file);
    }

    // `cli` delivery is defined by what it does *not* write: no server entry,
    // so nothing in the session pays a tool-discovery round trip before its
    // first question. The hooks below are written either way — they are the
    // binary talking to the session, not the session talking to a server.
    let mcp_file = claude_mcp_file(ctx.project_root, ctx.home, ctx.scope);
    if ctx.delivery.wires_mcp() {
        merge_mcp_entry(&mcp_file, ctx, store, ctx.always_load, manifest, notes)?;
    } else if remove_mcp_key(&mcp_file, SERVER_NAME)? {
        // Switching an existing install to `cli` has to take the server it
        // already registered back out, or the door this delivery exists to
        // close would stay open.
        notes.push(format!(
            "removed mcpServers.{SERVER_NAME} from {} — delivery: {}",
            mcp_file.display(),
            ctx.delivery.label()
        ));
    }

    // All three hooks: settings.json in the same scope as the skill. The
    // prompt hook first, so a manifest lists them in the order they were
    // written.
    let settings_file = match ctx.scope {
        Scope::Project => ctx.project_root.join(".claude").join("settings.json"),
        Scope::User => ctx.home.join(".claude").join("settings.json"),
    };
    // An earlier install of ours for this same store is replaced, not joined:
    // its command names a binary this version no longer writes, and leaving it
    // would run both on every prompt.
    let recall = hook_command(&shell, "recall", store);
    if remove_stale_hooks(&settings_file, HOOK_EVENT, "recall", store, &recall)? {
        notes.push(format!("replaced stale {HOOK_EVENT} hook"));
    }
    merge_hook_entry(
        &settings_file,
        HOOK_EVENT,
        &recall,
        hook_entry(&recall),
        manifest,
    )?;
    let touch = hook_command(&shell, "touch", store);
    if remove_stale_hooks(&settings_file, TOUCH_EVENT, "touch", store, &touch)? {
        notes.push(format!("replaced stale {TOUCH_EVENT} hook"));
    }
    merge_hook_entry(
        &settings_file,
        TOUCH_EVENT,
        &touch,
        matched_hook_entry(TOUCH_MATCHER, &touch, TOUCH_TIMEOUT_SECS, true),
        manifest,
    )?;
    let brief = hook_command(&shell, "brief", store);
    if remove_stale_hooks(&settings_file, BRIEF_EVENT, "brief", store, &brief)? {
        notes.push(format!("replaced stale {BRIEF_EVENT} hook"));
    }
    merge_hook_entry(
        &settings_file,
        BRIEF_EVENT,
        &brief,
        hook_entry(&brief),
        manifest,
    )?;

    // The fourth hook is opt-in, and an install that does not ask for it takes
    // back any earlier one of ours for this store — otherwise the experiment
    // could only ever be turned on.
    let intercept = hook_command(&shell, "intercept", store);
    if ctx.intercept_grep {
        if remove_stale_hooks(
            &settings_file,
            INTERCEPT_EVENT,
            "intercept",
            store,
            &intercept,
        )? {
            notes.push(format!("replaced stale {INTERCEPT_EVENT} hook"));
        }
        merge_hook_entry(
            &settings_file,
            INTERCEPT_EVENT,
            &intercept,
            matched_hook_entry(INTERCEPT_MATCHER, &intercept, HOOK_TIMEOUT_SECS, false),
            manifest,
        )?;
    } else if drop_hooks(&settings_file, INTERCEPT_EVENT, |c| {
        is_our_hook_command(c, "intercept", store)
    })? {
        notes.push(format!(
            "removed {INTERCEPT_EVENT} hook — no --intercept-grep"
        ));
    }

    // The fifth and sixth are opt-in the same way, and each shares its event
    // with a hook that is not it: the impact hook sits beside the redirect
    // under `PreToolUse`, the enrichment beside `touch` under `PostToolUse`.
    // The subcommand word keeps them apart, so turning one off leaves its
    // neighbour exactly where it was.
    let impact = hook_command(&shell, "impact-hook", store);
    if ctx.impact_before_edit {
        if remove_stale_hooks(&settings_file, IMPACT_EVENT, "impact-hook", store, &impact)? {
            notes.push(format!("replaced stale {IMPACT_EVENT} impact hook"));
        }
        merge_hook_entry(
            &settings_file,
            IMPACT_EVENT,
            &impact,
            matched_hook_entry(IMPACT_MATCHER, &impact, HOOK_TIMEOUT_SECS, false),
            manifest,
        )?;
    } else if drop_hooks(&settings_file, IMPACT_EVENT, |c| {
        is_our_hook_command(c, "impact-hook", store)
    })? {
        notes.push(format!(
            "removed {IMPACT_EVENT} impact hook — no --impact-before-edit"
        ));
    }

    let enrich = hook_command(&shell, "enrich", store);
    if ctx.enrich_grep {
        if remove_stale_hooks(&settings_file, ENRICH_EVENT, "enrich", store, &enrich)? {
            notes.push(format!("replaced stale {ENRICH_EVENT} enrichment hook"));
        }
        merge_hook_entry(
            &settings_file,
            ENRICH_EVENT,
            &enrich,
            matched_hook_entry(ENRICH_MATCHER, &enrich, HOOK_TIMEOUT_SECS, false),
            manifest,
        )?;
    } else if drop_hooks(&settings_file, ENRICH_EVENT, |c| {
        is_our_hook_command(c, "enrich", store)
    })? {
        notes.push(format!(
            "removed {ENRICH_EVENT} enrichment hook — no --enrich-grep"
        ));
    }

    Ok(())
}

fn install_cursor(
    ctx: &Ctx<'_>,
    store: &StoreRef,
    manifest: &mut Manifest,
    notes: &mut Vec<String>,
) -> Result<(), CliError> {
    let db_str = store.path().to_string_lossy();
    // Cursor is always an MCP install (see [`Delivery`]), so its rules file is
    // rendered for that door whatever `--delivery` asked for.
    let rules_content = render_template(
        CURSOR_RULES_TEMPLATE,
        &db_str,
        &ctx.cmd.shell(),
        Delivery::Mcp,
    )?;

    let rules_dir = match ctx.scope {
        Scope::Project => ctx.project_root.join(".cursor").join("rules"),
        Scope::User => ctx.home.join(".cursor").join("rules"),
    };
    let rules_file = rules_dir.join("mushroom.mdc");

    if !file_matches(&rules_file, &rules_content) {
        fs::create_dir_all(&rules_dir)
            .map_err(|e| CliError(format!("cannot create {}: {e}", rules_dir.display())))?;
        fs::write(&rules_file, &rules_content)
            .map_err(|e| CliError(format!("cannot write {}: {e}", rules_file.display())))?;
        manifest.files.push(rules_file);
    }

    let mcp_file = cursor_mcp_file(ctx.project_root, ctx.home, ctx.scope);
    merge_mcp_entry(&mcp_file, ctx, store, false, manifest, notes)?;

    Ok(())
}

/// The `codex` executable, or an error that says what to do about it.
fn codex_bin(ext: &Externals) -> Result<PathBuf, CliError> {
    ext.which("codex").ok_or_else(|| {
        CliError(
            "codex was not found on PATH — install the Codex CLI, or drop \
             `--platform codex`"
                .to_string(),
        )
    })
}

/// Take the Codex registration back out, through `codex mcp remove`. Appends
/// one line to `out` on success (`"{verb}  codex mcp server mushroomdb"`), or
/// a warning naming the manual fallback when `codex` cannot be reached — not
/// being able to reach it must not strand every other thing the caller is
/// removing. Shared by `uninstall` and `disable`, which take the registration
/// off disk the same way and differ only in whether they still own it after.
fn remove_codex(ext: &Externals, out: &mut Vec<String>, verb: &str) -> Result<(), CliError> {
    match ext.which("codex") {
        Some(bin) => {
            run_and_capture(&bin, &["mcp".into(), "remove".into(), SERVER_NAME.into()])
                .map_err(|e| CliError(format!("codex mcp remove failed: {e}")))?;
            out.push(format!("{verb}  codex mcp server {SERVER_NAME}"));
        }
        None => out.push(
            "warning: codex is not on PATH — run `codex mcp remove mushroomdb` yourself"
                .to_string(),
        ),
    }
    Ok(())
}

/// Register the server with Codex through its own CLI.
///
/// Codex owns its configuration file and its format is its business, so this
/// writes nothing: it runs `codex mcp add mushroomdb -- <command> <args…>` and
/// lets Codex record it. 0.6.0 ships no Codex skill — the MCP tools carry
/// their own descriptions, which is what Codex reads.
fn install_codex(ctx: &Ctx<'_>, store: &StoreRef, manifest: &mut Manifest) -> Result<(), CliError> {
    let bin = codex_bin(ctx.ext)?;
    let mut args = vec![
        "mcp".to_string(),
        "add".to_string(),
        SERVER_NAME.to_string(),
        "--".to_string(),
    ];
    args.extend(ctx.cmd.argv("mcp", &store.arg()));
    run_and_capture(&bin, &args).map_err(|e| CliError(format!("codex mcp add failed: {e}")))?;
    manifest.codex = true;
    Ok(())
}

// ---------------------------------------------------------------------------
// Repository wiring: the ignore line and the sync hooks
// ---------------------------------------------------------------------------

/// The git hooks a sync belongs in: after a commit lands, after a branch
/// changes the working tree, and after a merge brings other people's commits
/// in. All three leave the graph a commit behind if they are skipped.
pub(crate) const GIT_HOOKS: &[&str] = &["post-commit", "post-checkout", "post-merge"];

/// The `.gitignore` line for a store kept inside the repository, or `None`
/// when it is kept outside — a repository has no business ignoring a path it
/// does not contain.
fn gitignore_line(project_root: &Path, db: &Path) -> Option<String> {
    let rel = db.strip_prefix(project_root).ok()?;
    if rel.as_os_str().is_empty() {
        return None;
    }
    Some(format!("{}/", rel.to_string_lossy().replace('\\', "/")))
}

/// Append the store directory to the repository's `.gitignore` unless some
/// spelling of it is already listed. Creates the file if it is absent.
fn ensure_gitignore_line(ctx: &Ctx<'_>, manifest: &mut Manifest) -> Result<(), CliError> {
    let Some(line) = gitignore_line(ctx.project_root, ctx.repo_store.path()) else {
        return Ok(());
    };
    let path = ctx.project_root.join(".gitignore");
    let existed = path.exists();
    let current = match fs::read_to_string(&path) {
        Ok(s) => s,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(CliError(format!("cannot read {}: {e}", path.display()))),
    };
    let bare = line.trim_end_matches('/');
    if current
        .lines()
        .map(str::trim)
        .any(|l| l == line || l == bare || l == format!("/{line}") || l == format!("/{bare}"))
    {
        return Ok(());
    }
    let mut next = current;
    if !next.is_empty() && !next.ends_with('\n') {
        next.push('\n');
    }
    next.push_str(&line);
    next.push('\n');
    fs::write(&path, next)
        .map_err(|e| CliError(format!("cannot write {}: {e}", path.display())))?;
    // `created` is what lets uninstall leave a repository that had no
    // `.gitignore` with none again — but only if our line is still all that is
    // in it. Anything the user has added since is theirs, and the file stays.
    manifest.gitignore.push(ManagedLine {
        file: path,
        line,
        created: !existed,
    });
    Ok(())
}

/// Whether the file is gone or holds nothing but whitespace.
fn file_is_blank(path: &Path) -> bool {
    match fs::read_to_string(path) {
        Ok(s) => s.trim().is_empty(),
        Err(_) => true,
    }
}

/// Remove one exact line from a text file. Returns whether anything changed;
/// a file that does not hold the line is not rewritten at all.
fn remove_line(path: &Path, line: &str) -> Result<bool, CliError> {
    let Ok(current) = fs::read_to_string(path) else {
        return Ok(false);
    };
    if !current.lines().any(|l| l == line) {
        return Ok(false);
    }
    let kept: Vec<&str> = current.lines().filter(|l| *l != line).collect();
    let mut next = kept.join("\n");
    if !next.is_empty() {
        next.push('\n');
    }
    fs::write(path, next).map_err(|e| CliError(format!("cannot write {}: {e}", path.display())))?;
    Ok(true)
}

/// The directory git will actually run this checkout's hooks from, following
/// the `gitdir:` link a worktree or submodule leaves in place of a `.git`
/// directory.
///
/// The subtlety is the last step. A linked worktree's gitdir is
/// `<main>/.git/worktrees/<name>`, but git resolves hooks through the
/// **common** dir — `git rev-parse --git-path hooks` inside a worktree answers
/// `<main>/.git/hooks`, not the worktree's own. Writing a hook into the
/// worktree's gitdir puts it somewhere git never looks: the file is there, it
/// is executable, and nothing ever runs it. A linked worktree records the way
/// back in a `commondir` file next to its gitdir (contents `../..`), so this
/// follows it whenever it is there.
///
/// A submodule has no `commondir` and its own gitdir *is* its hooks dir
/// (`.git/modules/<path>/hooks`), which is what the plain resolution already
/// computes — so the absence of the file is the signal to stop.
pub(crate) fn git_hooks_dir(project_root: &Path) -> Option<PathBuf> {
    let dot_git = project_root.join(".git");
    if dot_git.is_dir() {
        return Some(dot_git.join("hooks"));
    }
    let text = fs::read_to_string(&dot_git).ok()?;
    let target = text.strip_prefix("gitdir:")?.trim();
    let target = Path::new(target);
    let resolved = if target.is_absolute() {
        target.to_path_buf()
    } else {
        project_root.join(target)
    };
    // A linked worktree defers its hooks to the common dir; a submodule keeps
    // its own. The `commondir` file is what tells the two apart.
    let base = match fs::read_to_string(resolved.join("commondir")) {
        Ok(rel) => {
            let rel_path = PathBuf::from(rel.trim());
            if rel_path.is_absolute() {
                rel_path
            } else {
                lexically_normalize(&resolved.join(rel_path))
            }
        }
        Err(_) => resolved,
    };
    Some(base.join("hooks"))
}

/// Resolve `.` and `..` in a path textually, without touching the filesystem.
///
/// `commondir` is written relative (`../..`), so joining it leaves a path that
/// works but reads badly in `doctor`'s output and in the manifest. This is
/// purely cosmetic and deliberately does not canonicalize: resolving symlinks
/// would rewrite a path the user gave us into one they do not recognise. A
/// leading `..` with nothing to pop is kept, since dropping it would change
/// where the path points.
fn lexically_normalize(path: &Path) -> PathBuf {
    let mut out = PathBuf::new();
    for part in path.components() {
        match part {
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                let can_pop = out
                    .components()
                    .next_back()
                    .is_some_and(|c| matches!(c, std::path::Component::Normal(_)));
                if !can_pop || !out.pop() {
                    out.push("..");
                }
            }
            other => out.push(other.as_os_str()),
        }
    }
    out
}

fn install_git_hooks(ctx: &Ctx<'_>, manifest: &mut Manifest) -> Result<(), CliError> {
    // Not a checkout: there is nothing to hook into, and that is not an error.
    let Some(dir) = git_hooks_dir(ctx.project_root) else {
        return Ok(());
    };
    let shell = ctx.cmd.shell();
    for name in GIT_HOOKS {
        let file = dir.join(name);
        if merge_git_hook(&file, &shell, ctx.repo_store)? {
            manifest.git_hooks.push(file);
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Pre-warm
// ---------------------------------------------------------------------------

/// Fetch the pinned package once, so the assistant's first spawn of the MCP
/// server is not a cold `npx` download inside a startup timeout.
///
/// Best effort in every direction: it only applies to the `npx` form, it is
/// skipped when asked to be, and a failure is a line in the summary rather
/// than a failed install — the entry that was written is correct either way.
///
/// Whenever [`resolve_fast_command`] got as far as asking `npx` anything, it
/// already ran this fetch — asking the package a question downloads it first —
/// so the caller clears `Ctx::prewarm` and this does not run a second time.
/// The match below is the remaining guard: a resolved binary or launcher is
/// not the `npx` form and needs no warming either way.
fn prewarm(ctx: &Ctx<'_>) -> Option<String> {
    if !ctx.prewarm {
        return None;
    }
    let McpCommand::Npx { version } = ctx.cmd else {
        return None;
    };
    let args = vec![
        "-y".to_string(),
        format!("{NPM_PACKAGE}@{version}"),
        "--version".to_string(),
    ];
    let Some(npx) = ctx.ext.which("npx") else {
        return Some(
            "warning: pre-warm skipped — npx is not on PATH; the first MCP \
             spawn will download the package"
                .to_string(),
        );
    };
    match run_with_timeout(&npx, &args, ctx.ext.prewarm_timeout) {
        Ok(()) => None,
        Err(e) => Some(format!(
            "warning: pre-warm of {NPM_PACKAGE}@{version} failed ({e}) — \
             the first MCP spawn will download the package"
        )),
    }
}

// ---------------------------------------------------------------------------
// MCP JSON merge helpers
// ---------------------------------------------------------------------------

/// Add `mcpServers.mushroomdb` to a JSON config file. Creates the file if
/// absent. No-op if the entry already matches (idempotent). An entry that is
/// present but different is an upgrade: it is rewritten, and the summary says
/// so, because a stale command is exactly the failure this replaces.
///
/// `always_load` adds the `alwaysLoad` key to the entry. It is a parameter
/// rather than a read of `ctx` because it belongs to one platform: the key is
/// Claude Code's, and the Cursor writer passes `false` whatever the flag said.
/// Comparing the whole entry is also what takes the key back off on a
/// re-install without the flag — the desired entry simply no longer has it.
fn merge_mcp_entry(
    mcp_file: &Path,
    ctx: &Ctx<'_>,
    store: &StoreRef,
    always_load: bool,
    manifest: &mut Manifest,
    notes: &mut Vec<String>,
) -> Result<(), CliError> {
    let mut root: serde_json::Value = if mcp_file.exists() {
        let raw = fs::read_to_string(mcp_file)
            .map_err(|e| CliError(format!("cannot read {}: {e}", mcp_file.display())))?;
        serde_json::from_str(&raw)
            .map_err(|e| CliError(format!("invalid JSON in {}: {e}", mcp_file.display())))?
    } else {
        serde_json::json!({})
    };

    // Ensure `mcpServers` object exists.
    if !root["mcpServers"].is_object() {
        root["mcpServers"] = serde_json::json!({});
    }

    let mut desired = ctx.cmd.json_entry("mcp", &store.arg());
    if always_load {
        desired["alwaysLoad"] = serde_json::Value::Bool(true);
    }
    let existing = &root["mcpServers"][SERVER_NAME];

    if existing == &desired {
        return Ok(()); // Exact match — idempotent.
    }
    let replaced = !existing.is_null();

    // Write the entry.
    root["mcpServers"][SERVER_NAME] = desired;

    let parent = mcp_file.parent().unwrap_or(Path::new("."));
    fs::create_dir_all(parent)
        .map_err(|e| CliError(format!("cannot create {}: {e}", parent.display())))?;

    let json = serde_json::to_string_pretty(&root)
        .map_err(|e| CliError(format!("cannot serialize mcp json: {e}")))?;
    fs::write(mcp_file, json)
        .map_err(|e| CliError(format!("cannot write {}: {e}", mcp_file.display())))?;

    manifest.mcp_keys.push(ManagedMcpKey {
        file: mcp_file.to_path_buf(),
        server: SERVER_NAME.to_string(),
    });
    if replaced {
        notes.push(format!(
            "updated mcp command in {} → {} mcp {}",
            mcp_file.display(),
            ctx.cmd.shell(),
            store.arg()
        ));
    }

    Ok(())
}

/// Remove `mcpServers.<server>` from a JSON config file. Leaves the file in
/// place (with the key removed) unless `mcpServers` becomes empty, in which
/// case we still leave the file (the user may have other keys).
///
/// Returns whether the key was there. A file that does not hold it is not
/// rewritten at all, for the same reason `drop_hooks` does not: re-serializing
/// a file we take nothing out of would reorder and re-indent the user's keys
/// for no reason.
fn remove_mcp_key(mcp_file: &Path, server: &str) -> Result<bool, CliError> {
    if !mcp_file.exists() {
        return Ok(false);
    }
    let raw = fs::read_to_string(mcp_file)
        .map_err(|e| CliError(format!("cannot read {}: {e}", mcp_file.display())))?;
    let mut root: serde_json::Value = serde_json::from_str(&raw)
        .map_err(|e| CliError(format!("corrupt mcp json at {}: {e}", mcp_file.display())))?;

    let removed = root["mcpServers"]
        .as_object_mut()
        .is_some_and(|servers| servers.remove(server).is_some());
    if !removed {
        return Ok(false);
    }

    let json = serde_json::to_string_pretty(&root)
        .map_err(|e| CliError(format!("cannot serialize mcp json: {e}")))?;
    fs::write(mcp_file, json)
        .map_err(|e| CliError(format!("cannot write {}: {e}", mcp_file.display())))?;
    Ok(true)
}

// ---------------------------------------------------------------------------
// Manifest helpers
// ---------------------------------------------------------------------------

pub(crate) fn manifest_path(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    platforms: &[Platform],
) -> PathBuf {
    // Codex writes nothing project-local — its registration lives wherever the
    // Codex CLI keeps it — so a Codex-only install records itself under the
    // home directory whatever the scope, in its own file so it cannot collide
    // with a user-scope Claude Code manifest.
    if platforms == [Platform::Codex] {
        return home.join(".mushroomdb").join("install-manifest-codex.json");
    }
    if scope == Scope::User {
        return home.join(".mushroomdb").join("install-manifest.json");
    }
    // Project scope: prefer the Claude Code location; fall back to Cursor.
    if platforms.contains(&Platform::ClaudeCode) {
        project_root
            .join(".claude")
            .join("skills")
            .join("mushroom")
            .join(".install-manifest.json")
    } else {
        project_root.join(".cursor").join(".install-manifest.json")
    }
}

/// Load an existing manifest from `path`. Returns an empty manifest if absent or unparseable.
///
/// A `.gitignore` is never a file this install may delete outright, whatever a
/// manifest says. An earlier 0.6.0 build recorded a `.gitignore` it created in
/// `files`, which the uninstall file loop removes unconditionally — taking any
/// line the user had added to it since. The `gitignore` entry in the same
/// manifest already carries the one line that is ours, and that is the only
/// route by which the file may be touched, so the stale `files` entry is
/// dropped on the way in.
fn load_manifest(path: &Path) -> Manifest {
    let raw = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(_) => return Manifest::default(),
    };
    serde_json::from_str::<Manifest>(&raw)
        .unwrap_or_default()
        .sanitised()
}

/// The door an install opened for the store at `db_dir`.
///
/// The `brief` hook is handed a store, not an install, and its last line says
/// how to reach the graph — so it has to know whether there is a server to
/// name. A project install keeps its manifest beside the skill it wrote, one
/// level up from a default store; a user install keeps it beside the store
/// itself. No manifest there means [`Delivery::Both`]: the reach line names
/// both doors, which is what every install before this flag wired, and naming
/// a door too many costs a reader a moment where naming too few would cost
/// them the graph.
pub fn delivery_for_store(db_dir: &Path) -> Delivery {
    let Some(parent) = db_dir.parent() else {
        return Delivery::default();
    };
    let candidates = [
        parent
            .join(".claude")
            .join("skills")
            .join("mushroom")
            .join(".install-manifest.json"),
        parent.join("install-manifest.json"),
    ];
    for candidate in candidates {
        if candidate.is_file() {
            return load_manifest(&candidate).delivery;
        }
    }
    Delivery::default()
}

/// Whether an install at this scope has been turned off by `disable`. `false`
/// for a scope with no manifest at all — `doctor` falls through to its normal
/// "no config entry" checks in that case rather than reporting a disabled
/// state that was never installed.
pub(crate) fn is_disabled(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    platforms: &[Platform],
) -> bool {
    load_manifest(&manifest_path(project_root, home, scope, platforms)).disabled
}

/// Which of the four opt-in experiments an install asked for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) struct OptIns {
    pub(crate) intercept_grep: bool,
    pub(crate) impact_before_edit: bool,
    pub(crate) enrich_grep: bool,
    pub(crate) always_load: bool,
}

/// What an install at this scope opted into. Every field is `false` for a
/// scope with no manifest, and for a manifest written before the flag existed
/// — `doctor` reports each of these only where one was asked for, because a
/// line about an experiment nobody enabled says something about every install
/// that is true of none.
pub(crate) fn opt_ins(
    project_root: &Path,
    home: &Path,
    scope: Scope,
    platforms: &[Platform],
) -> OptIns {
    let m = load_manifest(&manifest_path(project_root, home, scope, platforms));
    OptIns {
        intercept_grep: m.intercept_grep,
        impact_before_edit: m.impact_before_edit,
        enrich_grep: m.enrich_grep,
        always_load: m.always_load,
    }
}

/// Union `existing` with `this_run`, deduplicating by path (files, git hooks),
/// by (file, server) pair (mcp_keys), and by full equality (hooks, lines).
/// Entries from `this_run` win on collision so the manifest always reflects
/// the latest state.
fn union_manifests(mut existing: Manifest, this_run: &Manifest) -> Manifest {
    for f in &this_run.files {
        if !existing.files.contains(f) {
            existing.files.push(f.clone());
        }
    }
    for k in &this_run.mcp_keys {
        let already = existing
            .mcp_keys
            .iter()
            .any(|e| e.file == k.file && e.server == k.server);
        if !already {
            existing.mcp_keys.push(k.clone());
        }
    }
    for h in &this_run.hooks {
        if !existing.hooks.contains(h) {
            existing.hooks.push(h.clone());
        }
    }
    for h in &this_run.git_hooks {
        if !existing.git_hooks.contains(h) {
            existing.git_hooks.push(h.clone());
        }
    }
    for l in &this_run.gitignore {
        if !existing.gitignore.contains(l) {
            existing.gitignore.push(l.clone());
        }
    }
    existing.codex |= this_run.codex;
    if let Some(c) = &this_run.requested_cmd {
        existing.requested_cmd = Some(c.clone());
    }
    // The latest run's door wins: re-installing with a different `--delivery`
    // is how a user changes it, and the manifest has to describe what is on
    // disk now, not what an earlier run put there.
    existing.delivery = this_run.delivery;
    // Same rule for the three experiments (and `run_install_with` prunes the
    // hook entries when the latest run turned one off).
    existing.intercept_grep = this_run.intercept_grep;
    existing.impact_before_edit = this_run.impact_before_edit;
    existing.enrich_grep = this_run.enrich_grep;
    existing.always_load = this_run.always_load;
    existing
}

fn write_manifest(path: &Path, manifest: &Manifest) -> Result<(), CliError> {
    let parent = path.parent().unwrap_or(Path::new("."));
    fs::create_dir_all(parent).map_err(|e| {
        CliError(format!(
            "cannot create manifest dir {}: {e}",
            parent.display()
        ))
    })?;
    let json = serde_json::to_string_pretty(manifest)
        .map_err(|e| CliError(format!("cannot serialize manifest: {e}")))?;
    fs::write(path, json)
        .map_err(|e| CliError(format!("cannot write manifest {}: {e}", path.display())))?;
    Ok(())
}

// ---------------------------------------------------------------------------
// Git hook block — `mushroomdb sync` after every commit
// ---------------------------------------------------------------------------
//
// A git hook file belongs to the repository owner, not to us. Everything below
// therefore edits one marked region and nothing else: the region is rewritten
// in place when it changes, and removing it restores the user's lines exactly.
// The pure text transforms are split out from the filesystem wrappers so the
// merge and removal rules can be reasoned about — and tested — without a disk.

/// Opening marker of the region this module owns inside a git hook.
pub const HOOK_BEGIN: &str = "# >>> mushroomdb >>>";
/// Closing marker of that region.
pub const HOOK_END: &str = "# <<< mushroomdb <<<";
/// Written as the first line when we create a hook file ourselves.
const HOOK_SHEBANG: &str = "#!/bin/sh";

/// The block a git hook runs: one backgrounded, silenced `sync`.
///
/// Backgrounded (`( … & )` in a subshell, so no job-control notice reaches the
/// terminal) because a hook must not make `git commit` wait on a graph
/// refresh, and silenced because a hook that prints — or fails — on a store
/// that is momentarily busy would be noise on every commit. `sync` exits 3 when
/// another process holds the write lock, and the next commit picks the work up.
///
/// `shell` is the already-quoted command prefix from [`McpCommand::shell`];
/// the store contributes either `--auto` or its own quoted path, since a path
/// with a space in it would otherwise be word-split into two arguments.
///
/// `--auto` is what makes the block correct in a `git worktree`. Git runs a
/// hook with the working tree it acted on as the working directory, so `sync`
/// walks up from there to that tree's own root and updates that tree's own
/// store — the same block, committed once, doing the right thing in every
/// checkout of the repository.
#[must_use]
pub fn git_hook_block(shell: &str, store: &StoreRef) -> String {
    format!(
        "{HOOK_BEGIN}\n( {shell} sync {} >/dev/null 2>&1 & )\n{HOOK_END}\n",
        store.shell_arg()
    )
}

/// What [`strip_hook_block`] found in a hook file.
enum Stripped {
    /// No opening marker: every line belongs to whoever wrote the file.
    Absent,
    /// A complete region was removed; this is what is left.
    Removed(String),
    /// An opening marker with no closing marker. Where our region ends is
    /// unknowable, so nothing may be removed.
    Unterminated,
}

/// `text` with our marked region removed.
///
/// Blank lines left dangling at the end are dropped, so a merge followed by a
/// removal returns the original bytes rather than the original plus the blank
/// separator the merge inserted.
///
/// An opening marker with no closing marker is [`Stripped::Unterminated`]
/// rather than "ours to the end of the file". Someone hand-edited the region,
/// and the lines below the opening marker are now as likely to be theirs as
/// ours — a `make lint` they added under it would be deleted by the guess.
/// Both public helpers turn this into an error and write nothing, which is the
/// same rule the rest of this module follows for a config file whose shape it
/// does not recognise.
fn strip_hook_block(text: &str) -> Stripped {
    let mut kept: Vec<&str> = Vec::new();
    let mut inside = false;
    let mut found = false;
    for line in text.lines() {
        if !inside && line.trim_end() == HOOK_BEGIN {
            inside = true;
            found = true;
            continue;
        }
        if inside {
            if line.trim_end() == HOOK_END {
                inside = false;
            }
            continue;
        }
        kept.push(line);
    }
    if !found {
        return Stripped::Absent;
    }
    if inside {
        return Stripped::Unterminated;
    }
    while kept.last().is_some_and(|l| l.trim().is_empty()) {
        kept.pop();
    }
    let mut out = kept.join("\n");
    if !out.is_empty() {
        out.push('\n');
    }
    Stripped::Removed(out)
}

/// The error both helpers return for [`Stripped::Unterminated`].
fn unterminated(hook_file: &Path) -> CliError {
    CliError(format!(
        "{}: a mushroomdb block opens with `{HOOK_BEGIN}` but never closes \
         — refusing to edit it; delete the block by hand and re-run",
        hook_file.display()
    ))
}

/// What the hook file should contain once `block` is in it.
///
/// Idempotent by construction: any existing region is stripped first and the
/// fresh one appended, so a re-merge of the same block reproduces the same
/// bytes and a merge of a *different* block rewrites in place instead of
/// stacking a second region.
fn merged_hook_text(existing: Option<&str>, block: &str) -> Result<String, ()> {
    let base = match existing {
        None => String::new(),
        Some(text) => match strip_hook_block(text) {
            Stripped::Absent => text.to_string(),
            Stripped::Removed(rest) => rest,
            Stripped::Unterminated => return Err(()),
        },
    };
    let mut lines: Vec<&str> = base.lines().collect();
    while lines.last().is_some_and(|l| l.trim().is_empty()) {
        lines.pop();
    }
    // A file we are creating needs an interpreter line; one the user wrote
    // already has whichever they chose, and we must not add a second.
    if lines.is_empty() {
        lines.push(HOOK_SHEBANG);
    }
    let mut out = lines.join("\n");
    out.push_str("\n\n");
    out.push_str(block);
    Ok(out)
}

/// Whether `text` is nothing but an interpreter line — the shape a hook file we
/// created is left in once our region is stripped out of it.
fn only_a_shebang(text: &str) -> bool {
    text.lines()
        .filter(|l| !l.trim().is_empty())
        .all(|l| l.starts_with("#!"))
}

/// Put the sync block in `hook_file`, creating the file (mode 755, with a
/// `#!/bin/sh` line) if it is not there. Returns whether anything changed.
///
/// Every line the user has in the file is preserved, and running this twice
/// with the same arguments writes nothing the second time. A file whose
/// mushroomdb block was hand-edited so its closing marker is gone is an error
/// and is left byte-for-byte alone; see [`strip_hook_block`].
pub fn merge_git_hook(hook_file: &Path, shell: &str, store: &StoreRef) -> Result<bool, CliError> {
    let existing = if hook_file.exists() {
        Some(
            fs::read_to_string(hook_file)
                .map_err(|e| CliError(format!("cannot read {}: {e}", hook_file.display())))?,
        )
    } else {
        None
    };
    let next = merged_hook_text(existing.as_deref(), &git_hook_block(shell, store))
        .map_err(|()| unterminated(hook_file))?;
    if existing.as_deref() == Some(next.as_str()) {
        return Ok(false);
    }
    let parent = hook_file.parent().unwrap_or(Path::new("."));
    fs::create_dir_all(parent)
        .map_err(|e| CliError(format!("cannot create {}: {e}", parent.display())))?;
    fs::write(hook_file, &next)
        .map_err(|e| CliError(format!("cannot write {}: {e}", hook_file.display())))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        // git ignores a hook that is not executable, so this is not cosmetic.
        fs::set_permissions(hook_file, fs::Permissions::from_mode(0o755)).map_err(|e| {
            CliError(format!(
                "cannot make {} executable: {e}",
                hook_file.display()
            ))
        })?;
    }
    Ok(true)
}

/// Take the sync block back out of `hook_file`. Returns whether anything
/// changed.
///
/// The file itself is deleted only when nothing but an interpreter line is
/// left, which is exactly the state a hook *we* created is in — a hook the user
/// wrote has their lines in it and is rewritten rather than removed. An empty
/// stub of theirs would be deleted too, which git cannot tell apart from the
/// stub never having existed.
///
/// An unterminated block is an error and the file is left alone; see
/// [`strip_hook_block`].
pub fn remove_git_hook(hook_file: &Path) -> Result<bool, CliError> {
    if !hook_file.exists() {
        return Ok(false);
    }
    let existing = fs::read_to_string(hook_file)
        .map_err(|e| CliError(format!("cannot read {}: {e}", hook_file.display())))?;
    let next = match strip_hook_block(&existing) {
        // None of it is ours; leave the file untouched.
        Stripped::Absent => return Ok(false),
        Stripped::Removed(rest) => rest,
        Stripped::Unterminated => return Err(unterminated(hook_file)),
    };
    if only_a_shebang(&next) {
        fs::remove_file(hook_file)
            .map_err(|e| CliError(format!("cannot remove {}: {e}", hook_file.display())))?;
        return Ok(true);
    }
    fs::write(hook_file, next)
        .map_err(|e| CliError(format!("cannot write {}: {e}", hook_file.display())))?;
    Ok(true)
}

// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------

/// True if the file exists and its content equals `expected`.
fn file_matches(path: &Path, expected: &str) -> bool {
    fs::read_to_string(path)
        .map(|s| s == expected)
        .unwrap_or(false)
}