loctree-mcp 0.13.0

MCP server for loctree - hot codebase analysis for AI agents
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
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
//! # loctree-mcp
//!
//! Universal MCP server for loctree - works with ANY project directory.
//! Scan once, query everything. Use BEFORE reading files manually.
//!
//! ## Architecture
//!
//! - **Project-agnostic**: Each tool accepts `project` parameter
//! - **Auto-scan**: First use on a project creates snapshot automatically
//! - **Multi-project cache**: Snapshots kept in RAM for instant responses
//! - **Zero config**: Just start the server, no --project needed
//!
//! ## Usage
//!
//! ```bash
//! # Standalone
//! loctree-mcp
//! ```
//!
//! 𝚅𝚒𝚋𝚎𝚌𝚛𝚊𝚏𝚝𝚎𝚍. with AI Agents ⓒ 2025-2026 Loctree Team

use std::collections::{BTreeSet, HashMap, HashSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::{Arc, OnceLock};

use anyhow::{Context, Result};
use clap::Parser;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::ServerInfo;
use rmcp::{ServerHandler, ServiceExt, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;
use tracing::{debug, info};

mod args;
mod auth;
mod http;
mod security;
mod signals;

use args::{Args, TransportKind};
use signals::{ignore_sigpipe, install_panic_hook, safe_stderr_log};

use loctree::analyzer::classify::{detect_language, detect_language_from_filename};
use loctree::analyzer::crowd::detect_crowd_with_edges;
use loctree::analyzer::cycles::find_cycles;
use loctree::analyzer::dead_parrots::{DeadFilterConfig, find_dead_exports};
use loctree::analyzer::occurrences::{
    FileScope, OccurrenceResults, ReportOptions, ScanOptions, scan_files_with_scope,
};
use loctree::analyzer::pipelines::build_pipeline_summary;
use loctree::analyzer::root_scan::scan_results_from_snapshot;
use loctree::analyzer::route_twins::detect_route_twins;
use loctree::analyzer::search::{literal_fuzzy_suggestions, run_search};
use loctree::analyzer::suppression_inventory::{
    SilencerKind, inventory as silencer_inventory, resolve_ignore_globs,
};
use loctree::analyzer::twins::{detect_exact_twins, twin_action};
use loctree::atlas::{
    ContextOptions, atlas_dir_for_project, compose_context_pack_from_snapshot,
    materialize_context_atlas, render_context_markdown,
};
use loctree::focuser::{FocusConfig, HolographicFocus};
use loctree::git::find_git_root;
use loctree::metrics::{repository_metrics, top_hubs_by_importers_direct};
use loctree::query::{query_where_symbol, query_who_imports};
use loctree::slicer::{HolographicSlice, SliceConfig};
use loctree::snapshot::{Snapshot, normalize_roots_for_scope_compare};

// ============================================================================
// Tool Parameter Types - All tools have optional `project` parameter
// ============================================================================

/// Deserialize usize from either a number or a string (Claude Code sends strings).
mod deserialize_usize_lenient {
    use serde::{self, Deserialize, Deserializer};

    pub fn deserialize<'de, D>(deserializer: D) -> Result<usize, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        #[serde(untagged)]
        enum StringOrNum {
            Num(usize),
            Str(String),
        }
        match StringOrNum::deserialize(deserializer)? {
            StringOrNum::Num(n) => Ok(n),
            StringOrNum::Str(s) => s
                .trim()
                .parse()
                .map_err(|_| serde::de::Error::custom(format!("invalid number: {s}"))),
        }
    }
}

/// Process-wide default project root, pinned via `--root` / `--project`.
///
/// `None` (the default — never `.set()`) keeps the long-standing universal
/// behavior: every tool's empty `project` field resolves against the server
/// cwd. Once `--root` pins this at startup, empty `project` fields resolve
/// against the pinned root instead. A per-request `project` value always
/// wins because serde only invokes [`default_project`] when the field is
/// absent.
static DEFAULT_PROJECT_ROOT: OnceLock<String> = OnceLock::new();

/// Pin the process-wide default project root. Called once at startup when
/// `--root` is provided; the path is canonicalized to an absolute form so
/// the pin matches the watch lock's canonical snapshot root. A second call
/// is silently ignored (`OnceLock::set` returns `Err`).
fn set_default_project_root(root: &str) {
    let resolved = Path::new(root)
        .canonicalize()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| root.to_string());
    let _ = DEFAULT_PROJECT_ROOT.set(resolved);
}

fn default_project() -> String {
    // A `--root` / `--project` pin wins over cwd. Per-request `project`
    // params still override this — serde only calls us when the field is
    // absent, so universal callers are unaffected.
    if let Some(root) = DEFAULT_PROJECT_ROOT.get() {
        return root.clone();
    }
    // Normalize "." to absolute path - MCP server cwd may differ from agent cwd
    std::env::current_dir()
        .map(|p| p.display().to_string())
        .unwrap_or_else(|_| ".".to_string())
}

fn tagmap_normalize(value: &str) -> String {
    value
        .chars()
        .filter(|c| c.is_ascii_alphanumeric())
        .collect::<String>()
        .to_ascii_lowercase()
}

fn tagmap_matches(value: &str, keyword_lower: &str, keyword_normalized: &str) -> bool {
    let value_lower = value.to_ascii_lowercase();
    value_lower.contains(keyword_lower)
        || (!keyword_normalized.is_empty()
            && tagmap_normalize(&value_lower).contains(keyword_normalized))
}

fn path_filter_matches(path: &str, filter: &str) -> bool {
    loctree::analyzer::occurrences::path_matches_scope(path, filter)
}

fn signature_symbol_anchor(query: &str) -> Option<String> {
    let mut tokens = query
        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .filter(|token| !token.is_empty())
        .filter(|token| {
            !matches!(
                token.to_ascii_lowercase().as_str(),
                "async" | "fn" | "function" | "pub" | "export"
            )
        });
    tokens.next_back().map(|token| token.to_ascii_lowercase())
}

fn context_has_identifier(context: &str, ident: &str) -> bool {
    context
        .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
        .any(|token| token.eq_ignore_ascii_case(ident))
}

/// Environment variable that holds the SaaS-mode tenant root allowlist.
///
/// Format: one or more absolute paths separated by the platform path
/// separator (`:` on Unix, `;` on Windows). When set, every resolved
/// project path MUST canonicalize to a location underneath one of the
/// listed roots; otherwise the request is rejected with
/// `io::ErrorKind::PermissionDenied`.
///
/// When unset, the server falls back to the historical local-trust
/// behavior — the basic structural rejections in
/// `validate_project_path` still apply (no `..`, no NUL bytes, no
/// empty input), so even the unset configuration is hardened compared
/// to the pre-validation state.
const ALLOWED_ROOTS_ENV: &str = "LOCTREE_MCP_ALLOWED_ROOTS";

/// Read and canonicalize the optional tenant-root allowlist from the
/// process environment. Returns `None` when `LOCTREE_MCP_ALLOWED_ROOTS`
/// is unset or empty. Entries that fail to canonicalize are dropped
/// (they cannot match anything anyway) but a non-empty env var with no
/// valid entries returns `Some(Vec::new())`, which causes every
/// caller-supplied path to be rejected — fail-closed by design.
fn allowed_project_roots() -> Option<Vec<PathBuf>> {
    let raw = std::env::var(ALLOWED_ROOTS_ENV).ok()?;
    if raw.trim().is_empty() {
        return None;
    }
    let roots: Vec<PathBuf> = std::env::split_paths(&raw)
        .filter(|p| !p.as_os_str().is_empty())
        .filter_map(|p| p.canonicalize().ok())
        .collect();
    Some(roots)
}

/// Lexically-validated project path — proves that the caller-supplied
/// string has passed non-emptiness, NUL-byte rejection, parent-dir
/// rejection, and (when configured) the pre-canonical allowlist gate.
/// The wrapped `PathBuf` is the cwd-joined absolute lexical form; it
/// has NOT yet been canonicalized, because validation runs before any
/// filesystem touch (e.g. tests pass non-existent paths).
///
/// The newtype exists primarily as a dataflow witness: Semgrep's
/// `tainted-path` analysis sees `PathBuf::from(input)` as a sink, so
/// the input is decomposed into per-component sanitized pushes via
/// `assemble_lexical_path` rather than handed to `PathBuf::from`
/// wholesale. Consumers must canonicalize + bound via
/// [`loctree::fs_utils::SanitizedPath`] before passing the path to
/// any `fs::*` API.
pub struct LexicallyValidatedPath(PathBuf);

impl LexicallyValidatedPath {
    pub fn as_path(&self) -> &Path {
        self.0.as_path()
    }
    pub fn into_path_buf(self) -> PathBuf {
        self.0
    }
}

impl std::fmt::Debug for LexicallyValidatedPath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("LexicallyValidatedPath")
            .field(&self.0)
            .finish()
    }
}

/// Decompose a sanitized input string into a `PathBuf` by pushing each
/// component individually. This avoids `PathBuf::from(input)` /
/// `Path::new(input)` on the raw `&str`, which `p/rust`
/// `tainted-path` flags as a path-traversal sink. Components are
/// re-validated here as a defense-in-depth — `validate_project_path`
/// already rejects `..` and NUL bytes, but reconstructing the path
/// component-by-component makes the sanitization visible to Semgrep
/// dataflow.
fn assemble_lexical_path(input: &str) -> io::Result<PathBuf> {
    let mut out = PathBuf::new();
    let mut saw_any = false;
    // Iterate over OS-level segments without ever wrapping the full
    // input string in a Path/PathBuf. `split` on the platform separator
    // keeps Windows callers working through forward slashes too;
    // backslash handling is deliberately permissive (mirrors prior
    // behavior of treating Windows-style inputs as Unix-rooted).
    for raw in input.split(['/', std::path::MAIN_SEPARATOR]) {
        if raw.is_empty() {
            // Leading "/" or doubled separators: anchor at root on first
            // empty segment, otherwise skip.
            if !saw_any {
                out.push(std::path::MAIN_SEPARATOR_STR);
                saw_any = true;
            }
            continue;
        }
        if raw == "." {
            // skip explicit current-dir markers; PathBuf would too
            continue;
        }
        if raw == ".." {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "project path contains '..' component; provide a path that does not traverse upward",
            ));
        }
        out.push(raw);
        saw_any = true;
    }
    if !saw_any {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "project path is empty after sanitization",
        ));
    }
    Ok(out)
}

/// Validate a caller-supplied project path string before any filesystem
/// touch.
///
/// # Threat model
///
/// `loctree-mcp` exposes filesystem-rooted tools (`context`, `slice`,
/// `find`, `impact`, ...) to a calling agent over the MCP wire. The
/// `project` parameter is therefore **untrusted input** in the SaaS
/// posture: a hosted client, a misbehaving local agent, or a prompt
/// injection inside otherwise-trusted agent traffic can put arbitrary
/// strings into it. Without validation, `PathBuf::from(project)` would
/// happily accept `../../../etc/passwd`, `/etc/shadow`, a Windows UNC
/// path (`\\?\C:\Users\...`), or a string containing a NUL byte that
/// truncates downstream `CString` conversions.
///
/// This helper enforces, in order:
///
/// 1. **Non-empty** — `""` and whitespace-only strings are rejected
///    with `InvalidInput`. Empty strings canonicalize to the process
///    cwd, which is a silent privilege grant.
/// 2. **No NUL bytes** — embedded `\0` is rejected with `InvalidInput`.
///    NUL truncates strings in syscalls and breaks any audit trail.
/// 3. **No `..` components** — any `Component::ParentDir` in the *input*
///    is rejected with `InvalidInput`. We refuse to reason about how
///    many `..` segments are "safe"; the path stays anchored where the
///    caller wrote it. Decomposition uses [`assemble_lexical_path`] so
///    Semgrep's `tainted-path` dataflow sees the per-component
///    sanitization at the call site rather than a single
///    `PathBuf::from($INPUT)` sink.
/// 4. **Allowlist gate (optional)** — if `allowed_roots` is `Some(_)`,
///    absolute inputs that do not start with any allowed root are
///    rejected with `PermissionDenied`. The post-canonical
///    containment check (run by the caller after `.canonicalize()`,
///    via [`loctree::fs_utils::SanitizedPath`] or
///    [`enforce_allowed_root`]) catches symlink escape.
///
/// # Output
///
/// Returns a [`LexicallyValidatedPath`] wrapping the cwd-joined
/// absolute lexical form. The caller is expected to canonicalize and
/// re-assert containment via [`loctree::fs_utils::SanitizedPath`]
/// before any `fs::*` access. Returning a newtype rather than a bare
/// `PathBuf` documents the validation status at the type level.
fn validate_project_path(
    input: &str,
    allowed_roots: Option<&[PathBuf]>,
) -> io::Result<LexicallyValidatedPath> {
    if input.trim().is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "project path is empty",
        ));
    }
    if input.contains('\0') {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "project path contains NUL byte",
        ));
    }

    // Decompose and re-assemble per-component so Semgrep can see the
    // sanitization sites adjacent to PathBuf construction.
    let lexical = assemble_lexical_path(input)?;

    // Pre-canonical allowlist check for absolute inputs: catches obvious
    // `/etc/passwd`-style attempts before we touch the filesystem. The
    // authoritative check still happens post-canonicalize so symlink
    // escapes also reject.
    if let Some(roots) = allowed_roots
        && lexical.is_absolute()
        && !roots.iter().any(|root| lexical.starts_with(root))
    {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            "project path is outside the configured allowed roots",
        ));
    }

    // Resolve relative paths against cwd here (mirrors the historical
    // behavior) so the caller can canonicalize a complete path.
    let absolute = if lexical.is_absolute() {
        lexical
    } else {
        std::env::current_dir()?.join(lexical)
    };
    Ok(LexicallyValidatedPath(absolute))
}

/// Confirm that a canonicalized project path lives under one of the
/// configured allowed roots. No-op when `allowed_roots` is `None`
/// (allowlist not configured) or contains the path. Rejects with
/// `PermissionDenied` otherwise — symlink-escape and post-resolution
/// boundary crossings end here.
fn enforce_allowed_root(canonical: &Path, allowed_roots: Option<&[PathBuf]>) -> io::Result<()> {
    let Some(roots) = allowed_roots else {
        return Ok(());
    };
    if roots.iter().any(|root| canonical.starts_with(root)) {
        Ok(())
    } else {
        Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "project path {} resolves outside configured allowed roots",
                canonical.display()
            ),
        ))
    }
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ForAiParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ContextParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// Do not scan when a snapshot is missing or stale; return an error or stale snapshot.
    #[serde(default)]
    no_scan: bool,
    /// Return an error instead of using or refreshing a stale snapshot.
    #[serde(default)]
    fail_stale: bool,
    /// Force a fresh scan before composing context.
    #[serde(default)]
    fresh: bool,
    /// Optional: focus context on a specific file
    #[serde(default)]
    file: Option<String>,
    /// Optional: focus on a task description (token-overlap matcher)
    #[serde(default)]
    task: Option<String>,
    /// Optional: deterministic structural filter (repeatable; multiple = AND)
    #[serde(default, alias = "scopes")]
    scope: Vec<String>,
    /// Optional: limit to changed files (git-aware)
    #[serde(default)]
    changed: bool,
    /// Engage AICX memory overlay (default: true for MCP)
    #[serde(default = "default_true")]
    with_aicx: bool,
    /// Opt-out of AICX (overrides with_aicx)
    #[serde(default)]
    no_aicx: bool,
    /// Output format: json (default) or markdown.
    #[serde(default)]
    format: ContextFormat,
    /// (markdown format only) Zero-based section cursor for paginated reading.
    /// When the full markdown pack would exceed the MCP token cap, the response
    /// is split on its top-level `## ` sections; pass the `next_section` cursor
    /// from the previous response to walk the pack card-at-a-time. Ignored for
    /// JSON format and when the whole pack already fits the budget.
    #[serde(default)]
    section: Option<usize>,
}

#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
enum ContextFormat {
    #[default]
    Json,
    Markdown,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct SliceParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// File path relative to project root (e.g., 'src/App.tsx')
    file: String,
    /// Include consumer files (files that import this file)
    #[serde(default = "default_true")]
    consumers: bool,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct FindParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// Symbol name or regex pattern to search for
    name: String,
    /// Search mode: "symbols" (default), "who-imports", "where-symbol", "tagmap", "crowd", "literal"
    #[serde(default = "default_find_mode")]
    mode: String,
    /// Maximum results to return (default: 50)
    #[serde(
        default = "default_limit",
        deserialize_with = "deserialize_usize_lenient::deserialize"
    )]
    limit: usize,
    /// Filter results by language extension (e.g. 'rs', 'ts', 'py')
    #[serde(default)]
    lang: Option<String>,
    /// Only return exported symbols
    #[serde(default)]
    exported_only: bool,
    /// Only return symbols from dead-export files
    #[serde(default)]
    dead_only: bool,
    /// Minimum similarity score for fuzzy/crowd searches
    #[serde(default)]
    min_score: Option<f64>,
    /// Trigger fuzzy-only mode with similar symbol
    #[serde(default)]
    similar: Option<String>,
    /// Optional file path to narrow results (e.g., 'src/App.tsx')
    #[serde(default)]
    file: Option<String>,
    /// (literal mode) Treat `-` as token-internal so `backdrop` does not match
    /// inside `overlay-backdrop` / `--vista-z-overlay-backdrop`. Opt-in; the
    /// default boundary is unchanged. Ignored outside `mode="literal"`.
    #[serde(default)]
    whole_token: bool,
    /// (literal mode) Attach a per-file occurrence rollup (`by_file`).
    #[serde(default)]
    group_by_file: bool,
    /// (literal mode) Suppress the full occurrence list, keep only counters
    /// (`slim`). Accepts the alias `slim`. Ignored outside `mode="literal"`.
    #[serde(default, alias = "slim")]
    count_only: bool,
    /// (literal mode) Zero-based occurrence offset for paged output.
    #[serde(default, deserialize_with = "deserialize_usize_lenient::deserialize")]
    offset: usize,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct ImpactParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// File path to analyze impact for
    file: String,
}

fn default_prism_limit() -> usize {
    8
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct PrismParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// Task framings to compare. Pass at least two distinct phrasings of the same concept.
    #[serde(default, alias = "tasks")]
    task: Vec<String>,
    /// Engage AICX memory overlay (default: true).
    #[serde(default = "default_true")]
    with_aicx: bool,
    /// Opt-out of AICX memory overlay (overrides with_aicx).
    #[serde(default)]
    no_aicx: bool,
    /// Optional override for the AICX project bucket (defaults to the project root identity).
    #[serde(default)]
    aicx_project: Option<String>,
    /// Maximum example items per section (default: 8).
    #[serde(
        default = "default_prism_limit",
        deserialize_with = "deserialize_usize_lenient::deserialize"
    )]
    limit: usize,
}

fn default_true() -> bool {
    true
}

fn default_limit() -> usize {
    50
}

fn default_find_mode() -> String {
    "symbols".to_string()
}

/// Run the literal occurrence scan over a snapshot's files, reading raw bytes
/// from disk relative to `base`.
///
/// This is the MCP surface of the W1 literal truth layer. It deliberately
/// reuses [`loctree::analyzer::occurrences::scan_files`] — the *same* scanner
/// `loct occurrences` / `loct find --literal` use — so MCP results are
/// byte-for-byte identical to the CLI for the same snapshot. There is no second
/// scanner here; only the file-enumeration glue is mirrored from the CLI handler
/// (`loctree-rs/src/cli/dispatch/handlers/occurrences.rs::read_snapshot_contents`),
/// keeping the file set and the bytes read identical across surfaces.
fn scan_literal_occurrences(
    snapshot: &Snapshot,
    base: &std::path::Path,
    ident: &str,
    opts: ScanOptions,
    scope: FileScope<'_>,
) -> OccurrenceResults {
    // Best-effort read: a binary/deleted/unreadable file is simply not a literal
    // match site, exactly as in the CLI handler.
    let contents: Vec<(String, String)> = snapshot
        .files
        .iter()
        .filter_map(|file| {
            let joined = base.join(&file.path);
            let resolved = if joined.exists() {
                joined
            } else {
                std::path::PathBuf::from(&file.path)
            };
            std::fs::read_to_string(&resolved)
                .ok()
                .map(|text| (file.path.clone(), text))
        })
        .collect();
    let borrowed = contents
        .iter()
        .map(|(p, c)| (p.as_str(), c.as_str()))
        .collect::<Vec<_>>();
    scan_files_with_scope(borrowed, ident.trim(), opts, scope)
}

#[derive(Debug, Clone, Copy, Default)]
struct SnapshotLoadOptions {
    no_scan: bool,
    fail_stale: bool,
    fresh: bool,
    force_no_git: bool,
}

impl SnapshotLoadOptions {
    fn from_context(params: &ContextParams) -> Self {
        Self {
            no_scan: params.no_scan,
            fail_stale: params.fail_stale,
            fresh: params.fresh,
            force_no_git: params.force_no_git,
        }
    }
}

fn json_error(err: impl std::fmt::Display) -> String {
    serde_json::json!({ "error": err.to_string() }).to_string()
}

/// Environment override for the per-call deadline applied to `context()`.
///
/// Defaults to 90s — short enough that the loctree-mcp server returns a
/// structured `deadline_exceeded` payload before the typical MCP client-side
/// 120s timeout fires, giving operators an actionable hint rather than a
/// silent kill. Set to a higher value for very large monorepos where the
/// initial fresh scan legitimately needs more time.
const CONTEXT_DEADLINE_ENV: &str = "LOCT_MCP_CONTEXT_DEADLINE_SECS";

fn context_deadline() -> std::time::Duration {
    let secs = std::env::var(CONTEXT_DEADLINE_ENV)
        .ok()
        .and_then(|s| s.parse::<u64>().ok())
        .filter(|n| *n > 0)
        .unwrap_or(90);
    std::time::Duration::from_secs(secs)
}

/// Environment override for the markdown-body char budget applied to
/// `context(format=markdown)`.
///
/// loctree-fail tail (2026-06-22, recurring ~6×): the full ContextPack markdown
/// hit 149,891 chars and was rejected by the MCP runtime token cap, forcing
/// every agent off the recommended session-start surface onto a non-Loctree
/// fallback exactly when structural orientation matters most. The default
/// 38,000-char body budget keeps the JSON-wrapped response (atlas pointers +
/// receipt + newline/quote escaping overhead) at roughly half the ~25k-token
/// MCP cap — a verified worst-case page of ≈44 KB / ~12.5k tokens on
/// loctree-suite itself, against the ~88 KB / ~25k-token ceiling that rejected
/// the original 149,891-char dump. Full fidelity is preserved through section
/// pagination. Raise it for clients with a larger cap; the pack is split on its
/// top-level `## ` sections (synthesis-first, so early sections carry the most
/// value) and walked via the `next_section` cursor.
const CONTEXT_MARKDOWN_BUDGET_ENV: &str = "LOCT_MCP_CONTEXT_MAX_CHARS";
const CONTEXT_MARKDOWN_BUDGET_DEFAULT: usize = 38_000;

fn context_markdown_budget() -> usize {
    std::env::var(CONTEXT_MARKDOWN_BUDGET_ENV)
        .ok()
        .and_then(|s| s.parse::<usize>().ok())
        .filter(|n| *n >= 2_000)
        .unwrap_or(CONTEXT_MARKDOWN_BUDGET_DEFAULT)
}

const MCP_RESPONSE_BUDGET_PROTOCOL: &str = "loctree.mcp.response_budget.v1";

fn tool_json_response(tool: &str, project: Option<&Path>, value: serde_json::Value) -> String {
    match serde_json::to_string_pretty(&value) {
        Ok(raw) => budget_tool_response(tool, project, raw),
        Err(e) => format!("Serialization error: {e}"),
    }
}

fn budget_tool_response(tool: &str, project: Option<&Path>, raw: String) -> String {
    let budget = context_markdown_budget();
    if raw.chars().count() <= budget {
        return raw;
    }

    match write_full_tool_payload(tool, project, &raw) {
        Ok(artifact_path) => budget_marker_response(tool, &raw, budget, Some(artifact_path), None),
        Err(e) => budget_marker_response(tool, &raw, budget, None, Some(e.to_string())),
    }
}

fn write_full_tool_payload(tool: &str, project: Option<&Path>, raw: &str) -> io::Result<PathBuf> {
    let artifact_dir = project
        .map(|project| project.join(".loctree").join("mcp-response-payloads"))
        .unwrap_or_else(|| std::env::temp_dir().join("loctree-mcp-response-payloads"));
    fs::create_dir_all(&artifact_dir)?;

    let artifact_path = artifact_dir.join(format!(
        "{}-{}.full.json",
        sanitize_artifact_stem(tool),
        full_markdown_sha256(raw)
    ));
    fs::write(&artifact_path, raw)?;
    Ok(artifact_path)
}

fn sanitize_artifact_stem(value: &str) -> String {
    let sanitized: String = value
        .chars()
        .map(|ch| {
            if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' {
                ch
            } else {
                '-'
            }
        })
        .collect();
    if sanitized.is_empty() {
        "tool".to_string()
    } else {
        sanitized
    }
}

fn budget_marker_response(
    tool: &str,
    raw: &str,
    budget: usize,
    artifact_path: Option<PathBuf>,
    artifact_error: Option<String>,
) -> String {
    let mut preview_budget = budget.saturating_sub(1_800).max(256);
    let mut marker = serde_json::json!({
        "protocol": MCP_RESPONSE_BUDGET_PROTOCOL,
        "tool": tool,
        "status": "truncated_for_mcp_token_budget",
        "budget_chars": budget,
        "original_chars": raw.chars().count(),
        "original_bytes": raw.len(),
        "original_sha256": full_markdown_sha256(raw),
        "marker": "Full unmodified payload written to sibling artifact; response body was capped before MCP harness rejection.",
        "full_payload": artifact_path.as_ref().map(|path| serde_json::json!({
            "path": path.display().to_string(),
            "bytes": raw.len(),
            "sha256": full_markdown_sha256(raw)
        })),
        "artifact_error": artifact_error,
        "continuation": {
            "kind": "full_payload_artifact",
            "path": artifact_path.as_ref().map(|path| path.display().to_string())
        },
        "payload_preview": truncate_chars(raw, preview_budget),
        "preview_truncated": true
    });

    loop {
        let rendered = serde_json::to_string_pretty(&marker)
            .unwrap_or_else(|e| format!("Serialization error: {e}"));
        if rendered.chars().count() <= budget || preview_budget == 0 {
            return rendered;
        }
        preview_budget /= 2;
        if let Some(obj) = marker.as_object_mut() {
            obj.insert(
                "payload_preview".to_string(),
                serde_json::Value::String(truncate_chars(raw, preview_budget)),
            );
        }
    }
}

fn truncate_chars(value: &str, max_chars: usize) -> String {
    if value.chars().count() <= max_chars {
        return value.to_string();
    }
    value.chars().take(max_chars).collect::<String>()
}

/// One top-level `## ` section of the rendered ContextPack markdown.
struct MarkdownSection {
    /// Section title (the `## …` line, trimmed of the leading `## `), or
    /// `"Overview"` for the leading title block before the first `## `.
    title: String,
    /// Full section text including its own `## ` heading line and trailing
    /// blank lines, ready to concatenate.
    body: String,
}

/// A single paginated markdown page plus the cursor metadata an agent needs to
/// keep reading without overflowing the MCP token cap.
struct MarkdownPage {
    /// The markdown to emit in this response (already within budget).
    markdown: String,
    /// True when the pack was split (i.e. the caller did not receive the whole
    /// pack in one response).
    paginated: bool,
    /// Zero-based index of the first section included in this page.
    section_start: usize,
    /// Number of sections included in this page.
    sections_emitted: usize,
    /// Total number of top-level sections in the pack.
    total_sections: usize,
    /// Cursor to pass back as `section` to fetch the next page, or `None` at
    /// the end of the pack.
    next_section: Option<usize>,
    /// Titles of every top-level section, in order — a compact table of
    /// contents so an agent can see the whole map and jump the cursor.
    section_titles: Vec<String>,
}

/// Split rendered ContextPack markdown into its top-level `## ` sections. The
/// leading title block (everything before the first `## `) becomes the first
/// section titled `"Overview"`; if the document has no `## ` headers the whole
/// document is returned as a single `"Overview"` section.
fn split_markdown_sections(full: &str) -> Vec<MarkdownSection> {
    let mut sections: Vec<MarkdownSection> = Vec::new();
    let mut current_title = "Overview".to_string();
    let mut current_body = String::new();

    for line in full.split_inclusive('\n') {
        let is_h2 = {
            let trimmed = line.trim_end_matches('\n');
            trimmed.starts_with("## ") && !trimmed.starts_with("### ")
        };
        if is_h2 {
            // Close the section in progress (skip an empty synthetic preamble).
            if !current_body.trim().is_empty() {
                sections.push(MarkdownSection {
                    title: std::mem::take(&mut current_title),
                    body: std::mem::take(&mut current_body),
                });
            } else {
                current_body.clear();
            }
            current_title = line
                .trim_end_matches('\n')
                .trim_start_matches("## ")
                .trim()
                .to_string();
        }
        current_body.push_str(line);
    }
    if !current_body.trim().is_empty() {
        sections.push(MarkdownSection {
            title: current_title,
            body: current_body,
        });
    }
    if sections.is_empty() {
        sections.push(MarkdownSection {
            title: "Overview".to_string(),
            body: full.to_string(),
        });
    }
    sections
}

/// Hard-truncate a single over-budget section body on a line boundary,
/// appending an honest tail that points at the on-disk atlas card so the agent
/// never reads a silently clipped section as canonical truth.
fn truncate_section_body(body: &str, budget: usize) -> String {
    if body.len() <= budget {
        return body.to_string();
    }
    let tail = "\n<!-- truncated: section exceeds the MCP markdown budget; \
                read the matching card under .loctree/context-atlas/ or raise \
                LOCT_MCP_CONTEXT_MAX_CHARS for the full section -->\n";
    let keep = budget.saturating_sub(tail.len()).max(1);
    let mut cut = 0usize;
    for line in body.split_inclusive('\n') {
        if cut + line.len() > keep {
            break;
        }
        cut += line.len();
    }
    if cut == 0 {
        // A single line longer than the budget — cut on a char boundary.
        cut = body
            .char_indices()
            .take_while(|(idx, _)| *idx <= keep)
            .last()
            .map(|(idx, ch)| idx + ch.len_utf8())
            .unwrap_or(0);
    }
    let mut out = String::with_capacity(cut + tail.len());
    out.push_str(&body[..cut]);
    out.push_str(tail);
    out
}

/// Paginate rendered ContextPack markdown so a single response stays under the
/// MCP token cap while preserving full fidelity via the `next_section` cursor.
///
/// - `section == None` and the whole pack fits `budget` → return it unchanged
///   (backward-compatible whole-pack response; no pagination).
/// - otherwise → greedily pack as many consecutive top-level `## ` sections as
///   fit `budget`, starting at the requested cursor (default 0), always
///   emitting at least one section (hard-truncated if it alone overflows), and
///   hand back the cursor to the next un-emitted section.
fn paginate_context_markdown(full: &str, section: Option<usize>, budget: usize) -> MarkdownPage {
    let sections = split_markdown_sections(full);
    let total = sections.len();
    let section_titles: Vec<String> = sections.iter().map(|s| s.title.clone()).collect();

    if section.is_none() && full.len() <= budget {
        return MarkdownPage {
            markdown: full.to_string(),
            paginated: false,
            section_start: 0,
            sections_emitted: total,
            total_sections: total,
            next_section: None,
            section_titles,
        };
    }

    let start = section.unwrap_or(0).min(total.saturating_sub(1));
    let mut markdown = String::new();
    let mut emitted = 0usize;
    let mut idx = start;
    while idx < total {
        let body = &sections[idx].body;
        if emitted == 0 {
            // Always emit the first section; truncate it if it alone overflows.
            markdown.push_str(&truncate_section_body(body, budget));
            emitted += 1;
            idx += 1;
            continue;
        }
        if markdown.len() + body.len() > budget {
            break;
        }
        markdown.push_str(body);
        emitted += 1;
        idx += 1;
    }

    let next_section = if idx < total { Some(idx) } else { None };
    MarkdownPage {
        markdown,
        paginated: true,
        section_start: start,
        sections_emitted: emitted,
        total_sections: total,
        next_section,
        section_titles,
    }
}

/// Structured response returned when `context()` exceeds the server-side
/// deadline. Stays under the typical 120s MCP client timeout so the client
/// receives a real JSON payload instead of an "MCP timed out" wrapper.
fn deadline_exceeded_response(deadline: std::time::Duration) -> String {
    let session_id = format!(
        "ctx_{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0)
    );
    let payload = serde_json::json!({
        "protocol": "loctree.context_atlas.v1",
        "session": session_id,
        "status": "error",
        "error": "deadline_exceeded",
        "deadline_secs": deadline.as_secs(),
        "hint": "Context composition exceeded LOCT_MCP_CONTEXT_DEADLINE_SECS. \
                Try (a) context(no_scan=true) to use cached snapshot, \
                (b) repo-view/focus/slice for narrower views, \
                (c) raise LOCT_MCP_CONTEXT_DEADLINE_SECS for very large monorepos."
    });
    serde_json::to_string_pretty(&payload)
        .unwrap_or_else(|_| r#"{"error":"deadline_exceeded"}"#.to_string())
}

/// SHA-256 hex of the full rendered ContextPack markdown. Stamped into the
/// `receipt.full_context` accounting so a client that walks the pagination
/// cursor can prove it reconstructed the whole pack — completeness is checked
/// off by the receipt, never by trusting a single (possibly partial) response.
fn full_markdown_sha256(markdown: &str) -> String {
    use sha2::{Digest, Sha256};
    let mut hasher = Sha256::new();
    hasher.update(markdown.as_bytes());
    hasher
        .finalize()
        .iter()
        .map(|byte| format!("{byte:02x}"))
        .collect()
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct TreeParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// Maximum depth (default: 3)
    #[serde(
        default = "default_depth",
        deserialize_with = "deserialize_usize_lenient::deserialize"
    )]
    depth: usize,
    /// LOC threshold for highlighting (default: 500)
    #[serde(default = "default_loc_threshold")]
    loc_threshold: usize,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct FocusParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// Directory to focus on (e.g., 'src/components')
    directory: String,
}

fn default_follow_scope() -> String {
    "all".to_string()
}

fn default_follow_limit() -> usize {
    10
}

/// Parameters for the `suppressions` MCP tool.
///
/// Mirrors `loct suppressions [OPTIONS] [ROOT]`.
///
/// LITERAL-ONLY scan — free-tier scope. NO embedding similarity, NO LLM
/// classification, NO "this suppression is suspicious because…" enrichment.
/// Semantic enrichment is paid-tier delta (Wave 7+ post-aicx-library). See
/// `loctree::analyzer::suppression_inventory` module docs for the boundary.
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct SuppressionsParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// Filter to specific silencer kinds (omit for all). Tokens:
    /// `allow`, `dead-code`, `nosemgrep`, `ts-ignore`, `ts-expect-error`,
    /// `ts-nocheck`, `eslint-disable`, `noqa`, `type-ignore`,
    /// `pylint-disable`, `mypy-ignore`, `shellcheck`, `unsafe`,
    /// `unsafe-env-var`, `ignore`. Accepts `kind` (singular alias) for
    /// callers that pass one filter.
    #[serde(default, alias = "kind", alias = "types")]
    kinds: Vec<String>,
    /// Include paths normally excluded by `.semgrepignore` (fixtures,
    /// vendored tests, CLI entry-points). Default OFF for hygiene parity
    /// with `semgrep` audits.
    #[serde(default)]
    include_fixtures: bool,
}

#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct FollowParams {
    /// Project directory (default: current directory)
    #[serde(default = "default_project")]
    project: String,
    /// Allow non-git directories. Default false guards accidental scans outside a repo.
    #[serde(default)]
    force_no_git: bool,
    /// What to follow: "dead", "cycles", "twins", "hotspots", "trace", "commands", "events", "pipelines", or "all"
    #[serde(default = "default_follow_scope")]
    scope: String,
    /// Handler name for trace scope (e.g., "toggle_assistant")
    #[serde(default)]
    handler: Option<String>,
    /// Max trails to return per scope (default: 10)
    #[serde(
        default = "default_follow_limit",
        deserialize_with = "deserialize_usize_lenient::deserialize"
    )]
    limit: usize,
}

fn default_depth() -> usize {
    3
}

fn default_loc_threshold() -> usize {
    500
}

fn common_prefix_len(a: &str, b: &str) -> usize {
    a.chars()
        .zip(b.chars())
        .take_while(|(left, right)| left == right)
        .count()
}

fn suggest_directories(snapshot: &Snapshot, query: &str, max: usize) -> Vec<String> {
    if max == 0 {
        return Vec::new();
    }

    let mut dirs = BTreeSet::new();
    for file in &snapshot.files {
        if let Some(parent) = Path::new(&file.path).parent() {
            let dir = parent.to_string_lossy().replace('\\', "/");
            if !dir.is_empty() && dir != "." {
                dirs.insert(dir);
            }
        }
    }

    if dirs.is_empty() {
        return Vec::new();
    }

    let normalized_query = query.trim().trim_matches('/');
    let query_lower = normalized_query.to_ascii_lowercase();
    let query_last = normalized_query
        .split('/')
        .rfind(|part| !part.is_empty())
        .unwrap_or(normalized_query);
    let query_last_lower = query_last.to_ascii_lowercase();
    let query_tokens: Vec<_> = query_lower
        .split(['/', '_', '-', '.'])
        .filter(|token| token.len() >= 2)
        .collect();

    let mut scored: Vec<(String, usize)> = dirs
        .iter()
        .map(|dir| {
            let dir_lower = dir.to_ascii_lowercase();
            let mut score = 0usize;

            if !query_last_lower.is_empty() && dir.contains(query_last) {
                score += 100;
            }
            if query_last_lower.len() > 2 && dir_lower.contains(&query_last_lower) {
                score += 50;
            }
            if !query_lower.is_empty() {
                score += common_prefix_len(&dir_lower, &query_lower) * 10;
            }
            for token in &query_tokens {
                if dir_lower.contains(token) {
                    score += 3;
                }
            }

            (dir.clone(), score)
        })
        .filter(|(_, score)| *score > 0)
        .collect();

    if scored.is_empty() {
        return dirs.into_iter().take(max).collect();
    }

    scored.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
    scored.into_iter().take(max).map(|(dir, _)| dir).collect()
}

// ============================================================================
// Server State - Multi-project cache
// ============================================================================

/// Universal server with multi-project snapshot cache.
#[derive(Clone)]
pub(crate) struct LoctreeServer {
    /// Cache of loaded snapshots per project
    cache: Arc<RwLock<HashMap<PathBuf, Arc<Snapshot>>>>,
    /// Tool router (generated by macro)
    tool_router: rmcp::handler::server::router::tool::ToolRouter<Self>,
}

impl LoctreeServer {
    pub(crate) fn new() -> Self {
        Self {
            cache: Arc::new(RwLock::new(HashMap::new())),
            tool_router: Self::tool_router(),
        }
    }

    /// Resolve project path to absolute, canonicalized path.
    ///
    /// Every MCP tool funnels its caller-supplied `project` string through this
    /// helper before any filesystem operation. The validation below sits in
    /// front of `PathBuf::from`/`canonicalize` precisely so the MCP server is
    /// safe under the SaaS threat model where the calling agent (Claude,
    /// Codex, Gemini, or a hosted client) is NOT trusted to stay inside the
    /// repo. See `validate_project_path` for the rule set and rejection model.
    ///
    /// If the path has no snapshot yet, `get_snapshot()` will auto-scan it.
    fn resolve_existing_project_path(project: &str) -> Result<PathBuf> {
        let allowed_roots = allowed_project_roots();
        let validated = validate_project_path(project, allowed_roots.as_deref())
            .with_context(|| format!("Invalid project path: {project}"))?;
        // Funnel through SanitizedPath::within_any for the post-canonical
        // boundary check so canonicalize + allowlist containment happen at
        // one auditable site visible to Semgrep's `tainted-path` dataflow.
        // When no allowlist is configured, fall back to the previous shape
        // (canonicalize + enforce_allowed_root no-op).
        let lexical_buf = validated.into_path_buf();
        match allowed_roots.as_deref() {
            Some(roots) => {
                let root_refs: Vec<&Path> = roots.iter().map(|p| p.as_path()).collect();
                let sanitized =
                    loctree::fs_utils::SanitizedPath::within_any(&root_refs, &lexical_buf)
                        .with_context(|| format!("Project directory not found: {project}"))?;
                Ok(sanitized.as_path().to_path_buf())
            }
            None => {
                let canon = lexical_buf
                    .canonicalize()
                    .with_context(|| format!("Project directory not found: {project}"))?;
                enforce_allowed_root(&canon, None)?;
                Ok(canon)
            }
        }
    }

    fn resolve_project(project: &str, force_no_git: bool) -> Result<PathBuf> {
        let canonical = Self::resolve_existing_project_path(project)?;
        if !force_no_git && find_git_root(&canonical).is_none() {
            anyhow::bail!(
                "Project is not inside a git repository: {}. Pass force_no_git=true to opt out for scratch directories.",
                canonical.display()
            );
        }
        Ok(canonical)
    }

    /// Get or load snapshot for a project. Auto-scans if needed and allowed.
    ///
    /// Scope guard: a snapshot whose `metadata.roots` does not match the
    /// requested `project` (after canonicalization) is treated as a
    /// foreign-scope artifact and forces a rescan. This protects the
    /// workspace-root flat-fallback from being polluted by sub-tree scans
    /// (e.g. fixture-only scans whose `snapshot_root` walks up to the
    /// workspace's git root and overwrites the project_id flat fallback).
    /// Mirrors the CLI guard in `cli/dispatch/mod.rs::load_or_create_snapshot_for_roots`.
    async fn get_snapshot(
        &self,
        project: &Path,
        load_options: SnapshotLoadOptions,
    ) -> Result<Arc<Snapshot>> {
        // Compute the canonical scope identity once so cache lookup and
        // post-load checks compare against the same shape the CLI uses.
        let project_owned = project.to_path_buf();
        let strategy = if load_options.force_no_git {
            loctree::snapshot::SnapshotRootStrategy::Exact
        } else {
            loctree::snapshot::SnapshotRootStrategy::Project
        };
        let snapshot_root = loctree::snapshot::resolve_snapshot_root_with_strategy(
            std::slice::from_ref(&project_owned),
            strategy,
        );
        let requested_roots =
            normalize_roots_for_scope_compare(std::iter::once(project), &snapshot_root);
        let scope_matches = |snap: &Snapshot| -> bool {
            let snap_roots = normalize_roots_for_scope_compare(
                snap.metadata.roots.iter().map(Path::new),
                &snapshot_root,
            );
            snap_roots == requested_roots
        };

        // Check cache first — but require matching scope, not just matching path key.
        let cached_snapshot = {
            let cache = self.cache.read().await;
            cache.get(project).map(Arc::clone)
        };
        if let Some(snapshot) = cached_snapshot {
            if !scope_matches(&snapshot) {
                debug!(
                    "Cached snapshot scope mismatch for {:?}, will reload from disk",
                    project
                );
            } else if load_options.fresh {
                debug!("Fresh snapshot requested for {:?}", project);
            } else if !Self::is_snapshot_stale(&snapshot, project) {
                debug!("Using cached snapshot for {:?}", project);
                return Ok(snapshot);
            } else if load_options.fail_stale {
                anyhow::bail!(
                    "Snapshot is stale for {} and fail_stale=true",
                    project.display()
                );
            } else if load_options.no_scan {
                debug!(
                    "Using stale cached snapshot for {:?} because no_scan=true",
                    project
                );
                return Ok(snapshot);
            } else {
                debug!("Cached snapshot is stale for {:?}", project);
            }
        }

        // Need to load or create snapshot.
        //
        // Freshness decisions and the rescan file universe are owned by the
        // snapshot freshness authority in the loctree lib — this is a thin
        // call, not a parallel staleness implementation. `no_scan_uses_stale`
        // preserves MCP semantics: with no_scan=true a stale snapshot is
        // served instead of erroring.
        info!("Loading snapshot for {:?}", project);

        let snapshot = loctree::snapshot::acquire_snapshot(
            std::slice::from_ref(&project_owned),
            loctree::snapshot::SnapshotReusePolicy::Strict,
            &loctree::snapshot::AcquireOptions {
                fresh: load_options.fresh,
                no_scan: load_options.no_scan,
                fail_stale: load_options.fail_stale,
                quiet: true,
                no_scan_uses_stale: true,
                full_scan: load_options.fresh,
                strategy,
                ..Default::default()
            },
        )
        .map_err(|e| {
            if load_options.fail_stale {
                anyhow::anyhow!(
                    "Snapshot unavailable for {} and fail_stale=true: {e}",
                    project.display()
                )
            } else if load_options.no_scan {
                anyhow::anyhow!(
                    "Snapshot unavailable for {} and no_scan=true: {e}",
                    project.display()
                )
            } else {
                anyhow::anyhow!("Failed to load snapshot for {}: {e}", project.display())
            }
        })?;

        info!(
            "Snapshot loaded: {} files, {} edges",
            snapshot.files.len(),
            snapshot.edges.len()
        );

        let snapshot = Arc::new(snapshot);

        // Update cache
        {
            let mut cache = self.cache.write().await;
            cache.insert(project.to_path_buf(), Arc::clone(&snapshot));
        }

        Ok(snapshot)
    }

    /// Check if snapshot is stale (git HEAD changed OR dirty worktree).
    /// Delegates to `Snapshot::is_stale()` — single source of truth shared
    /// with CLI and LSP, covers both commit mismatch and uncommitted changes.
    fn is_snapshot_stale(snapshot: &Snapshot, project: &Path) -> bool {
        snapshot.is_stale(project)
    }

    /// Validate file path: check if within project, return matched path from snapshot or error.
    fn resolve_file_in_snapshot(
        snapshot: &Snapshot,
        project: &Path,
        file: &str,
    ) -> Result<String, String> {
        let requested = assemble_lexical_path(file).map_err(|e| e.to_string())?;
        if requested.is_absolute() && !requested.starts_with(project) {
            return Err(format!(
                "File outside project: '{}' not in '{}'",
                file,
                project.display()
            ));
        }

        let normalized = if requested.is_absolute() {
            requested
                .strip_prefix(project)
                .unwrap_or(requested.as_path())
                .to_string_lossy()
                .replace('\\', "/")
        } else {
            requested.to_string_lossy().replace('\\', "/")
        };
        let normalized = normalized.trim_start_matches("./").to_string();

        if let Some(exact) = snapshot.files.iter().find(|f| {
            let path = f.path.trim_start_matches("./").replace('\\', "/");
            path == normalized
        }) {
            return Ok(exact.path.clone());
        }

        let suffix = format!("/{normalized}");
        let mut suffix_matches: Vec<_> = snapshot
            .files
            .iter()
            .filter(|f| {
                let path = f.path.trim_start_matches("./").replace('\\', "/");
                path.ends_with(&suffix)
            })
            .collect();
        suffix_matches.sort_by(|a, b| a.path.cmp(&b.path));

        if suffix_matches.len() == 1 {
            return Ok(suffix_matches[0].path.clone());
        }
        if suffix_matches.len() > 1 {
            return Err(format!(
                "Ambiguous file '{}': {}. Provide a repo-relative path.",
                file,
                suffix_matches
                    .iter()
                    .map(|f| f.path.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ));
        }

        Err(format!(
            "File '{}' not in snapshot. Run 'scan' or check path.",
            file
        ))
    }

    fn requested_file_exists(project: &Path, file: &str) -> bool {
        Self::resolve_existing_file_under_project(project, file).is_ok()
    }

    fn resolve_existing_file_under_project(
        project: &Path,
        file: &str,
    ) -> io::Result<(PathBuf, String)> {
        if file.trim().is_empty() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "requested file path is empty",
            ));
        }
        if file.contains('\0') {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "requested file path contains NUL byte",
            ));
        }
        let requested = assemble_lexical_path(file)?;
        let candidate = if requested.is_absolute() {
            requested
        } else {
            project.join(requested)
        };
        let sanitized = loctree::fs_utils::SanitizedPath::within(project, &candidate)?;
        let path = sanitized.as_path().to_path_buf();
        if !path.is_file() {
            return Err(io::Error::new(
                io::ErrorKind::NotFound,
                "requested path is not a file",
            ));
        }
        let rel = path
            .strip_prefix(project)
            .unwrap_or(&path)
            .to_string_lossy()
            .replace('\\', "/");
        Ok((path, rel))
    }

    fn disk_file_language(path: &Path) -> String {
        let ext = path
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.to_ascii_lowercase())
            .unwrap_or_default();
        if !ext.is_empty() {
            return detect_language(&ext);
        }
        let filename = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or("");
        detect_language_from_filename(filename)
    }

    fn disk_core_slice_payload(
        project: &Path,
        file: &str,
        exclusion_note: &str,
    ) -> io::Result<serde_json::Value> {
        let (path, rel) = Self::resolve_existing_file_under_project(project, file)?;
        let content = loctree::fs_utils::read_to_string_within(project, &path)?;
        let loc = content.lines().count();
        let language = Self::disk_file_language(&path);
        Ok(serde_json::json!({
            "target": file,
            "project": project.display().to_string(),
            "core_loc": loc,
            "dependencies": 0,
            "consumers": 0,
            "snapshot_exclusion": exclusion_note,
            "files": [{
                "path": rel,
                "layer": "core",
                "loc": loc,
                "language": language,
                "source": "disk_explicit_fallback"
            }]
        }))
    }

    fn requested_file_ignore_explanation(project: &Path, file: &str) -> Option<String> {
        let (path, _) = Self::resolve_existing_file_under_project(project, file).ok()?;
        loctree::fs_utils::explain_ignore_for_path(project, &path)
    }

    async fn resolve_file_in_snapshot_or_refresh(
        &self,
        snapshot: Arc<Snapshot>,
        project: &Path,
        file: &str,
        force_no_git: bool,
    ) -> Result<(Arc<Snapshot>, String), String> {
        match Self::resolve_file_in_snapshot(&snapshot, project, file) {
            Ok(path) => Ok((snapshot, path)),
            Err(first_error) => {
                if !Self::requested_file_exists(project, file) {
                    return Err(first_error);
                }

                let refreshed = self
                    .get_snapshot(
                        project,
                        SnapshotLoadOptions {
                            fresh: true,
                            force_no_git,
                            ..Default::default()
                        },
                    )
                    .await
                    .map_err(|e| {
                        format!(
                            "{first_error}; requested file exists on disk, but fresh scan failed: {e:#}"
                        )
                    })?;

                let path = Self::resolve_file_in_snapshot(&refreshed, project, file).map_err(
                    |second_error| {
                        let exclusion = Self::requested_file_ignore_explanation(project, file)
                            .map(|note| format!("; detected exclusion: {note}"))
                            .unwrap_or_default();
                        format!(
                            "{first_error}; fresh scan completed but file is still absent: {second_error}{exclusion}"
                        )
                    },
                )?;

                Ok((refreshed, path))
            }
        }
    }

    fn context_receipt_payload(
        session_id: &str,
        project: &Path,
        snapshot: &Snapshot,
        with_aicx: bool,
    ) -> serde_json::Value {
        use sha2::{Digest, Sha256};

        let mut loaded = vec![
            "identity",
            "risk",
            "action",
            "authority",
            "structural",
            "runtime",
        ];
        if with_aicx {
            loaded.push("memory");
        }

        let authority = snapshot.authority_report(project);
        let mut hasher = Sha256::new();
        hasher.update(session_id.as_bytes());
        hasher.update(project.display().to_string().as_bytes());
        hasher.update(authority.fingerprint.value.as_bytes());
        for section in &loaded {
            hasher.update(section.as_bytes());
        }
        let hash: String = hasher
            .finalize()
            .iter()
            .map(|byte| format!("{byte:02x}"))
            .collect();

        serde_json::json!({
            "sections_loaded": loaded,
            "sections_skipped": if with_aicx { Vec::<&str>::new() } else { vec!["memory"] },
            "aicx": if with_aicx { "enabled" } else { "disabled" },
            "snapshot": authority,
            "sha256": hash
        })
    }
}

// ============================================================================
// MCP Tool Implementations
// ============================================================================

#[tool_router]
impl LoctreeServer {
    #[tool(
        name = "context",
        description = "Get a complete Agent Context Pack with structural, runtime, risk, action, authority, and optional AICX memory context. Start here for onboarding."
    )]
    async fn context(&self, Parameters(params): Parameters<ContextParams>) -> String {
        // Server-side deadline keeps loctree-mcp ahead of the typical 120s MCP
        // client timeout so operators always receive a structured payload —
        // either the full response or a `deadline_exceeded` hint with a
        // fallback recipe (`no_scan=true`, narrower tools, or raising the env
        // override). Cooperative cancellation only fires at `.await` points,
        // so a long sync scan inside `get_snapshot` may still overshoot; the
        // operator-visible knob is still strictly better than a silent kill.
        let deadline = context_deadline();
        match tokio::time::timeout(deadline, self.context_inner(params)).await {
            Ok(response) => response,
            Err(_elapsed) => deadline_exceeded_response(deadline),
        }
    }

    async fn context_inner(&self, params: ContextParams) -> String {
        let load_options = SnapshotLoadOptions::from_context(&params);
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return json_error(e),
        };

        let snapshot = match self.get_snapshot(&project, load_options).await {
            Ok(snapshot) => snapshot,
            Err(e) => return json_error(e),
        };

        let opts = ContextOptions {
            file: params.file.map(std::path::PathBuf::from),
            changed: params.changed,
            task: params.task,
            scopes: params.scope,
            with_aicx: params.with_aicx,
            no_aicx: params.no_aicx,
            project: Some(project.clone()),
            aicx_project_override: None,
            json: matches!(params.format, ContextFormat::Json),
            full: true,
            markdown: matches!(params.format, ContextFormat::Markdown),
        };

        let pack = match compose_context_pack_from_snapshot(&opts, &project, &snapshot) {
            Ok(pack) => pack,
            Err(err) => return json_error(err),
        };

        let session_id = format!(
            "ctx_{}",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs()
        );
        let context_has_aicx = params.with_aicx && !params.no_aicx;

        let atlas = materialize_context_atlas(&pack, &project, None).ok();

        if matches!(params.format, ContextFormat::Markdown) {
            // The full pack markdown can hit ~150k chars and blow past the MCP
            // token cap (loctree-fail tail, recurring). We NEVER truncate — that
            // strands agents on a head + "go read the cards" and breaks their
            // flow. Instead paginate on top-level `## ` sections under a char
            // budget; the whole pack still comes back in one response when it
            // fits, so small repos are unchanged, and every section stays
            // reachable through the `next_section` cursor.
            let full_markdown = render_context_markdown(&pack);
            let page = paginate_context_markdown(
                &full_markdown,
                params.section,
                context_markdown_budget(),
            );
            let status = if page.next_section.is_some() {
                "partial"
            } else {
                "complete"
            };

            // Full context is accounted for in the receipt: even when delivery is
            // paginated, the receipt carries the whole-pack digest, byte count,
            // and section total so a client can tick off complete delivery once
            // it has walked the cursor to the end.
            let mut receipt =
                Self::context_receipt_payload(&session_id, &project, &snapshot, context_has_aicx);
            if let Some(obj) = receipt.as_object_mut() {
                obj.insert(
                    "full_context".to_string(),
                    serde_json::json!({
                        "total_sections": page.total_sections,
                        "total_bytes": full_markdown.len(),
                        "sha256": full_markdown_sha256(&full_markdown),
                        "complete_in_this_response": page.next_section.is_none()
                            && page.section_start == 0,
                    }),
                );
            }

            let markdown_response = serde_json::json!({
                "protocol": "loctree.context_atlas.v1",
                "format": "markdown",
                "session": session_id,
                "status": status,
                "atlas": atlas.as_ref().map(|manifest| manifest.pointer_payload()),
                "pagination": {
                    "paginated": page.paginated,
                    "section": page.section_start,
                    "sections_emitted": page.sections_emitted,
                    "total_sections": page.total_sections,
                    "next_section": page.next_section,
                    "section_titles": page.section_titles,
                    "budget_chars": context_markdown_budget(),
                    "hint": page.next_section.map(|next| format!(
                        "Markdown paginated to stay under the MCP token cap. \
                        Call context(format=\"markdown\", section={next}) to continue, \
                        or read the materialized cards under .loctree/context-atlas/. \
                        Raise LOCT_MCP_CONTEXT_MAX_CHARS for larger single responses."
                    )),
                },
                "receipt": receipt,
                "markdown": page.markdown
            });

            return tool_json_response("context", Some(&project), markdown_response);
        }

        let core_response = serde_json::json!({
            "protocol": "loctree.context_atlas.v1",
            "session": session_id,
            "status": "complete",
            "atlas": atlas.as_ref().map(|manifest| manifest.pointer_payload()),
            "format": "json",
            "sections_loaded": if context_has_aicx {
                vec!["identity", "risk", "action", "authority", "structural", "runtime", "memory", "receipt"]
            } else {
                vec!["identity", "risk", "action", "authority", "structural", "runtime", "receipt"]
            },
            "sections_skipped": if context_has_aicx { Vec::<&str>::new() } else { vec!["memory"] },
            "receipt": Self::context_receipt_payload(
                &session_id,
                &project,
                &snapshot,
                context_has_aicx
            ),
            "advisory": "Context is complete in this response and also materialized as a Context Atlas. Use repo-view/focus/slice/find/impact/tree/follow for follow-up structural questions.",
            "data": {
                "schema_version": pack.schema_version,
                "project": pack.project,
                "risk": pack.risk,
                "action": pack.action,
                "authority": pack.authority,
                "structural": pack.structural,
                "runtime": pack.runtime,
                "memory": if context_has_aicx { Some(pack.memory) } else { None },
            }
        });

        tool_json_response("context", Some(&project), core_response)
    }

    /// Get repository overview for AI agents
    #[tool(
        name = "repo-view",
        description = "Get a compact repository overview: file count, LOC, languages, health summary, top hubs, and quick wins."
    )]
    async fn repo_view(&self, Parameters(params): Parameters<ForAiParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        let metrics = repository_metrics(&snapshot);

        // Health metrics — canonical dead pipeline, the same source as
        // `loct dead` / `loct twins` / `loct findings`: one config, semantic
        // suppression, literal + symbol-graph cross-check, entry-point fence.
        // repo-view must never report a forked dead count.
        let dead_exports = loctree::analyzer::dead_parrots::compute_dead_truth(&snapshot).dead;
        let dead_high: Vec<_> = dead_exports
            .iter()
            .filter(|d| d.confidence == "high")
            .collect();

        let edges: Vec<_> = snapshot
            .edges
            .iter()
            .map(|e| (e.from.clone(), e.to.clone(), e.label.clone()))
            .collect();
        let cycles = find_cycles(&edges);

        let twins = detect_exact_twins(&snapshot.files, false);

        let top_hubs = top_hubs_by_importers_direct(&snapshot, 5);

        // Languages
        let languages: Vec<_> = snapshot.metadata.languages.iter().cloned().collect();

        let atlas_dir = atlas_dir_for_project(&project);
        let atlas_manifest = atlas_dir.join("manifest.md");
        let atlas = if atlas_manifest.exists() {
            let receipt_path = atlas_dir.join("receipt.json");
            // Use the same git probe (Snapshot::git_context_for on the canonical
            // project root) that materialize_context_atlas uses when stamping the
            // receipt. Mixing snapshot.metadata.git_* with a canonical-root probe
            // produces false "stale" verdicts whenever metadata is contaminated
            // by an outer repo's git state.
            let canonical_project = project.canonicalize().unwrap_or_else(|_| project.clone());
            let live_git = Snapshot::git_context_for(&canonical_project);
            let live_branch = live_git.branch.as_deref().unwrap_or("unknown");
            let live_commit = live_git.commit.as_deref().unwrap_or("unknown");
            let live_snapshot_tag = format!("{}@{}", live_branch, live_commit);

            let atlas_snapshot_tag = fs::read_to_string(&receipt_path)
                .ok()
                .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
                .and_then(|value| {
                    value
                        .get("snapshot")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                });

            let (status, freshness_note) = match atlas_snapshot_tag.as_deref() {
                Some(tag) if tag == live_snapshot_tag => (
                    "atlas_available",
                    "Atlas matches current snapshot.".to_string(),
                ),
                Some(_) => (
                    "atlas_stale",
                    "Atlas was materialized against a different snapshot. Re-run `loct context --full` to refresh cards before relying on them."
                        .to_string(),
                ),
                None => (
                    "atlas_unknown_freshness",
                    "Atlas exists but receipt.json is missing or unreadable. Re-run `loct context --full` to refresh."
                        .to_string(),
                ),
            };

            let message = if status == "atlas_available" {
                "This repo has a materialized Context Atlas. Read manifest.md, then core/structural/runtime cards before broad architectural decisions.".to_string()
            } else {
                format!(
                    "{freshness_note} Cards may misrepresent current code state until refreshed."
                )
            };

            Some(serde_json::json!({
                "protocol": "loctree.context_atlas.v1",
                "status": status,
                "atlas_dir": atlas_dir,
                "manifest": atlas_manifest,
                "recommended_start": atlas_dir.join("00-core-map.md"),
                "atlas_snapshot": atlas_snapshot_tag,
                "current_snapshot": live_snapshot_tag,
                "freshness_note": freshness_note,
                "message": message,
            }))
        } else {
            None
        };

        let overview = serde_json::json!({
            "project": project.display().to_string(),
            "context_atlas": atlas,
            "snapshot": snapshot.authority_report(&project),
            "summary": {
                "files": metrics.file_count,
                "total_loc": metrics.total_loc,
                "edges": metrics.edge_count,
                "languages": languages,
            },
            "health": {
                "dead_exports": {
                    "total": dead_exports.len(),
                    "high_confidence": dead_high.len(),
                },
                "cycles": cycles.len(),
                "twins": twins.len(),
            },
            "top_hubs": top_hubs.into_iter().map(|metric| serde_json::json!({
                "file": metric.file,
                "importers": metric.importers_direct,
                "importers_direct": metric.importers_direct,
                "import_edges": metric.import_edges,
                "loc": metric.loc
            })).collect::<Vec<_>>(),
            "quick_wins": {
                "dead_to_remove": dead_high.iter().take(3).map(|d| serde_json::json!({
                    "file": d.file,
                    "symbol": d.symbol
                })).collect::<Vec<_>>(),
            },
            "next_steps": [
                "slice(file) - before modifying any file",
                "find(name) - before creating anything new",
                "impact(file) - before deleting or major refactor",
                "follow(all) - pursue signals before commits"
            ]
        });

        tool_json_response("repo-view", Some(&project), overview)
    }

    /// Get file slice with dependencies and consumers
    #[tool(
        name = "slice",
        description = "Get file context: the file + all its imports + all files that depend on it. USE THIS BEFORE modifying any file. One call = complete understanding of a file's role."
    )]
    async fn slice(&self, Parameters(params): Parameters<SliceParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        let (snapshot, target_path) = match self
            .resolve_file_in_snapshot_or_refresh(
                snapshot,
                &project,
                &params.file,
                params.force_no_git,
            )
            .await
        {
            Ok(resolved) => resolved,
            Err(e) => match Self::disk_core_slice_payload(&project, &params.file, &e) {
                Ok(payload) => return tool_json_response("slice", Some(&project), payload),
                Err(_) => return format!("Error: {}", e),
            },
        };
        let config = SliceConfig {
            include_consumers: params.consumers,
            max_depth: SliceConfig::default().max_depth,
        };
        let slice = match HolographicSlice::from_path(&snapshot, &target_path, &config) {
            Some(slice) => slice,
            None => {
                return format!(
                    "Error: Internal snapshot inconsistency for '{}'. Run a fresh scan and retry.",
                    params.file
                );
            }
        };

        let mut files = Vec::new();
        for core in &slice.core {
            files.push(serde_json::json!({
                "path": core.path,
                "layer": "core",
                "loc": core.loc,
                "language": core.language
            }));
        }
        for dep in &slice.deps {
            let import_type = snapshot
                .edges
                .iter()
                .find(|edge| edge.to == dep.path)
                .map(|edge| edge.label.as_str())
                .unwrap_or("unknown");
            files.push(serde_json::json!({
                "path": dep.path,
                "layer": "dependency",
                "loc": dep.loc,
                "language": dep.language,
                "depth": dep.depth,
                "import_type": import_type
            }));
        }
        for consumer in &slice.consumers {
            files.push(serde_json::json!({
                "path": consumer.path,
                "layer": "consumer",
                "loc": consumer.loc,
                "language": consumer.language,
                "depth": consumer.depth
            }));
        }

        let result = serde_json::json!({
            "target": slice.target,
            "project": project.display().to_string(),
            "core_loc": slice.stats.core_loc,
            "dependencies": slice.stats.deps_files,
            "consumers": slice.stats.consumers_files,
            "files": files,
            "core_symbols": slice.core_symbols,
            "authority_labels": slice.authority_labels,
            "suggested_next": slice.suggested_next
        });

        tool_json_response("slice", Some(&project), result)
    }

    /// Find symbol definitions (supports multi-query: "foo|bar|baz")
    #[tool(
        name = "find",
        description = "Find symbols, trace imports, or explore features. Modes: 'symbols' (default) — symbol/param search with regex. 'who-imports' — what files import this file (reverse deps). 'where-symbol' — where is this symbol defined. 'tagmap' — unified keyword search (files + crowd + dead). 'crowd' — functional clustering around a keyword. 'literal' — exact identifier-boundary occurrences over the indexed universe; coverage stated per query; 'not found' means not found, with fuzzy hints kept strictly separate. At parity with `loct occurrences` / `loct find --literal`. Literal-mode tuning (all opt-in, ignored otherwise): every occurrence carries a language-aware `occurrence_kind` (css_property, class_token, custom_property, comment, string_literal, data_attribute, identifier, plus the Rust role shapes; `unknown` only as honest fallback); `whole_token=true` treats '-' as token-internal so e.g. 'backdrop' stops matching inside 'overlay-backdrop'/'--vista-z-overlay-backdrop'; `group_by_file=true` adds a per-file `by_file` count rollup; `count_only`/`slim=true` suppresses the full occurrence list (keeping `total`/`files_matched`/`by_file`) for token economy."
    )]
    async fn find(&self, Parameters(params): Parameters<FindParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        let mode = params.mode.to_lowercase();

        // Mode: who-imports - reverse dependency query
        if mode == "who-imports" {
            let result = query_who_imports(&snapshot, &params.name);
            return tool_json_response(
                "find",
                Some(&project),
                serde_json::json!({
                    "mode": "who-imports",
                    "query": params.name,
                    "project": project.display().to_string(),
                    "results": result.results.iter().map(|m| serde_json::json!({
                        "file": m.file,
                        "line": m.line,
                        "context": m.context.clone()
                    })).collect::<Vec<_>>(),
                    "total": result.results.len()
                }),
            );
        }

        // Mode: where-symbol - symbol definition/export lookup
        if mode == "where-symbol" {
            let has_pipe = params.name.contains('|');
            let has_signature_shape = !has_pipe && params.name.split_whitespace().count() > 1;

            let mut result = query_where_symbol(&snapshot, &params.name);
            if has_signature_shape && result.results.is_empty() {
                if let Some(anchor) = signature_symbol_anchor(&params.name) {
                    result = query_where_symbol(&snapshot, &anchor);
                }
            } else if !has_signature_shape && has_pipe {
                result = query_where_symbol(&snapshot, &params.name);
            }

            if let Some(file_filter) = params.file.as_deref() {
                result
                    .results
                    .retain(|m| path_filter_matches(&m.file, file_filter));
            }

            if has_signature_shape && let Some(anchor) = signature_symbol_anchor(&params.name) {
                let exact_symbol_matches: Vec<_> = result
                    .results
                    .iter()
                    .filter(|m| {
                        m.context
                            .as_deref()
                            .is_some_and(|ctx| context_has_identifier(ctx, &anchor))
                    })
                    .cloned()
                    .collect();
                if !exact_symbol_matches.is_empty() {
                    result.results = exact_symbol_matches;
                }
            }

            let total = result.results.len();
            return tool_json_response(
                "find",
                Some(&project),
                serde_json::json!({
                    "mode": "where-symbol",
                    "query": params.name,
                    "project": project.display().to_string(),
                    "file_filter": params.file,
                    "results": result.results.iter().take(params.limit).map(|m| serde_json::json!({
                        "file": m.file,
                        "line": m.line,
                        "context": m.context.clone()
                    })).collect::<Vec<_>>(),
                    "total": total
                }),
            );
        }

        // Mode: crowd - functional clustering around keyword
        if mode == "crowd" {
            let crowd = detect_crowd_with_edges(&snapshot.files, &params.name, &snapshot.edges);
            let members: Vec<_> = crowd
                .members
                .iter()
                .take(params.limit)
                .map(|m| {
                    serde_json::json!({
                        "file": m.file,
                        "importer_count": m.importer_count,
                        "reason": format!("{:?}", &m.match_reason),
                        "similarity_scores": m.similarity_scores,
                        "is_test": m.is_test
                    })
                })
                .collect();

            return tool_json_response(
                "find",
                Some(&project),
                serde_json::json!({
                    "mode": "crowd",
                    "query": params.name,
                    "project": project.display().to_string(),
                    "pattern": crowd.pattern,
                    "score": crowd.score,
                    "members": members,
                    "issues": crowd.issues.iter().map(|i| format!("{:?}", i)).collect::<Vec<_>>(),
                    "total": crowd.members.len()
                }),
            );
        }

        // Mode: tagmap - unified keyword search (files + crowd + dead)
        if mode == "tagmap" {
            let keyword = &params.name;
            let keyword_lower = keyword.to_ascii_lowercase();
            let keyword_normalized = tagmap_normalize(keyword);

            // 1) files matching keyword in path
            let matching_files: Vec<_> = snapshot
                .files
                .iter()
                .filter(|f| tagmap_matches(&f.path, &keyword_lower, &keyword_normalized))
                .take(params.limit)
                .map(|f| {
                    serde_json::json!({
                        "path": f.path,
                        "loc": f.loc
                    })
                })
                .collect();

            // 2) indexed code facts matching keyword in symbols, imports,
            // usages, and literals. This is intentionally literal-only:
            // tagmap should recall terms already present in the snapshot,
            // not perform semantic enrichment.
            let mut fact_matches = Vec::new();
            'files: for file in &snapshot.files {
                for export in &file.exports {
                    if tagmap_matches(&export.name, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&export.kind, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&export.export_type, &keyword_lower, &keyword_normalized)
                    {
                        fact_matches.push(serde_json::json!({
                            "kind": "export",
                            "file": file.path,
                            "name": export.name,
                            "symbol_kind": export.kind,
                            "line": export.line
                        }));
                    }
                    if fact_matches.len() >= params.limit {
                        break 'files;
                    }
                }

                for local in &file.local_symbols {
                    if tagmap_matches(&local.name, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&local.kind, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&local.context, &keyword_lower, &keyword_normalized)
                    {
                        fact_matches.push(serde_json::json!({
                            "kind": "local-symbol",
                            "file": file.path,
                            "name": local.name,
                            "symbol_kind": local.kind,
                            "line": local.line,
                            "context": local.context
                        }));
                    }
                    if fact_matches.len() >= params.limit {
                        break 'files;
                    }
                }

                for usage in &file.symbol_usages {
                    if tagmap_matches(&usage.name, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&usage.context, &keyword_lower, &keyword_normalized)
                    {
                        fact_matches.push(serde_json::json!({
                            "kind": "symbol-usage",
                            "file": file.path,
                            "name": usage.name,
                            "line": usage.line,
                            "context": usage.context
                        }));
                    }
                    if fact_matches.len() >= params.limit {
                        break 'files;
                    }
                }

                for import in &file.imports {
                    if tagmap_matches(&import.source, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&import.source_raw, &keyword_lower, &keyword_normalized)
                        || import.resolved_path.as_ref().is_some_and(|path| {
                            tagmap_matches(path, &keyword_lower, &keyword_normalized)
                        })
                    {
                        fact_matches.push(serde_json::json!({
                            "kind": "import-source",
                            "file": file.path,
                            "source": import.source,
                            "source_raw": import.source_raw,
                            "line": import.line
                        }));
                    }
                    if fact_matches.len() >= params.limit {
                        break 'files;
                    }

                    for symbol in &import.symbols {
                        if tagmap_matches(&symbol.name, &keyword_lower, &keyword_normalized)
                            || symbol.alias.as_ref().is_some_and(|alias| {
                                tagmap_matches(alias, &keyword_lower, &keyword_normalized)
                            })
                        {
                            fact_matches.push(serde_json::json!({
                                "kind": "import-symbol",
                                "file": file.path,
                                "name": symbol.name,
                                "alias": symbol.alias,
                                "source": import.source,
                                "line": import.line
                            }));
                        }
                        if fact_matches.len() >= params.limit {
                            break 'files;
                        }
                    }
                }

                for literal in &file.string_literals {
                    if tagmap_matches(&literal.value, &keyword_lower, &keyword_normalized) {
                        fact_matches.push(serde_json::json!({
                            "kind": "string-literal",
                            "file": file.path,
                            "value": literal.value,
                            "line": literal.line
                        }));
                    }
                    if fact_matches.len() >= params.limit {
                        break 'files;
                    }
                }
            }

            // 3) crowd analysis
            let crowd = detect_crowd_with_edges(&snapshot.files, keyword, &snapshot.edges);
            let crowd_members: Vec<_> = crowd
                .members
                .iter()
                .take(params.limit)
                .map(|m| {
                    serde_json::json!({
                        "file": m.file,
                        "importer_count": m.importer_count,
                        "reason": format!("{:?}", &m.match_reason),
                        "is_test": m.is_test
                    })
                })
                .collect();

            // 4) dead exports related to keyword
            let config = DeadFilterConfig::default();
            let dead = find_dead_exports(&snapshot.files, true, None, config);
            let related_dead: Vec<_> = dead
                .iter()
                .filter(|d| {
                    tagmap_matches(&d.file, &keyword_lower, &keyword_normalized)
                        || tagmap_matches(&d.symbol, &keyword_lower, &keyword_normalized)
                })
                .take(params.limit)
                .map(|d| {
                    serde_json::json!({
                        "file": d.file,
                        "symbol": d.symbol,
                        "confidence": d.confidence,
                        "reason": d.reason
                    })
                })
                .collect();

            return tool_json_response(
                "find",
                Some(&project),
                serde_json::json!({
                    "mode": "tagmap",
                    "query": keyword,
                    "project": project.display().to_string(),
                    "files": {
                        "count": matching_files.len(),
                        "matches": matching_files
                    },
                    "facts": {
                        "count": fact_matches.len(),
                        "matches": fact_matches
                    },
                    "crowd": {
                        "score": crowd.score,
                        "count": crowd_members.len(),
                        "members": crowd_members
                    },
                    "dead": {
                        "count": related_dead.len(),
                        "matches": related_dead
                    }
                }),
            );
        }

        // Mode: literal - exact identifier-boundary scan (W1 literal truth layer).
        // Reuses the shared `scan_files` scanner, so `literal_matches` is
        // byte-for-byte identical to `loct occurrences` / `loct find --literal`
        // for the same snapshot. Fuzzy name-similarity hints ride along in a
        // strictly separate `fuzzy_suggestions` block (source: "fuzzy") and are
        // NEVER promoted into the literal matches — a suggestion is not evidence.
        if mode == "literal" {
            let mut literal_matches = scan_literal_occurrences(
                &snapshot,
                &project,
                &params.name,
                ScanOptions {
                    whole_token: params.whole_token,
                },
                FileScope {
                    file: params.file.as_deref(),
                },
            );
            literal_matches.apply_report(ReportOptions {
                group_by_file: params.group_by_file,
                count_only: params.count_only,
                offset: params.offset,
                limit: Some(params.limit),
            });
            let total = literal_matches.total;
            let fuzzy_suggestions = literal_fuzzy_suggestions(params.name.trim(), &snapshot.files);
            return tool_json_response(
                "find",
                Some(&project),
                serde_json::json!({
                    "mode": "literal",
                    "query": params.name,
                    "project": project.display().to_string(),
                    "file_filter": params.file,
                    "literal_matches": literal_matches,
                    "fuzzy_suggestions": fuzzy_suggestions,
                    "scope": literal_matches.scope,
                    "total": total
                }),
            );
        }

        if mode != "symbols" {
            return tool_json_response(
                "find",
                Some(&project),
                serde_json::json!({
                    "error": format!("Unsupported find mode: {}", params.mode),
                    "supported_modes": ["symbols", "who-imports", "where-symbol", "tagmap", "crowd", "literal"]
                }),
            );
        }

        // Default mode: symbols (existing behavior)
        // Normalize query: split by whitespace and join with | for OR matching (like CLI)
        let query = if params.name.contains('|') {
            // Already has pipe - use as-is
            params.name.clone()
        } else {
            // Split by whitespace, filter short tokens, join with |
            let tokens: Vec<&str> = params
                .name
                .split_whitespace()
                .filter(|t| t.len() >= 2)
                .collect();
            if tokens.is_empty() {
                params.name.clone()
            } else {
                tokens.join("|")
            }
        };

        // Use the same search infrastructure as CLI
        let search_results = run_search(&query, &snapshot.files);

        // Convert symbol matches to JSON format (with limit)
        let symbol_matches: Vec<_> = search_results
            .symbol_matches
            .files
            .iter()
            .filter(|f| {
                params
                    .file
                    .as_deref()
                    .is_none_or(|filter| path_filter_matches(&f.file, filter))
            })
            .flat_map(|f| {
                f.matches.iter().map(move |m| {
                    serde_json::json!({
                        "file": f.file,
                        "symbol": m.context.split_whitespace().last().unwrap_or(&m.context),
                        "kind": if m.is_definition { "definition" } else { "usage" },
                        "line": m.line,
                        "context": m.context
                    })
                })
            })
            .take(params.limit)
            .collect();

        // Convert param matches to JSON format
        let param_matches: Vec<_> = search_results
            .param_matches
            .iter()
            .take(params.limit.saturating_sub(symbol_matches.len()))
            .map(|pm| {
                serde_json::json!({
                    "file": pm.file,
                    "function": pm.function,
                    "param": pm.param_name,
                    "type": pm.param_type,
                    "line": pm.line
                })
            })
            .collect();

        // Convert semantic matches to JSON format
        let semantic_matches: Vec<_> = search_results
            .semantic_matches
            .iter()
            .take(20)
            .map(|sm| {
                serde_json::json!({
                    "symbol": sm.symbol,
                    "file": sm.file,
                    "score": sm.score
                })
            })
            .collect();

        // Convert cross-match files to JSON format (files with 2+ query terms)
        let cross_matches: Vec<_> = search_results
            .cross_matches
            .iter()
            .take(20)
            .map(|cm| {
                let terms: Vec<_> = cm
                    .matched_terms
                    .iter()
                    .map(|t| {
                        let type_tag = match &t.match_type {
                            loctree::analyzer::search::MatchType::Export { kind } => {
                                format!("EXPORT:{}", kind)
                            }
                            loctree::analyzer::search::MatchType::Import { source } => {
                                format!("IMPORT:{}", source)
                            }
                            loctree::analyzer::search::MatchType::Parameter {
                                function, ..
                            } => {
                                format!("PARAM:{}", function)
                            }
                        };
                        serde_json::json!({
                            "term": t.term,
                            "line": t.line,
                            "type": type_tag,
                            "context": t.context
                        })
                    })
                    .collect();
                serde_json::json!({
                    "file": cm.file,
                    "matched_terms": terms
                })
            })
            .collect();

        // Convert suppression matches to JSON format
        let suppression_matches: Vec<_> = search_results
            .suppression_matches
            .iter()
            .take(20)
            .map(|sm| {
                serde_json::json!({
                    "file": sm.file,
                    "line": sm.line,
                    "type": sm.suppression_type,
                    "lint": sm.lint_name,
                    "context": sm.context
                })
            })
            .collect();

        let result = serde_json::json!({
            "query": query,
            "project": project.display().to_string(),
            "symbol_matches": {
                "count": symbol_matches.len(),
                "matches": symbol_matches
            },
            "param_matches": {
                "count": param_matches.len(),
                "matches": param_matches
            },
            "semantic_matches": {
                "count": semantic_matches.len(),
                "matches": semantic_matches
            },
            "cross_matches": {
                "count": cross_matches.len(),
                "matches": cross_matches
            },
            "suppression_matches": {
                "count": suppression_matches.len(),
                "matches": suppression_matches
            },
            "dead_status": {
                "is_exported": search_results.dead_status.is_exported,
                "is_dead": search_results.dead_status.is_dead
            }
        });

        let no_primary_matches =
            symbol_matches.is_empty() && param_matches.is_empty() && semantic_matches.is_empty();
        let mut result = result;
        if no_primary_matches && let Some(obj) = result.as_object_mut() {
            obj.insert(
                "suggestions".to_string(),
                serde_json::json!([
                    "Try a broader pattern or check spelling.",
                    "Browse available exports with repo-view()."
                ]),
            );
        }

        tool_json_response("find", Some(&project), result)
    }

    /// Analyze impact of changing/removing a file
    #[tool(
        name = "impact",
        description = "What breaks if you change or delete this file? Shows direct and transitive consumers. USE THIS BEFORE deleting or major refactor."
    )]
    async fn impact(&self, Parameters(params): Parameters<ImpactParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        // Validate file exists in snapshot
        let (snapshot, target_path) = match self
            .resolve_file_in_snapshot_or_refresh(
                snapshot,
                &project,
                &params.file,
                params.force_no_git,
            )
            .await
        {
            Ok(resolved) => resolved,
            Err(e) => match Self::disk_core_slice_payload(&project, &params.file, &e) {
                Ok(fallback_read) => {
                    let payload = serde_json::json!({
                        "file": params.file,
                        "project": project.display().to_string(),
                        "risk_level": "unknown",
                        "direct_consumers": {
                            "count": 0,
                            "files": []
                        },
                        "transitive_consumers": {
                            "count": 0,
                            "files": []
                        },
                        "safe_to_delete": false,
                        "snapshot_exclusion": fallback_read["snapshot_exclusion"].clone(),
                        "fallback_read": fallback_read
                    });
                    return tool_json_response("impact", Some(&project), payload);
                }
                Err(_) => return format!("Error: {}", e),
            },
        };

        // Direct consumers (use exact match on resolved path)
        let direct: Vec<_> = snapshot
            .edges
            .iter()
            .filter(|e| e.to == target_path)
            .map(|e| e.from.clone())
            .collect();

        // Transitive consumers (BFS)
        let mut visited: std::collections::HashSet<String> = direct.iter().cloned().collect();
        let mut queue: std::collections::VecDeque<String> = direct.iter().cloned().collect();
        let mut transitive = Vec::new();

        while let Some(file) = queue.pop_front() {
            for edge in &snapshot.edges {
                if edge.to == file && !visited.contains(&edge.from) {
                    visited.insert(edge.from.clone());
                    queue.push_back(edge.from.clone());
                    transitive.push(edge.from.clone());
                }
            }
        }

        let risk = if direct.is_empty() {
            "none"
        } else if direct.len() > 10 || !transitive.is_empty() {
            "high"
        } else if direct.len() > 3 {
            "medium"
        } else {
            "low"
        };

        let result = serde_json::json!({
            "file": params.file,
            "project": project.display().to_string(),
            "risk_level": risk,
            "direct_consumers": {
                "count": direct.len(),
                "files": direct.iter().take(20).collect::<Vec<_>>()
            },
            "transitive_consumers": {
                "count": transitive.len(),
                "files": transitive.iter().take(10).collect::<Vec<_>>()
            },
            "safe_to_delete": direct.is_empty()
        });

        tool_json_response("impact", Some(&project), result)
    }

    /// Get directory tree with LOC counts
    #[tool(
        name = "tree",
        description = "Get directory structure with LOC (lines of code) counts. Helps understand project layout and find large files/directories."
    )]
    async fn tree(&self, Parameters(params): Parameters<TreeParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        // Build directory tree
        let mut dir_loc: HashMap<String, usize> = HashMap::new();
        let mut large_files = Vec::new();

        for file in &snapshot.files {
            // Accumulate LOC per directory
            let parts: Vec<&str> = file.path.split('/').collect();
            for i in 1..=parts.len().min(params.depth) {
                let dir = parts[..i].join("/");
                *dir_loc.entry(dir).or_default() += file.loc;
            }

            // Track large files
            if file.loc >= params.loc_threshold {
                large_files.push(serde_json::json!({
                    "path": file.path,
                    "loc": file.loc,
                    "language": file.language
                }));
            }
        }

        // Sort directories by LOC
        let mut sorted_dirs: Vec<_> = dir_loc.into_iter().collect();
        sorted_dirs.sort_by_key(|b| std::cmp::Reverse(b.1));

        // Sort large files
        large_files.sort_by(|a, b| {
            b.get("loc")
                .and_then(|v| v.as_u64())
                .unwrap_or(0)
                .cmp(&a.get("loc").and_then(|v| v.as_u64()).unwrap_or(0))
        });

        let result = serde_json::json!({
            "project": project.display().to_string(),
            "total_files": snapshot.files.len(),
            "total_loc": snapshot.files.iter().map(|f| f.loc).sum::<usize>(),
            "depth": params.depth,
            "top_directories": sorted_dirs.iter().take(15).map(|(dir, loc)| serde_json::json!({
                "path": dir,
                "loc": loc
            })).collect::<Vec<_>>(),
            "large_files": large_files.iter().take(10).collect::<Vec<_>>(),
            "loc_threshold": params.loc_threshold
        });

        tool_json_response("tree", Some(&project), result)
    }

    /// Focus on a specific directory
    #[tool(
        name = "focus",
        description = "Focus on a specific directory: list files, their LOC, exports, and dependencies within that directory. Great for understanding a module or subsystem."
    )]
    async fn focus(&self, Parameters(params): Parameters<FocusParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        let config = FocusConfig {
            include_consumers: true,
            max_depth: FocusConfig::default().max_depth,
        };
        let focus = match HolographicFocus::from_path(&snapshot, &params.directory, &config) {
            Some(focus) => focus,
            None => {
                let suggestions = suggest_directories(&snapshot, &params.directory, 3);
                // A correct path can still yield no files if .loctignore parks it
                // outside the snapshot (loctree-fail.md: vista docs/). Surface that
                // precise cause instead of the blanket "Check the path."
                let ignore_hint =
                    loctree::fs_utils::loctignore_exclusion_hint(&project, &params.directory);
                let error = match &ignore_hint {
                    Some(hint) => hint.clone(),
                    None => "No files found in this directory. Check the path.".to_string(),
                };
                return tool_json_response(
                    "focus",
                    Some(&project),
                    serde_json::json!({
                        "directory": params.directory,
                        "project": project.display().to_string(),
                        "error": error,
                        "loctignore_excluded": ignore_hint.is_some(),
                        "suggestions": suggestions
                    }),
                );
            }
        };
        let total_exports: usize = snapshot
            .files
            .iter()
            .filter(|file| focus.core.iter().any(|core| core.path == file.path))
            .map(|file| file.exports.len())
            .sum();

        let result = serde_json::json!({
            "directory": focus.target,
            "project": project.display().to_string(),
            "summary": {
                "files": focus.core.len(),
                "total_loc": focus.stats.core_loc,
                "total_exports": total_exports,
                "internal_edges": focus.stats.internal_edges,
                "external_dependency_edges": focus.deps.len(),
                "external_consumer_edges": focus.consumers.len(),
            },
            "files": focus.core.iter().map(|f| {
                let exports = snapshot
                    .files
                    .iter()
                    .find(|file| file.path == f.path)
                    .map(|file| file.exports.len())
                    .unwrap_or_default();
                serde_json::json!({
                "path": f.path,
                "loc": f.loc,
                "language": f.language,
                "exports": exports
                })
            }).collect::<Vec<_>>(),
            "external_dependencies": focus.deps.iter().take(20).map(|f| &f.path).collect::<Vec<_>>(),
            "external_consumers": focus.consumers.iter().take(20).map(|f| &f.path).collect::<Vec<_>>(),
            "module_consumers": focus.consumers.iter().take(20).map(|f| serde_json::json!({
                "path": f.path,
                "loc": f.loc,
                "language": f.language,
                "authority": "LoctreeDerived"
            })).collect::<Vec<_>>(),
            "core_symbols": focus.core_symbols,
            "authority_labels": focus.authority_labels,
            "suggested_next": focus.suggested_next
        });

        tool_json_response("focus", Some(&project), result)
    }

    /// Follow signals flagged by repo-view at field level
    #[tool(
        name = "follow",
        description = "Pursue structural signals at field level. Scopes: 'dead' — unused exports with nearest consumers. 'cycles' — circular imports with weakest link. 'twins' — duplicate exports plus route-level twins (CLI `loct twins` parity). 'hotspots' — high-importer files. 'trace' — trace a Tauri/IPC handler end-to-end (requires handler param). 'commands' — Tauri FE<->BE handler coverage. 'events' — event emit/listen flow analysis. 'pipelines' — pipeline summary (events + commands + risks). 'all' — dead + cycles + twins (incl. route_twins) + hotspots."
    )]
    async fn follow(&self, Parameters(params): Parameters<FollowParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return format!("Error: {}", e),
        };

        let snapshot = match self
            .get_snapshot(
                &project,
                SnapshotLoadOptions {
                    force_no_git: params.force_no_git,
                    ..Default::default()
                },
            )
            .await
        {
            Ok(s) => s,
            Err(e) => return format!("Error loading project: {}", e),
        };

        let scope = params.scope.to_lowercase();
        let limit = params.limit;
        let mut trails = serde_json::Map::new();

        // Dead exports trail
        if scope == "dead" || scope == "all" {
            let config = DeadFilterConfig::default();
            let dead = find_dead_exports(&snapshot.files, true, None, config);

            // Find nearest candidate consumers for each dead export
            let signals: Vec<_> = dead
                .iter()
                .take(limit)
                .map(|d| {
                    // Find files that import from the same directory (potential wiring candidates)
                    let dir = Path::new(&d.file)
                        .parent()
                        .map(|p| p.to_string_lossy().to_string())
                        .unwrap_or_default();
                    let candidates: Vec<_> = snapshot
                        .edges
                        .iter()
                        .filter(|e| e.to.starts_with(&dir) && e.from != d.file)
                        .map(|e| e.from.clone())
                        .collect::<std::collections::HashSet<_>>()
                        .into_iter()
                        .take(3)
                        .collect();

                    let loc = snapshot
                        .files
                        .iter()
                        .find(|f| f.path == d.file)
                        .map(|f| f.loc)
                        .unwrap_or(0);

                    serde_json::json!({
                        "file": d.file,
                        "symbol": d.symbol,
                        "confidence": d.confidence,
                        "reason": d.reason,
                        "loc": loc,
                        "nearest_candidates": candidates,
                        "action": "remove or wire into candidate consumers"
                    })
                })
                .collect();

            trails.insert(
                "dead_exports".to_string(),
                serde_json::json!({
                    "total": dead.len(),
                    "shown": signals.len(),
                    "signals": signals
                }),
            );
        }

        // Cycles trail
        if scope == "cycles" || scope == "all" {
            let edges: Vec<_> = snapshot
                .edges
                .iter()
                .map(|e| (e.from.clone(), e.to.clone(), e.label.clone()))
                .collect();
            let cycles = find_cycles(&edges);

            let signals: Vec<_> = cycles
                .iter()
                .take(limit)
                .map(|chain| {
                    // Calculate total LOC in cycle
                    let total_loc: usize = chain
                        .iter()
                        .filter_map(|f| snapshot.files.iter().find(|a| a.path == *f))
                        .map(|a| a.loc)
                        .sum();

                    // Find weakest link (edge with fewest symbols crossing).
                    // Defense-in-depth (marbles L6, hak CYC-PHANTOM 2026-05-18):
                    // only consider edges where symbols_crossed > 0. A pair
                    // with symbols_crossed == 0 is a graph phantom — the
                    // chain hop reaches the next node but no snapshot edge
                    // actually carries a symbol across that pair. The legacy
                    // selector treated that as the *strongest* signal (lowest
                    // count wins), producing reports like
                    // `weakest_link: {from: A, to: B, symbols_crossed: 0}`
                    // even though no such edge exists. Filter first.
                    let mut weakest: Option<(&String, &String, usize)> = None;
                    for i in 0..chain.len() {
                        let from = &chain[i];
                        let to = &chain[(i + 1) % chain.len()];
                        let symbols_crossed = snapshot
                            .edges
                            .iter()
                            .filter(|e| e.from == *from && e.to == *to)
                            .count();
                        if symbols_crossed == 0 {
                            continue;
                        }
                        match weakest {
                            None => weakest = Some((from, to, symbols_crossed)),
                            Some((_, _, current)) if symbols_crossed < current => {
                                weakest = Some((from, to, symbols_crossed));
                            }
                            _ => {}
                        }
                    }

                    let (weakest_link, action) = match weakest {
                        Some((from, to, sym)) => (
                            serde_json::json!({
                                "from": from,
                                "to": to,
                                "symbols_crossed": sym
                            }),
                            "break at weakest link",
                        ),
                        None => (
                            serde_json::json!(null),
                            "graph anomaly: all chain edges have symbols_crossed == 0; verify analyzer edges",
                        ),
                    };

                    serde_json::json!({
                        "chain": chain,
                        "length": chain.len(),
                        "total_loc": total_loc,
                        "weakest_link": weakest_link,
                        "action": action
                    })
                })
                .collect();

            trails.insert(
                "cycles".to_string(),
                serde_json::json!({
                    "total": cycles.len(),
                    "shown": signals.len(),
                    "signals": signals
                }),
            );
        }

        // Twins trail
        if scope == "twins" || scope == "all" {
            let twins = detect_exact_twins(&snapshot.files, false);

            let signals: Vec<_> = twins
                .iter()
                .take(limit)
                .map(|twin| {
                    let files: Vec<_> = twin.locations.iter().map(|l| &l.file_path).collect();
                    serde_json::json!({
                        "symbol": twin.name,
                        "files": files,
                        "locations": twin.locations.iter().map(|l| serde_json::json!({
                            "file": l.file_path,
                            "line": l.line,
                            "kind": l.kind,
                            "importers": l.import_count
                        })).collect::<Vec<_>>(),
                        "signature_similarity": twin.signature_similarity,
                        "classification": twin.classification,
                        "action": twin_action(twin)
                    })
                })
                .collect();

            // loctree-fail hak 2026-05-18 #6 + 2026-05-23 #13 (L9 closure):
            // CLI `loct twins` returns both exact_twins AND route_twins
            // (since marbles-L8). MCP `follow(scope='twins')` was only
            // returning exact_twins, leaving agents blind to runtime
            // route-level collisions (e.g. duplicate `POST /api/stt`)
            // that the operator sees from the CLI. Restore parity.
            let route_twins = detect_route_twins(&snapshot.files);
            let route_signals: Vec<_> = route_twins
                .iter()
                .take(limit)
                .map(|rt| {
                    serde_json::json!({
                        "framework": rt.framework,
                        "method": rt.method,
                        "path": rt.path,
                        "severity": rt.severity,
                        "registrations": rt.locations.iter().map(|loc| serde_json::json!({
                            "file": loc.file,
                            "line": loc.line,
                            "handler": loc.handler,
                        })).collect::<Vec<_>>(),
                    })
                })
                .collect();

            trails.insert(
                "twins".to_string(),
                serde_json::json!({
                    "total": twins.len(),
                    "shown": signals.len(),
                    "signals": signals,
                    "route_twins": {
                        "total": route_twins.len(),
                        "shown": route_signals.len(),
                        "signals": route_signals,
                    }
                }),
            );
        }

        // Hotspots trail (files with most direct importer files)
        if scope == "hotspots" || scope == "all" {
            let hubs = top_hubs_by_importers_direct(&snapshot, limit);

            let signals: Vec<_> = hubs
                .iter()
                .map(|metric| {
                    let importers = metric.importers_direct;

                    let risk = if importers > 30 {
                        "high — changes here ripple everywhere"
                    } else if importers > 10 {
                        "medium — significant blast radius"
                    } else {
                        "low"
                    };

                    serde_json::json!({
                        "file": metric.file,
                        "importers": importers,
                        "importers_direct": metric.importers_direct,
                        "import_edges": metric.import_edges,
                        "loc": metric.loc,
                        "risk": risk,
                        "action": if importers > 20 { "split or freeze interface" } else { "monitor" }
                    })
                })
                .collect();

            trails.insert(
                "hotspots".to_string(),
                serde_json::json!({
                    "total": hubs.len(),
                    "shown": signals.len(),
                    "signals": signals
                }),
            );
        }

        // Trace trail - trace a specific Tauri handler end-to-end
        if scope == "trace" {
            let handler_name = match params.handler.as_deref() {
                Some(name) => name,
                None => {
                    return tool_json_response(
                        "follow",
                        Some(&project),
                        serde_json::json!({
                            "error": "trace scope requires 'handler' parameter",
                            "example": "follow(scope='trace', handler='toggle_assistant')",
                            "hint": "Use commands scope first to see available handlers"
                        }),
                    );
                }
            };

            let handler_lower = handler_name.to_lowercase();
            let matching: Vec<_> = snapshot
                .command_bridges
                .iter()
                .filter(|b| b.name.to_lowercase().contains(&handler_lower))
                .take(limit)
                .map(|b| {
                    serde_json::json!({
                        "name": b.name,
                        "has_handler": b.has_handler,
                        "is_called": b.is_called,
                        "backend": b.backend_handler.as_ref().map(|(f, l)| serde_json::json!({
                            "file": f,
                            "line": l
                        })),
                        "frontend_calls": b.frontend_calls.iter().map(|(f, l)| serde_json::json!({
                            "file": f,
                            "line": l
                        })).collect::<Vec<_>>(),
                        "status": if b.has_handler && b.is_called {
                            "healthy"
                        } else if !b.has_handler && b.is_called {
                            "missing_handler"
                        } else if b.has_handler && !b.is_called {
                            "unused_handler"
                        } else {
                            "orphan"
                        }
                    })
                })
                .collect();

            trails.insert(
                "trace".to_string(),
                serde_json::json!({
                    "handler": handler_name,
                    "total": matching.len(),
                    "signals": matching
                }),
            );
        }

        // Commands trail - Tauri FE<->BE handler coverage
        if scope == "commands" {
            let total = snapshot.command_bridges.len();
            let missing: Vec<_> = snapshot
                .command_bridges
                .iter()
                .filter(|b| !b.has_handler && b.is_called)
                .map(|b| {
                    serde_json::json!({
                        "name": b.name,
                        "frontend_calls": b.frontend_calls.iter().map(|(f, l)| serde_json::json!({
                            "file": f,
                            "line": l
                        })).collect::<Vec<_>>()
                    })
                })
                .collect();
            let unused: Vec<_> = snapshot
                .command_bridges
                .iter()
                .filter(|b| b.has_handler && !b.is_called)
                .map(|b| {
                    serde_json::json!({
                        "name": b.name,
                        "backend": b.backend_handler.as_ref().map(|(f, l)| serde_json::json!({
                            "file": f,
                            "line": l
                        }))
                    })
                })
                .collect();
            let matched = total.saturating_sub(missing.len() + unused.len());

            trails.insert(
                "commands".to_string(),
                serde_json::json!({
                    "total": total,
                    "matched": matched,
                    "missing_handlers": {
                        "count": missing.len(),
                        "signals": missing
                    },
                    "unused_handlers": {
                        "count": unused.len(),
                        "signals": unused
                    }
                }),
            );
        }

        // Events trail - event emit/listen flow
        if scope == "events" {
            let ghosts: Vec<_> = snapshot
                .event_bridges
                .iter()
                .filter(|e| e.listens.is_empty() || e.emits.is_empty())
                .take(limit)
                .map(|e| {
                    let status = if e.emits.is_empty() {
                        "listen_only"
                    } else if e.listens.is_empty() {
                        "emit_only"
                    } else {
                        "healthy"
                    };

                    serde_json::json!({
                        "name": e.name,
                        "status": status,
                        "emits": e.emits.iter().map(|(f, l, k)| serde_json::json!({
                            "file": f,
                            "line": l,
                            "kind": k
                        })).collect::<Vec<_>>(),
                        "listens": e.listens.iter().map(|(f, l)| serde_json::json!({
                            "file": f,
                            "line": l
                        })).collect::<Vec<_>>(),
                        "is_fe_sync": e.is_fe_sync,
                        "same_file_sync": e.same_file_sync
                    })
                })
                .collect();

            let total_events = snapshot.event_bridges.len();
            let ghost_count = snapshot
                .event_bridges
                .iter()
                .filter(|e| e.listens.is_empty() || e.emits.is_empty())
                .count();

            trails.insert(
                "events".to_string(),
                serde_json::json!({
                    "total": total_events,
                    "ghost_events": ghost_count,
                    "signals": ghosts
                }),
            );
        }

        // Pipelines trail - event/command/payload risks summary
        if scope == "pipelines" {
            let scan_results = scan_results_from_snapshot(&snapshot);
            let summary = build_pipeline_summary(
                &scan_results.global_analyses,
                &None,
                &None,
                &scan_results.global_fe_commands,
                &scan_results.global_be_commands,
                &scan_results.global_fe_payloads,
                &scan_results.global_be_payloads,
            );
            trails.insert("pipelines".to_string(), summary);
        }

        let result = serde_json::json!({
            "project": project.display().to_string(),
            "scope": params.scope,
            "trails": trails
        });

        tool_json_response("follow", Some(&project), result)
    }

    #[tool(
        name = "suppressions",
        description = "Source-side silencer inventory. LITERAL-ONLY detection (free-tier scope): surfaces every Rust #[allow(...)], Rust #[ignore], Rust unsafe { ... } (with Rust 2024 env-var boilerplate triaged as 'unsafe-env-var'), Semgrep nosemgrep comments, TypeScript @ts-ignore, @ts-expect-error, @ts-nocheck, ESLint eslint-disable, Python # noqa, Python # type: ignore, Python # pylint: disable, Python # mypy:, Shell # shellcheck disable. Returns structured JSON: { matches: [{ kind, file, line, snippet, rule_id }], counts: { kind: count }, files_per_kind: { kind: file_count }, total, total_files }. Filter with kinds=[...]. NO semantic enrichment — semantic classification (suspicious/stale/similar-to-fixed) is paid-tier Wave 7+ delta and explicitly out of scope here. Distinct from .loctree/suppressions.toml (that's loctree's OWN finding-suppression file; different concept, similar name)."
    )]
    async fn suppressions(&self, Parameters(params): Parameters<SuppressionsParams>) -> String {
        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return json_error(e),
        };

        // Parse filter tokens. Unknown tokens fail fast with the same shape
        // as the CLI handler so MCP callers learn the vocabulary the same way.
        let mut filter: HashSet<SilencerKind> = HashSet::new();
        for raw in &params.kinds {
            for token in raw.split(',') {
                let token = token.trim();
                if token.is_empty() {
                    continue;
                }
                match SilencerKind::from_filter(token) {
                    Some(k) => {
                        filter.insert(k);
                    }
                    None => {
                        return json_error(format!(
                            "unknown kind '{}'. Valid: allow, dead-code, nosemgrep, ts-ignore, ts-expect-error, ts-nocheck, eslint-disable, noqa, type-ignore, pylint-disable, mypy-ignore, shellcheck, unsafe, unsafe-env-var, ignore",
                            token
                        ));
                    }
                }
            }
        }

        // .semgrepignore filtering ON by default — same hygiene as CLI.
        let extra_globs = resolve_ignore_globs(&project, !params.include_fixtures);
        let inv = silencer_inventory(&project, &filter, &extra_globs);

        tool_json_response(
            "suppressions",
            Some(&project),
            serde_json::json!({
                "tier": "free",
                "detection": "literal-only",
                "project": project.display().to_string(),
                "filter": params.kinds,
                "include_fixtures": params.include_fixtures,
                "total": inv.total,
                "total_files": inv.total_files,
                "counts": inv.counts,
                "files_per_kind": inv.files_per_kind,
                "matches": inv.matches,
            }),
        )
    }

    #[tool(
        name = "prism",
        description = "Score conceptual smear across two or more task framings. Composes one ContextPack per task, computes file overlap and Jaccard distance, and emits the canonical loctree.prism.v1 JSON schema (axes, band, recommendation, task summaries, overlap). Use when a feature feels like it lives in multiple places at once and you need to decide whether vc-polarize is warranted."
    )]
    async fn prism(&self, Parameters(params): Parameters<PrismParams>) -> String {
        if params.task.len() < 2 {
            return json_error(
                "prism requires at least two task framings; pass task=[\"a\", \"b\"]",
            );
        }

        let project = match Self::resolve_project(&params.project, params.force_no_git) {
            Ok(p) => p,
            Err(e) => return json_error(e),
        };

        let opts = loctree::cli::command::PrismOptions {
            tasks: params.task.clone(),
            project: Some(project.clone()),
            aicx_project_override: params.aicx_project.clone(),
            with_aicx: params.with_aicx && !params.no_aicx,
            no_aicx: params.no_aicx,
            json: true,
            limit: params.limit.max(1),
        };

        let report = match loctree::run_prism(&opts) {
            Ok(report) => report,
            Err(err) => return json_error(err),
        };

        serde_json::to_string(&report).unwrap_or_else(json_error)
    }
}

// ============================================================================
// Server Handler Implementation
// ============================================================================

/// Build-time identity stamp (populated by `build.rs`). Surfaced in the MCP
/// `initialize` handshake so an agent can detect that the running binary lags
/// its repo's source HEAD straight from `serverInfo.version` / `instructions`,
/// without reverse-engineering the tool schema. See `loctree-fail.md`
/// ("live binary predates the committed fix").
const BUILD_VERSION: &str = env!("LOCTREE_MCP_BUILD_VERSION");
/// Richer human-facing commit stamp: `git describe --always --dirty --tags`.
const GIT_DESCRIBE: &str = env!("LOCTREE_MCP_GIT_DESCRIBE");

/// The tool catalogue half of the `initialize` instructions. The build-identity
/// header is prepended at runtime in [`LoctreeServer::get_info`].
const INSTRUCTIONS_BODY: &str = "Loctree MCP provides one sharp agent surface: 10 tools, not a mirrored CLI.\n\n\
                 START:\n\
                 - context(project, format?) - Complete Agent Context Pack: structural + runtime semantics + risk + action + optional AICX memory + authority labels. Pretty JSON by default; use format='markdown' for operator-readable context.\n\n\
                 MAP TOOLS:\n\
                 - repo-view(project) - Overview: files, LOC, languages, health, top hubs.\n\
                 - focus(directory) - Understand a module. Files, internal edges, external deps.\n\
                 - slice(file) - Before modifying. File + dependencies + consumers in one call.\n\
                 - find(name) - Before creating. Symbol search with regex. Modes: symbols, who-imports, where-symbol, tagmap, crowd, literal (exact identifier-boundary truth scan, at parity with `loct occurrences`).\n\
                 - impact(file) - Before deleting. Direct + transitive consumers (blast radius).\n\
                 - tree(project) - Directory structure with LOC counts.\n\
                 - follow(scope) - Pursue signals: dead, cycles, twins, hotspots, trace, commands, events, pipelines.\n\n\
                 SILENCER SURFACE:\n\
                 - suppressions(project, kinds?) - Source-side silencer inventory: Rust #[allow(...)], Rust #[ignore], Rust unsafe { ... } (env-var boilerplate split out), Semgrep nosemgrep, TypeScript @ts-ignore, ESLint eslint-disable, Python # noqa, Python # type: ignore, Shell # shellcheck disable. Literal-only detection (free-tier). Semantic enrichment (suspicious/stale) is paid-tier Wave 7+.\n\n\
                 POLARIZATION GATE:\n\
                 - prism(task=[a, b, ...]) - Score conceptual smear across task framings. Emits loctree.prism.v1 JSON for vc-polarize gating.\n\n\
                 Reports such as health/findings/audit/coverage stay in the `loct` CLI, not the MCP tool list.\n\
                 All tools accept 'project' parameter (default: current dir).\n\
                 First use auto-scans if no snapshot exists.";

/// Build-identity header prepended to the `initialize` instructions. Kept as a
/// standalone helper so the regression tests can assert its exact shape.
fn build_identity_banner() -> String {
    format!(
        "BUILD: loctree-mcp {BUILD_VERSION} (git {GIT_DESCRIBE}). \
         If this commit lags your repo's source HEAD, the running binary is STALE — \
         rebuild and restart the MCP server before trusting tool-schema parity.\n\n"
    )
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for LoctreeServer {
    fn get_info(&self) -> ServerInfo {
        let mut capabilities = rmcp::model::ServerCapabilities::default();
        capabilities.tools = Some(rmcp::model::ToolsCapability {
            list_changed: Some(true),
        });

        ServerInfo::new(capabilities)
            .with_server_info(
                // `version` carries the git commit as semver build metadata
                // (`0.13.0+g<sha>`), so an agent reading `serverInfo.version`
                // can tell a stale binary from a fresh one.
                rmcp::model::Implementation::new("loctree", BUILD_VERSION)
                    .with_title("Loctree MCP Server")
                    .with_description("Structural code intelligence for AI agents")
                    .with_website_url("https://github.com/Loctree/Loctree"),
            )
            .with_instructions(format!("{}{INSTRUCTIONS_BODY}", build_identity_banner()))
    }
}

// ============================================================================
// Main Entry Point
// ============================================================================

async fn run_server() -> Result<()> {
    let args = Args::parse();

    // Pin the default project root before serving so the first tool call
    // already resolves empty `project` fields against it. No `--root` keeps
    // the universal per-request behavior untouched.
    if let Some(root) = args.root.as_deref() {
        set_default_project_root(root);
    }

    // Initialize logging - MUST write to stderr, stdout is for MCP JSON-RPC
    tracing_subscriber::fmt()
        .with_writer(std::io::stderr)
        // Prevent tracing from recursively writing fallback errors to stderr when stderr is closed.
        .log_internal_errors(false)
        .with_env_filter(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| args.log_level.parse().unwrap_or_default()),
        )
        .init();

    info!(
        "Starting loctree-mcp v{} (git {}) (universal)",
        BUILD_VERSION, GIT_DESCRIBE
    );
    if args.root.is_some() {
        info!("Default project root pinned to {}", default_project());
    }

    match args.transport {
        TransportKind::Stdio => serve_stdio().await,
        TransportKind::Http => http::serve_http(&args.bind).await,
    }
}

/// Stdio transport — the default, line-delimited JSON-RPC over stdin/stdout.
/// Behaves exactly as previous versions of loctree-mcp.
async fn serve_stdio() -> Result<()> {
    let server = LoctreeServer::new();
    info!("Server ready. Listening on stdio...");
    server
        .serve(rmcp::transport::stdio())
        .await?
        .waiting()
        .await?;
    Ok(())
}

#[tokio::main]
async fn main() -> ExitCode {
    // Ignore SIGPIPE - allows broken pipe to be handled as error instead of signal
    ignore_sigpipe();

    // Install panic hook for clean shutdown on broken pipe
    install_panic_hook();

    match run_server().await {
        Ok(()) => ExitCode::SUCCESS,
        Err(e) => {
            // Check if this is a broken pipe error (client disconnected)
            let err_str = format!("{:?}", e);
            if err_str.contains("Broken pipe") || err_str.contains("os error 32") {
                safe_stderr_log("[loctree-mcp] Client disconnected, shutting down");
                ExitCode::SUCCESS
            } else {
                safe_stderr_log(&format!("[loctree-mcp] Error: {:#}", e));
                ExitCode::FAILURE
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::path::Path;

    use serde_json::Value;
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn build_version_extends_crate_version_with_commit_metadata() {
        // Always starts with the plain crate version; in a git checkout it is
        // extended with `+g<sha>` build metadata. Robust when git is absent
        // (packaged build) — then it degrades to exactly the crate version.
        assert!(
            BUILD_VERSION.starts_with(env!("CARGO_PKG_VERSION")),
            "build version {BUILD_VERSION:?} must begin with crate version {:?}",
            env!("CARGO_PKG_VERSION")
        );
        let extended = BUILD_VERSION == env!("CARGO_PKG_VERSION")
            || BUILD_VERSION.contains("+g")
            || BUILD_VERSION.contains("+");
        assert!(
            extended,
            "unexpected build version shape: {BUILD_VERSION:?}"
        );
    }

    #[test]
    fn get_info_version_carries_the_build_stamp() {
        let info = LoctreeServer::new().get_info();
        assert_eq!(
            info.server_info.version, BUILD_VERSION,
            "serverInfo.version must expose the git-stamped build version so an \
             agent can spot a stale binary from the initialize handshake"
        );
        assert_eq!(info.server_info.name, "loctree");
    }

    #[test]
    fn get_info_instructions_lead_with_build_identity_banner() {
        let info = LoctreeServer::new().get_info();
        let instructions = info
            .instructions
            .expect("initialize instructions must be present");
        assert!(
            instructions.starts_with("BUILD: loctree-mcp "),
            "instructions must open with the build-identity banner, got: {:?}",
            &instructions[..instructions.len().min(60)]
        );
        assert!(
            instructions.contains(BUILD_VERSION) && instructions.contains(GIT_DESCRIBE),
            "banner must name both the build version and the git describe stamp"
        );
        assert!(
            instructions.contains("STALE"),
            "banner must warn that a lagging binary is stale"
        );
        // The original tool catalogue must survive the prepend.
        assert!(
            instructions.contains("MAP TOOLS:") && instructions.contains("prism(task="),
            "tool catalogue body must be preserved after the banner"
        );
    }

    /// Single env-sensitive test for context_deadline() — consolidated to
    /// avoid the parallel race that would happen if these three branches
    /// ran as independent #[test]s mutating the same process-global env var.
    #[test]
    fn context_deadline_env_matrix() {
        // SAFETY: this is the only test that touches CONTEXT_DEADLINE_ENV;
        // all scenarios run sequentially inside a single test function so
        // there is no race with another #[test] reading the variable.
        unsafe { std::env::remove_var(CONTEXT_DEADLINE_ENV) };
        assert_eq!(
            context_deadline(),
            std::time::Duration::from_secs(90),
            "default applies when env var is unset"
        );

        unsafe { std::env::set_var(CONTEXT_DEADLINE_ENV, "30") };
        assert_eq!(
            context_deadline(),
            std::time::Duration::from_secs(30),
            "valid override is honored"
        );

        unsafe { std::env::set_var(CONTEXT_DEADLINE_ENV, "0") };
        assert_eq!(
            context_deadline(),
            std::time::Duration::from_secs(90),
            "zero falls back to default"
        );

        unsafe { std::env::set_var(CONTEXT_DEADLINE_ENV, "not-a-number") };
        assert_eq!(
            context_deadline(),
            std::time::Duration::from_secs(90),
            "garbage falls back to default"
        );

        unsafe { std::env::remove_var(CONTEXT_DEADLINE_ENV) };
    }

    #[test]
    fn deadline_exceeded_response_is_well_formed_json() {
        let body = deadline_exceeded_response(std::time::Duration::from_secs(45));
        let value: Value = serde_json::from_str(&body).expect("valid JSON");
        assert_eq!(value["status"], "error");
        assert_eq!(value["error"], "deadline_exceeded");
        assert_eq!(value["deadline_secs"], 45);
        assert_eq!(value["protocol"], "loctree.context_atlas.v1");
        assert!(
            value["hint"]
                .as_str()
                .expect("hint is string")
                .contains(CONTEXT_DEADLINE_ENV),
            "hint should reference the env var name"
        );
        assert!(
            value["session"]
                .as_str()
                .expect("session is string")
                .starts_with("ctx_"),
            "session id should follow ctx_ prefix"
        );
    }

    fn fixture_project() -> TempDir {
        let temp = tempfile::tempdir().expect("create temp project");
        fs::create_dir_all(temp.path().join("src")).expect("create src dir");
        fs::write(
            temp.path().join("Cargo.toml"),
            r#"[package]
name = "context-fixture"
version = "0.1.0"
edition = "2024"
"#,
        )
        .expect("write Cargo.toml");
        fs::write(
            temp.path().join("src/lib.rs"),
            r#"pub mod foo;

pub fn public_entry() {
    foo::helper();
}"#,
        )
        .expect("write lib.rs");
        fs::write(
            temp.path().join("src/foo.rs"),
            r#"pub fn helper() -> &'static str {
    "ok"
}"#,
        )
        .expect("write foo.rs");
        temp
    }

    fn params_for(project: &Path) -> ContextParams {
        ContextParams {
            project: project.display().to_string(),
            force_no_git: true,
            no_scan: false,
            fail_stale: false,
            fresh: false,
            file: None,
            task: None,
            scope: Vec::new(),
            changed: false,
            with_aicx: true,
            no_aicx: true,
            format: ContextFormat::Json,
            section: None,
        }
    }

    async fn context_output(project: &Path, mutate: impl FnOnce(&mut ContextParams)) -> String {
        let server = LoctreeServer::new();
        let mut params = params_for(project);
        mutate(&mut params);
        server.context(Parameters(params)).await
    }

    #[tokio::test]
    async fn context_tool_returns_valid_json() {
        let project = fixture_project();
        let output = context_output(project.path(), |_| {}).await;

        serde_json::from_str::<serde_json::Value>(&output).expect("context output should parse");
    }

    #[test]
    fn context_receipt_uses_snapshot_git_metadata_not_caller_root() {
        let scanned = fixture_project();
        let caller = fixture_project();
        let mut snapshot = Snapshot::new(vec![scanned.path().display().to_string()]);
        snapshot.metadata.git_repo = Some("scanned-repo".to_string());
        snapshot.metadata.git_owner_repo = Some("Org/scanned-repo".to_string());
        snapshot.metadata.git_branch = Some("feature/scanned".to_string());
        snapshot.metadata.git_commit = Some("abc1234".to_string());
        snapshot.metadata.git_scan_id = Some("feature/scanned@abc1234".to_string());

        let receipt =
            LoctreeServer::context_receipt_payload("ctx-test", caller.path(), &snapshot, true);

        assert_eq!(
            receipt["snapshot"]["git"]["repo"].as_str(),
            Some("scanned-repo")
        );
        assert_eq!(
            receipt["snapshot"]["git"]["owner_repo"].as_str(),
            Some("Org/scanned-repo")
        );
        assert_eq!(
            receipt["snapshot"]["git"]["scan_id"].as_str(),
            Some("feature/scanned@abc1234")
        );
        assert_eq!(
            receipt["snapshot"]["roots"][0].as_str(),
            Some(scanned.path().to_str().expect("utf8 temp path"))
        );
    }

    #[tokio::test]
    async fn slice_refreshes_when_existing_file_is_missing_from_cached_snapshot() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        fs::write(
            project.path().join("CONTRIBUTING.md"),
            "# Contributor Guide\n",
        )
        .expect("write markdown after initial snapshot");

        let output = server
            .slice(Parameters(SliceParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                file: "CONTRIBUTING.md".to_string(),
                consumers: false,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("slice output should be valid JSON after retry");
        assert_eq!(value["target"], "CONTRIBUTING.md");
        assert!(
            value["files"]
                .as_array()
                .expect("files array")
                .iter()
                .any(|file| file["path"] == "CONTRIBUTING.md"),
            "existing file missing from cached snapshot should trigger a fresh scan and retry: {output}"
        );
    }

    #[tokio::test]
    async fn slice_returns_core_for_explicit_file_excluded_by_loctignore() {
        let project = fixture_project();
        let server = LoctreeServer::new();
        fs::create_dir_all(project.path().join("fixtures")).expect("create fixtures dir");
        fs::write(project.path().join(".loctignore"), "fixtures/\n").expect("write loctignore");
        fs::write(
            project.path().join("fixtures/local.rs"),
            "pub fn fixture_only() {}\n",
        )
        .expect("write ignored fixture");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .slice(Parameters(SliceParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                file: "fixtures/local.rs".to_string(),
                consumers: false,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("ignored explicit fixture should still JSON");
        assert_eq!(value["target"], "fixtures/local.rs");
        assert_eq!(value["files"][0]["path"], "fixtures/local.rs");
        assert_eq!(value["files"][0]["source"], "disk_explicit_fallback");
        assert!(
            value["snapshot_exclusion"]
                .as_str()
                .unwrap_or_default()
                .contains("detected exclusion: ignored by .loctignore:1 pattern `fixtures/`"),
            "fallback should explain why the slice is core-only: {output}"
        );
    }

    #[tokio::test]
    async fn impact_returns_named_fallback_for_explicit_file_excluded_by_loctignore() {
        let project = fixture_project();
        let server = LoctreeServer::new();
        fs::create_dir_all(project.path().join("fixtures")).expect("create fixtures dir");
        fs::write(project.path().join(".loctignore"), "fixtures/\n").expect("write loctignore");
        fs::write(
            project.path().join("fixtures/local.rs"),
            "pub fn fixture_only() {}\n",
        )
        .expect("write ignored fixture");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .impact(Parameters(ImpactParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                file: "fixtures/local.rs".to_string(),
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("ignored explicit impact should still JSON");
        assert_eq!(value["file"], "fixtures/local.rs");
        assert_eq!(value["risk_level"], "unknown");
        assert_eq!(value["safe_to_delete"], false);
        assert_eq!(value["direct_consumers"]["count"], 0);
        assert_eq!(value["transitive_consumers"]["count"], 0);
        assert_eq!(
            value["fallback_read"]["files"][0]["path"],
            "fixtures/local.rs"
        );
        assert_eq!(
            value["fallback_read"]["files"][0]["source"],
            "disk_explicit_fallback"
        );
        assert!(
            value["snapshot_exclusion"]
                .as_str()
                .unwrap_or_default()
                .contains("detected exclusion: ignored by .loctignore:1 pattern `fixtures/`"),
            "fallback should explain why impact is core-only: {output}"
        );
    }

    #[tokio::test]
    async fn slice_prefers_exact_repo_relative_file_over_fixture_suffix() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        fs::write(project.path().join("Makefile"), "root:\n\t@echo root\n")
            .expect("write root Makefile");
        fs::create_dir_all(project.path().join("scripts")).expect("create root scripts dir");
        fs::write(
            project.path().join("scripts/version-bump.sh"),
            "#!/usr/bin/env bash\necho root\n",
        )
        .expect("write root version script");

        fs::create_dir_all(project.path().join("loctree-rs/tests/fixtures/make_rich"))
            .expect("create nested make fixture dir");
        fs::write(
            project
                .path()
                .join("loctree-rs/tests/fixtures/make_rich/Makefile"),
            "fixture:\n\t@echo fixture\n",
        )
        .expect("write fixture Makefile");
        fs::create_dir_all(
            project
                .path()
                .join("loctree-rs/tests/fixtures/shell_rich/scripts"),
        )
        .expect("create nested shell fixture dir");
        fs::write(
            project
                .path()
                .join("loctree-rs/tests/fixtures/shell_rich/scripts/version-bump.sh"),
            "#!/usr/bin/env bash\necho fixture\n",
        )
        .expect("write fixture version script");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let make_output = server
            .slice(Parameters(SliceParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                file: "Makefile".to_string(),
                consumers: false,
            }))
            .await;
        let make_value: serde_json::Value =
            serde_json::from_str(&make_output).expect("Makefile slice output should be JSON");
        assert_eq!(make_value["files"][0]["path"], "Makefile");

        let script_output = server
            .slice(Parameters(SliceParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                file: "scripts/version-bump.sh".to_string(),
                consumers: false,
            }))
            .await;
        let script_value: serde_json::Value =
            serde_json::from_str(&script_output).expect("script slice output should be JSON");
        assert_eq!(script_value["files"][0]["path"], "scripts/version-bump.sh");
    }

    #[tokio::test]
    async fn slice_exposes_core_symbols_authority_and_suggested_next() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .slice(Parameters(SliceParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                file: "src/lib.rs".to_string(),
                consumers: true,
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("slice output JSON");

        assert!(
            value["core_symbols"]
                .as_array()
                .expect("core_symbols array")
                .iter()
                .any(|symbol| {
                    symbol["name"] == "public_entry"
                        && symbol["file"] == "src/lib.rs"
                        && symbol["line"] == 3
                        && symbol["authority"] == "LoctreeDerived"
                }),
            "MCP slice should expose core symbols with file:line authority: {output}"
        );
        assert!(
            value["authority_labels"]
                .as_array()
                .expect("authority_labels array")
                .iter()
                .any(|label| label == "LoctreeDerived"),
            "MCP slice should expose authority labels: {output}"
        );
        assert!(
            value["suggested_next"]
                .as_array()
                .expect("suggested_next")
                .iter()
                .any(|step| step["command"] == "loct occurrences 'public_entry' --json"),
            "MCP slice should suggest concrete next commands: {output}"
        );
    }

    #[tokio::test]
    async fn focus_exposes_core_symbols_consumers_and_suggested_next() {
        let project = fixture_project();
        let server = LoctreeServer::new();
        fs::create_dir_all(project.path().join("src/feature")).expect("create feature dir");
        fs::write(
            project.path().join("src/feature/index.ts"),
            "export function feature_entry() { return 42; }\n",
        )
        .expect("write feature index");
        fs::write(
            project.path().join("src/app.ts"),
            "import { feature_entry } from './feature';\nfeature_entry();\n",
        )
        .expect("write app consumer");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .focus(Parameters(FocusParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                directory: "src/feature".to_string(),
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("focus output JSON");

        assert!(
            value["core_symbols"]
                .as_array()
                .expect("core_symbols")
                .iter()
                .any(|symbol| {
                    symbol["name"] == "feature_entry"
                        && symbol["file"] == "src/feature/index.ts"
                        && symbol["line"] == 1
                }),
            "MCP focus should expose core symbols in the focused directory: {output}"
        );
        assert!(
            value["module_consumers"]
                .as_array()
                .expect("module_consumers")
                .iter()
                .any(|consumer| consumer["path"] == "src/app.ts"),
            "MCP focus should expose pathful module consumer entries: {output}"
        );
        assert!(
            value["suggested_next"]
                .as_array()
                .expect("suggested_next")
                .iter()
                .any(|step| step["command"] == "loct occurrences 'feature_entry' --json"),
            "MCP focus should suggest concrete next commands: {output}"
        );
    }

    #[tokio::test]
    async fn follow_cycles_returns_deduped_pathful_chains() {
        let project = tempfile::tempdir().expect("create cycle project");
        fs::create_dir_all(project.path().join("src")).expect("create src");
        fs::write(
            project.path().join("src/a.ts"),
            "import { b } from './b';\nexport const a = b;\n",
        )
        .expect("write a.ts");
        fs::write(
            project.path().join("src/b.ts"),
            "import { a } from './a';\nexport const b = a;\n",
        )
        .expect("write b.ts");

        let server = LoctreeServer::new();
        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .follow(Parameters(FollowParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                scope: "cycles".to_string(),
                handler: None,
                limit: 10,
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("follow output JSON");
        let signals = value["trails"]["cycles"]["signals"]
            .as_array()
            .expect("cycle signals");
        let mut seen = std::collections::HashSet::new();
        for signal in signals {
            let chain = signal["chain"].as_array().expect("cycle chain");
            assert!(
                chain
                    .iter()
                    .all(|node| node.as_str().is_some_and(|path| path.starts_with("src/"))),
                "cycle chains should use repo-relative paths, not bare names: {output}"
            );
            let key = chain
                .iter()
                .filter_map(|node| node.as_str())
                .collect::<Vec<_>>()
                .join(" -> ");
            assert!(
                seen.insert(key.clone()),
                "duplicate cycle chain {key}: {output}"
            );
        }
    }

    #[tokio::test]
    async fn tagmap_recalls_symbols_with_dash_underscore_normalization() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .find(Parameters(FindParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                name: "public-entry".to_string(),
                mode: "tagmap".to_string(),
                limit: 20,
                lang: None,
                exported_only: false,
                dead_only: false,
                min_score: None,
                similar: None,
                file: None,
                whole_token: false,
                group_by_file: false,
                count_only: false,
                offset: 0,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("tagmap output should be valid JSON");
        assert!(
            value["facts"]["matches"]
                .as_array()
                .expect("facts matches array")
                .iter()
                .any(|item| {
                    item["kind"] == "export"
                        && item["file"] == "src/lib.rs"
                        && item["name"] == "public_entry"
                }),
            "tagmap should recall exported symbols, including dash/underscore query variants: {output}"
        );
    }

    #[tokio::test]
    async fn tagmap_recalls_exact_indexed_local_symbol_terms() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        fs::write(
            project.path().join("src/receipt.rs"),
            r#"pub fn context_receipt_payload() -> &'static str {
    "receipt"
}"#,
        )
        .expect("write receipt module");
        fs::write(
            project.path().join("src/lib.rs"),
            r#"pub mod foo;
pub mod receipt;

pub fn public_entry() {
    foo::helper();
}"#,
        )
        .expect("rewrite lib.rs");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .find(Parameters(FindParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                name: "context_receipt_payload".to_string(),
                mode: "tagmap".to_string(),
                limit: 20,
                lang: None,
                exported_only: false,
                dead_only: false,
                min_score: None,
                similar: None,
                file: None,
                whole_token: false,
                group_by_file: false,
                count_only: false,
                offset: 0,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("tagmap output should be valid JSON");
        assert!(
            value["facts"]["matches"]
                .as_array()
                .expect("facts matches array")
                .iter()
                .any(|item| {
                    item["kind"] == "export"
                        && item["file"] == "src/receipt.rs"
                        && item["name"] == "context_receipt_payload"
                }),
            "tagmap should recall exact indexed source terms surfaced by snapshot facts: {output}"
        );
    }

    #[tokio::test]
    async fn where_symbol_can_narrow_to_file_and_prefer_signature_context() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        fs::write(
            project.path().join("src/handler.rs"),
            r#"pub async fn find() -> &'static str {
    "handler"
}

pub fn find_helper() -> &'static str {
    "helper"
}"#,
        )
        .expect("write handler");
        fs::write(
            project.path().join("src/other.rs"),
            r#"pub async fn find() -> &'static str {
    "other"
}"#,
        )
        .expect("write other");
        fs::write(
            project.path().join("src/lib.rs"),
            r#"pub mod handler;
pub mod other;

pub fn public_entry() {
    let _ = handler::find_helper();
}"#,
        )
        .expect("rewrite lib.rs");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .find(Parameters(FindParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                name: "async fn find".to_string(),
                mode: "where-symbol".to_string(),
                limit: 20,
                lang: None,
                exported_only: false,
                dead_only: false,
                min_score: None,
                similar: None,
                file: Some("src/handler.rs".to_string()),
                whole_token: false,
                group_by_file: false,
                count_only: false,
                offset: 0,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("where-symbol output should be valid JSON");
        let results = value["results"].as_array().expect("results array");
        assert!(
            !results.is_empty(),
            "file-scoped signature query should return at least one result: {output}"
        );
        assert!(
            results.iter().all(|item| item["file"] == "src/handler.rs"),
            "file filter should remove same-name symbols in other files: {output}"
        );
        assert!(
            results[0]["context"]
                .as_str()
                .unwrap_or_default()
                .to_ascii_lowercase()
                .contains("function find"),
            "signature-shaped query should prefer the exact symbol anchor over substring matches: {output}"
        );
    }

    #[tokio::test]
    async fn find_param_parity_literal_mode_returns_occurrence_role_truth_at_cli_parity() {
        // The CodeScribe `utterance_id` failure class: a local binding plus an
        // increment plus a struct-field emission buried inside a function body.
        // `find` (AST/tagmap) misses the locals; the literal mode must see them.
        let project = fixture_project();
        let server = LoctreeServer::new();

        let source = r#"pub fn process() {
    let mut utterance_id = 0;
    utterance_id += 1;
    let _evt = Event { utterance_id };
    let _ = utterance_id;
}
"#;
        fs::write(project.path().join("src/scribe.rs"), source).expect("write scribe.rs");
        fs::write(
            project.path().join("src/lib.rs"),
            "pub mod foo;\npub mod scribe;\n",
        )
        .expect("rewrite lib.rs");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .find(Parameters(FindParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                name: "utterance_id".to_string(),
                mode: "literal".to_string(),
                limit: 50,
                lang: None,
                exported_only: false,
                dead_only: false,
                min_score: None,
                similar: None,
                file: None,
                whole_token: false,
                group_by_file: false,
                count_only: false,
                offset: 0,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("literal output should be valid JSON");
        assert_eq!(value["mode"], "literal", "mode echo: {output}");
        assert_eq!(value["literal_matches"]["source"], "literal");
        assert_eq!(value["literal_matches"]["query_kind"], "identifier");
        assert_eq!(
            value["literal_matches"]["match_mode"],
            "identifier_boundary"
        );
        assert!(
            value["literal_matches"]["coverage_line"]
                .as_str()
                .is_some_and(|line| line.contains("scanned")),
            "literal response should expose CLI coverage text: {output}"
        );
        assert!(
            value["literal_matches"]["scope"]["files_scanned"]
                .as_u64()
                .is_some_and(|count| count > 0),
            "literal response should expose scan scope stats: {output}"
        );

        let occ = value["literal_matches"]["occurrences"]
            .as_array()
            .expect("occurrences array");
        // 4 literal sites: binding, increment, field shorthand, plain read.
        assert_eq!(occ.len(), 4, "expected 4 literal occurrences: {output}");
        assert_eq!(value["total"], 4);
        assert!(
            occ.iter().all(|o| o["source"] == "literal"
                && o["matched_text"] == "utterance_id"
                && o["file"] == "src/scribe.rs"),
            "every occurrence is literal evidence in scribe.rs: {output}"
        );
        let kinds: Vec<&str> = occ
            .iter()
            .map(|o| o["occurrence_kind"].as_str().unwrap_or_default())
            .collect();
        assert_eq!(
            kinds,
            vec![
                "definition_like",
                "mutation_like",
                "field_emit_like",
                // `let _ = utterance_id;` is an honest `identifier` read now,
                // no longer a blanket `unknown`.
                "identifier"
            ],
            "single-line classification rides along on every occurrence: {output}"
        );
        let roles: Vec<&str> = occ
            .iter()
            .map(|o| o["match_role"].as_str().unwrap_or_default())
            .collect();
        assert_eq!(
            roles,
            vec!["local_binding", "mutation", "field_emission", "reference"],
            "MCP literal mode must expose the compact role contract: {output}"
        );
        let confidences: Vec<&str> = occ
            .iter()
            .map(|o| o["confidence"].as_str().unwrap_or_default())
            .collect();
        assert_eq!(
            confidences,
            vec!["high", "high", "high", "medium"],
            "MCP literal mode must expose role confidence: {output}"
        );
        assert!(
            occ.iter()
                .all(|o| o["scope_classification"] == "production"),
            "MCP literal mode must expose file-scope classification per occurrence: {output}"
        );
        let suggested_next = value["literal_matches"]["suggested_next"]
            .as_array()
            .expect("suggested_next array");
        assert!(
            suggested_next
                .iter()
                .any(|s| s["command"] == "loct body 'utterance_id' --json"),
            "MCP literal mode should carry CLI suggested-next body command: {output}"
        );
        assert!(
            suggested_next
                .iter()
                .any(|s| s["command"] == "loct slice 'src/scribe.rs'"),
            "MCP literal mode should carry CLI suggested-next slice command: {output}"
        );

        // Parity contract: the MCP surface must equal the shared scanner run over
        // the same bytes. This is what guarantees `find(mode=literal)` never
        // drifts from `loct occurrences` / `loct find --literal`.
        let mut expected = loctree::analyzer::occurrences::scan_files_with(
            [("src/scribe.rs", source)],
            "utterance_id",
            ScanOptions::default(),
        );
        expected.apply_report(ReportOptions {
            group_by_file: false,
            count_only: false,
            offset: 0,
            limit: Some(50),
        });
        let mut expected_json =
            serde_json::to_value(&expected).expect("serialize expected OccurrenceResults");
        // Align scope/coverage fields to the actual MCP run's project context to assert parity on occurrences.
        if let Some(obj) = expected_json.as_object_mut() {
            if let Some(real_obj) = value["literal_matches"].as_object() {
                if let Some(cov) = real_obj.get("coverage_line") {
                    obj.insert("coverage_line".to_string(), cov.clone());
                }
                if let Some(scope) = real_obj.get("scope") {
                    obj.insert("scope".to_string(), scope.clone());
                }
            }
        }
        assert_eq!(
            value["literal_matches"], expected_json,
            "MCP literal_matches must be byte-for-byte identical to the shared scanner output"
        );
    }

    #[tokio::test]
    async fn find_literal_mode_honors_file_scope_and_reports_range() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        fs::write(
            project.path().join("src/styles.css"),
            ".checkout-success { color: var(--checkout-success); }\n",
        )
        .expect("write styles");
        fs::write(
            project.path().join("src/other.css"),
            ".checkout-success { opacity: 1; }\n",
        )
        .expect("write other");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .find(Parameters(FindParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                name: "checkout-success".to_string(),
                mode: "literal".to_string(),
                limit: 50,
                lang: None,
                exported_only: false,
                dead_only: false,
                min_score: None,
                similar: None,
                file: Some("src/styles.css".to_string()),
                whole_token: false,
                group_by_file: false,
                count_only: false,
                offset: 0,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("literal output should be valid JSON");
        assert_eq!(value["file_filter"], "src/styles.css");
        let lit = &value["literal_matches"];
        assert_eq!(lit["files_matched"], 1);
        assert_eq!(lit["total"], 2);
        let occ = lit["occurrences"].as_array().expect("occurrences array");
        assert!(
            occ.iter().all(|o| o["file"] == "src/styles.css"),
            "file-scoped literal mode must not leak sibling files: {output}"
        );
        assert_eq!(occ[0]["line"], 1);
        assert_eq!(occ[0]["column"], 2);
        assert_eq!(occ[0]["range"]["start"]["line"], 1);
        assert_eq!(occ[0]["range"]["start"]["column"], 2);
        assert_eq!(occ[0]["range"]["end"]["column"], 18);
    }

    #[tokio::test]
    async fn follow_twins_exposes_classification_for_agent_action() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        fs::write(
            project.path().join("src/left.rs"),
            r#"pub fn shared_marker(input: MarkerConfig) -> MarkerOutput {
    unimplemented!("{input:?}")
}"#,
        )
        .expect("write left twin");
        fs::write(
            project.path().join("src/right.rs"),
            r#"pub fn shared_marker(input: MarkerConfig) -> MarkerOutput {
    unimplemented!("{input:?}")
}"#,
        )
        .expect("write right twin");
        fs::write(
            project.path().join("src/lib.rs"),
            r#"pub mod foo;
pub mod left;
pub mod right;

pub fn public_entry() {
    foo::helper();
}"#,
        )
        .expect("rewrite lib.rs");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .follow(Parameters(FollowParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                scope: "twins".to_string(),
                handler: None,
                limit: 10,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("follow output should be valid JSON");
        let signals = value["trails"]["twins"]["signals"]
            .as_array()
            .expect("twins signals array");
        let marker = signals
            .iter()
            .find(|signal| signal["symbol"] == "shared_marker")
            .unwrap_or_else(|| panic!("shared_marker twin should be present: {output}"));

        assert_eq!(marker["classification"], "duplicate");
        assert_eq!(marker["action"], "consolidate into single module");
    }

    /// Regression for loctree-fail hak 2026-05-23 #13 (L9 closure): MCP
    /// `follow(scope='twins')` must include route-level twins (FastAPI /
    /// Flask / Tauri duplicate `(method, path)` registrations) to match
    /// CLI `loct twins` since marbles-L8. Before this fix MCP returned
    /// only symbol-level twins while CLI returned both, so agents (MCP)
    /// and operators (CLI) saw different views of repo twin reality.
    #[tokio::test]
    async fn follow_twins_includes_route_twins() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        // Synthesize two Python files that both register POST /api/stt
        // with a FastAPI-shaped decorator. The detector only needs the
        // route surface to populate `FileAnalysis::routes`.
        fs::write(
            project.path().join("src/analyze_server.py"),
            r#"from fastapi import FastAPI
app = FastAPI()

@app.post("/api/stt")
def transcribe_voice():
    return {"ok": True}
"#,
        )
        .expect("write analyze_server.py");
        fs::write(
            project.path().join("src/review_server.py"),
            r#"from fastapi import FastAPI
app = FastAPI()

@app.post("/api/stt")
def transcribe_voice():
    return {"ok": False}
"#,
        )
        .expect("write review_server.py");

        let initial = server.context(Parameters(params_for(project.path()))).await;
        serde_json::from_str::<serde_json::Value>(&initial).expect("prime snapshot");

        let output = server
            .follow(Parameters(FollowParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                scope: "twins".to_string(),
                handler: None,
                limit: 10,
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("follow output should be valid JSON");

        // The route_twins envelope MUST exist (parity contract with CLI).
        let route_twins = value["trails"]["twins"]["route_twins"]
            .as_object()
            .unwrap_or_else(|| {
                panic!(
                    "MCP follow(twins) must expose route_twins envelope for CLI parity: {output}"
                )
            });
        let total = route_twins["total"].as_u64().unwrap_or(0);
        let signals = route_twins["signals"]
            .as_array()
            .expect("route_twins.signals array");

        // If the Python analyzer in this build surfaces FastAPI routes,
        // the duplicate POST /api/stt must show up; if it does not
        // surface routes at all (analyzer feature flag), the envelope
        // is still present (total=0) so the contract still holds.
        if total > 0 {
            let stt_collision = signals.iter().find(|sig| {
                sig["path"] == "/api/stt" && sig["method"].as_str().unwrap_or("") == "POST"
            });
            assert!(
                stt_collision.is_some(),
                "POST /api/stt must surface as a route twin when route analyzer is active: {output}"
            );
        }
    }

    #[tokio::test]
    async fn focus_summary_counts_external_edges_it_lists() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        fs::create_dir_all(project.path().join("src/pages")).expect("create pages dir");
        fs::write(
            project.path().join("src/pages/mod.rs"),
            r#"use crate::foo::helper;

pub fn page() {
    let _ = helper();
}
"#,
        )
        .expect("write pages module");

        let output = server
            .focus(Parameters(FocusParams {
                project: project.path().display().to_string(),
                force_no_git: true,
                directory: "src/pages".to_string(),
            }))
            .await;

        let value: serde_json::Value =
            serde_json::from_str(&output).expect("focus output should be valid JSON");
        let listed_deps = value["external_dependencies"]
            .as_array()
            .expect("external deps array")
            .len();

        assert!(
            listed_deps > 0,
            "fixture should produce at least one external dependency: {output}"
        );
        assert_eq!(
            value["summary"]["external_dependency_edges"], listed_deps,
            "summary should count the same external dependency edges focus lists"
        );
    }

    #[tokio::test]
    async fn context_format_defaults_to_json() {
        let project = fixture_project();
        let output = context_output(project.path(), |_| {}).await;
        let value: Value = serde_json::from_str(&output).expect("valid context json");

        assert_eq!(value["protocol"], "loctree.context_atlas.v1");
        assert!(value.get("markdown").is_none());
        assert_ne!(value["format"], "markdown");
    }

    #[tokio::test]
    async fn context_format_markdown_returns_pill() {
        let project = fixture_project();
        let output = context_output(project.path(), |params| {
            params.format = ContextFormat::Markdown;
        })
        .await;
        let value: Value = serde_json::from_str(&output).expect("valid markdown wrapper json");

        assert_eq!(value["protocol"], "loctree.context_atlas.v1");
        assert_eq!(value["format"], "markdown");
        assert_eq!(value["status"], "complete");
        assert!(
            value
                .pointer("/receipt/snapshot/fingerprint/value")
                .is_some()
        );
        assert!(
            value["markdown"]
                .as_str()
                .expect("markdown string")
                .starts_with("# Loctree Context")
        );
        // A small fixture fits in a single page: no truncation (forbidden by
        // decree), pagination is inert, and the receipt accounts for the full
        // pack so completeness is provable rather than trusted.
        assert_eq!(value["pagination"]["paginated"], serde_json::json!(false));
        assert!(value["pagination"]["next_section"].is_null());
        assert!(
            value.pointer("/receipt/full_context/sha256").is_some(),
            "receipt must check off full context via a whole-pack digest"
        );
        assert!(
            value["receipt"]["full_context"]["total_bytes"]
                .as_u64()
                .expect("full_context.total_bytes")
                > 0
        );
        assert_eq!(
            value["receipt"]["full_context"]["complete_in_this_response"],
            serde_json::json!(true)
        );
        // Truncation fields are gone — agents must never get a lossy head.
        assert!(value.get("truncated").is_none());
        assert!(value.get("read_cards_hint").is_none());
    }

    /// Single env-sensitive test for context_markdown_budget() — consolidated to
    /// avoid the parallel race that would occur if multiple #[test]s mutated the
    /// same process-global env var.
    #[test]
    fn context_markdown_budget_env_matrix() {
        // SAFETY: this is the only test that touches CONTEXT_MARKDOWN_BUDGET_ENV;
        // all scenarios run sequentially inside this single test function, so
        // there is no race with another #[test] reading the variable.
        unsafe { std::env::remove_var(CONTEXT_MARKDOWN_BUDGET_ENV) };
        assert_eq!(
            context_markdown_budget(),
            CONTEXT_MARKDOWN_BUDGET_DEFAULT,
            "default applies when env var is unset"
        );

        // Use a value ABOVE the default so a concurrent context() call (e.g.
        // context_format_markdown_returns_pill) just sees a larger single page
        // from this test's transient env mutation — the getter logic is
        // identical regardless of the magnitude.
        unsafe { std::env::set_var(CONTEXT_MARKDOWN_BUDGET_ENV, "60000") };
        assert_eq!(
            context_markdown_budget(),
            60_000,
            "valid override is honored"
        );

        // Below the 2_000 floor is rejected (a tiny budget would shred the pack
        // into uselessly small pages).
        unsafe { std::env::set_var(CONTEXT_MARKDOWN_BUDGET_ENV, "1500") };
        assert_eq!(
            context_markdown_budget(),
            CONTEXT_MARKDOWN_BUDGET_DEFAULT,
            "sub-floor value is rejected and falls back to the default"
        );

        unsafe { std::env::set_var(CONTEXT_MARKDOWN_BUDGET_ENV, "0") };
        assert_eq!(
            context_markdown_budget(),
            CONTEXT_MARKDOWN_BUDGET_DEFAULT,
            "zero is rejected and falls back to the default"
        );

        unsafe { std::env::set_var(CONTEXT_MARKDOWN_BUDGET_ENV, "not-a-number") };
        assert_eq!(
            context_markdown_budget(),
            CONTEXT_MARKDOWN_BUDGET_DEFAULT,
            "non-numeric is rejected and falls back to the default"
        );

        unsafe { std::env::remove_var(CONTEXT_MARKDOWN_BUDGET_ENV) };
    }

    #[test]
    fn oversized_tool_response_writes_full_payload_artifact_and_marker() {
        let temp = tempfile::tempdir().expect("temp dir");
        let raw = serde_json::json!({
            "tool": "slice",
            "items": ["x".repeat(CONTEXT_MARKDOWN_BUDGET_DEFAULT + 8_000)]
        })
        .to_string();

        let response = budget_tool_response("slice", Some(temp.path()), raw.clone());
        assert!(
            response.chars().count() <= CONTEXT_MARKDOWN_BUDGET_DEFAULT,
            "budgeted response must stay under default budget"
        );

        let marker: Value = serde_json::from_str(&response).expect("marker JSON");
        assert_eq!(marker["protocol"], MCP_RESPONSE_BUDGET_PROTOCOL);
        assert_eq!(marker["tool"], "slice");
        assert_eq!(marker["status"], "truncated_for_mcp_token_budget");
        let artifact_path = marker["full_payload"]["path"]
            .as_str()
            .expect("full payload path");
        assert!(
            artifact_path.ends_with(".full.json"),
            "marker must point at concrete full JSON artifact: {artifact_path}"
        );
        let artifact = fs::read_to_string(artifact_path).expect("read full payload artifact");
        assert_eq!(artifact, raw, "artifact must preserve unmodified payload");
    }

    #[test]
    fn budgeted_tool_response_keeps_small_payload_unchanged() {
        let raw = serde_json::json!({ "ok": true, "items": [1, 2, 3] }).to_string();
        let response = budget_tool_response("tree", None, raw.clone());
        assert_eq!(response, raw);
    }

    fn synthetic_pack_markdown(section_count: usize, section_chars: usize) -> String {
        let mut out = String::from("# Loctree Context — synthetic\n\nlead-in line\n\n");
        for s in 0..section_count {
            out.push_str(&format!("## Section {s}\n\n"));
            out.push_str(&"x".repeat(section_chars));
            out.push('\n');
        }
        out
    }

    #[test]
    fn split_markdown_keeps_preamble_as_overview_and_counts_h2() {
        let md = synthetic_pack_markdown(2, 10);
        let sections = split_markdown_sections(&md);
        // Overview (title block) + 2 `## ` sections.
        assert_eq!(sections.len(), 3);
        assert_eq!(sections[0].title, "Overview");
        assert_eq!(sections[1].title, "Section 0");
        assert_eq!(sections[2].title, "Section 1");
        // `### ` must not start a new top-level section.
        let nested = "# Title\n\n## Top\n\n### Sub\n\nbody\n";
        let nested_sections = split_markdown_sections(nested);
        assert_eq!(
            nested_sections.len(),
            2,
            "### must stay inside its ## parent"
        );
    }

    #[test]
    fn paginate_returns_whole_pack_unchanged_when_it_fits() {
        let md = synthetic_pack_markdown(3, 50);
        let page = paginate_context_markdown(&md, None, 1_000_000);
        assert!(!page.paginated, "small pack must not paginate");
        assert_eq!(page.markdown, md, "whole pack returned byte-for-byte");
        assert!(page.next_section.is_none());
    }

    #[test]
    fn paginate_splits_and_stays_under_budget_when_oversized() {
        // 6 sections × ~2KB each ≈ 12KB; budget 3KB forces pagination.
        let md = synthetic_pack_markdown(6, 2_000);
        let budget = 3_000;
        let page = paginate_context_markdown(&md, None, budget);
        assert!(page.paginated, "oversized pack must paginate");
        assert!(
            page.markdown.len() <= budget,
            "page {} must fit budget {budget}",
            page.markdown.len()
        );
        assert!(page.next_section.is_some(), "more sections must remain");
        assert!(
            page.sections_emitted >= 1,
            "always emit at least one section"
        );
    }

    #[test]
    fn paginate_cursor_walks_every_section_exactly_once_in_order() {
        let md = synthetic_pack_markdown(6, 2_000);
        let budget = 3_000;
        let total = split_markdown_sections(&md).len();

        let mut cursor: Option<usize> = None;
        let mut covered: Vec<usize> = Vec::new();
        let mut guard = 0;
        loop {
            let page = paginate_context_markdown(&md, cursor, budget);
            assert_eq!(page.total_sections, total);
            for i in 0..page.sections_emitted {
                covered.push(page.section_start + i);
            }
            match page.next_section {
                Some(next) => {
                    assert!(next > page.section_start, "cursor must advance");
                    cursor = Some(next);
                }
                None => break,
            }
            guard += 1;
            assert!(guard < 100, "cursor walk must terminate");
        }
        let expected: Vec<usize> = (0..total).collect();
        assert_eq!(covered, expected, "every section read once, in order");
    }

    #[test]
    fn paginate_truncates_single_oversized_section_with_marker() {
        // A section far bigger than the budget must still be emitted when it
        // is the first on the page, but hard-truncated with an honest tail
        // rather than overflowing. Section 0 lives at index 1 (index 0 is the
        // small "Overview" title block), so aim the cursor straight at it.
        let md = synthetic_pack_markdown(1, 20_000);
        let budget = 4_000;
        let page = paginate_context_markdown(&md, Some(1), budget);
        assert!(page.paginated);
        assert!(
            page.markdown.len() <= budget,
            "truncated page {} must fit budget {budget}",
            page.markdown.len()
        );
        assert!(
            page.markdown
                .contains("truncated: section exceeds the MCP markdown budget"),
            "truncation must be explicit, not silent"
        );
    }

    #[tokio::test]
    async fn context_markdown_response_carries_pagination_block() {
        let project = fixture_project();
        let output = context_output(project.path(), |params| {
            params.format = ContextFormat::Markdown;
        })
        .await;
        let value: Value = serde_json::from_str(&output).expect("valid markdown wrapper json");
        // The tiny fixture fits the budget, so this is a whole-pack response:
        // pagination present, not paginated, status complete.
        assert_eq!(value["format"], "markdown");
        assert_eq!(value["status"], "complete");
        assert_eq!(value["pagination"]["paginated"], false);
        assert!(value["pagination"]["next_section"].is_null());
        assert!(
            value["markdown"]
                .as_str()
                .expect("markdown string")
                .starts_with("# Loctree Context")
        );
    }

    #[test]
    fn context_format_rejects_unknown() {
        let payload = serde_json::json!({
            "project": ".",
            "force_no_git": true,
            "format": "xml"
        });

        assert!(serde_json::from_value::<ContextParams>(payload).is_err());
    }

    #[tokio::test]
    async fn context_rejects_non_git_project_without_force_flag() {
        let project = fixture_project();
        let server = LoctreeServer::new();
        let mut params = params_for(project.path());
        params.force_no_git = false;
        let output = server.context(Parameters(params)).await;
        let value: Value = serde_json::from_str(&output).expect("error should be json-safe");

        assert!(
            value["error"]
                .as_str()
                .unwrap()
                .contains("not inside a git repository")
        );
    }

    #[tokio::test]
    async fn context_accepts_non_git_project_with_force_flag() {
        let project = fixture_project();
        let server = LoctreeServer::new();
        let mut params = params_for(project.path());
        params.force_no_git = true;
        let output = server.context(Parameters(params)).await;
        let value: Value = serde_json::from_str(&output).expect("success should be json-safe");
        println!("Value: {:?}", value);

        // Should return a valid payload (not an error string)
        assert!(value.get("error").is_none());
        assert!(value.get("data").is_some() || value.get("atlas").is_some());
    }

    #[tokio::test]
    async fn context_no_scan_returns_json_error_without_snapshot() {
        let project = fixture_project();
        let output = context_output(project.path(), |params| {
            params.no_scan = true;
        })
        .await;
        let value: Value = serde_json::from_str(&output).expect("error should be json-safe");

        assert!(value["error"].as_str().unwrap().contains("no_scan=true"));
    }

    #[test]
    fn mcp_server_does_not_shell_out_to_loctree_cli() {
        let source = include_str!("main.rs");
        let forbidden_process_bridges = [
            concat!("std::process", "::", "Command"),
            concat!("tokio::process", "::", "Command"),
            concat!("process", "::", "Command"),
            concat!("Command", "::", "new"),
            concat!("duct", "::", "cmd"),
            concat!("xshell", "::"),
            concat!("cargo", " run"),
        ];

        for needle in forbidden_process_bridges {
            assert!(
                !source.contains(needle),
                "loctree-mcp must use loctree library APIs instead of shelling out: found `{needle}`"
            );
        }
    }

    /// Guard against silently re-introducing path-traversal `nosemgrep`
    /// suppressions on the MCP project-path entrypoint. The real fix is
    /// `validate_project_path` — if a future change adds back a
    /// suppression to silence Semgrep instead of strengthening the
    /// validator, this test fails loudly. Test fixtures and unrelated
    /// suppressions inside this same file are still allowed; we only
    /// reject the specific tainted-path rule.
    #[test]
    fn mcp_project_path_has_no_tainted_path_suppressions() {
        let source = include_str!("main.rs");
        let needle = concat!("nose", "mgrep").to_string() + ": rust.actix.path-traversal";
        assert!(
            !source.contains(&needle),
            "loctree-mcp must validate project paths via `validate_project_path`, not suppress Semgrep: found `{needle}`"
        );
        let bare = concat!("// nose", "mgrep");
        let count = source.matches(bare).count();
        assert_eq!(
            count, 0,
            "loctree-mcp must not carry bare `nosemgrep` comments; rely on real validation instead"
        );
    }

    #[test]
    fn validate_project_path_rejects_empty_input() {
        let err = validate_project_path("", None).expect_err("empty input must reject");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn validate_project_path_rejects_whitespace_only_input() {
        let err = validate_project_path("   ", None).expect_err("whitespace input must reject");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn validate_project_path_rejects_null_bytes() {
        let err = validate_project_path("/tmp/proj\0/etc/passwd", None)
            .expect_err("NUL byte must reject");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn validate_project_path_rejects_parent_dir_segments() {
        let err = validate_project_path("../escape", None).expect_err("../escape must reject");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);

        let err =
            validate_project_path("subdir/../../escape", None).expect_err("nested .. must reject");
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn validate_project_path_accepts_relative_paths_without_traversal() {
        validate_project_path("subdir/file", None).expect("clean relative path must pass");
        validate_project_path("./subdir", None).expect("leading ./ must pass");
    }

    #[test]
    fn validate_project_path_with_allowlist_rejects_absolute_path_outside_root() {
        let temp = tempfile::tempdir().expect("temp dir");
        let allowed = vec![temp.path().to_path_buf()];
        // /etc is the canonical "out of bounds" target on Unix runners;
        // skipping the test cleanly on platforms where /etc cannot be
        // assumed keeps the suite hermetic.
        if Path::new("/etc").exists() {
            let err = validate_project_path("/etc", Some(&allowed))
                .expect_err("absolute path outside allowed root must reject");
            assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
        }
    }

    #[test]
    fn validate_project_path_with_allowlist_accepts_absolute_path_inside_root() {
        let temp = tempfile::tempdir().expect("temp dir");
        // canonicalize so the prefix comparison matches /private/var/...
        // on macOS where /tmp -> /private/tmp.
        let allowed_canon = temp.path().canonicalize().expect("canonicalize temp");
        let inside = allowed_canon.join("inner");
        std::fs::create_dir_all(&inside).expect("mkdir inside");
        let allowed = vec![allowed_canon];
        validate_project_path(inside.to_str().expect("utf8"), Some(&allowed))
            .expect("absolute path inside allowed root must pass");
    }

    #[test]
    fn enforce_allowed_root_rejects_path_outside_allowlist() {
        let temp = tempfile::tempdir().expect("temp dir");
        let allowed_canon = temp.path().canonicalize().expect("canonicalize temp");
        let allowed = vec![allowed_canon];
        let outside = Path::new("/");
        let err = enforce_allowed_root(outside, Some(&allowed))
            .expect_err("post-canonical escape must reject");
        assert_eq!(err.kind(), io::ErrorKind::PermissionDenied);
    }

    #[test]
    fn enforce_allowed_root_is_noop_when_unset() {
        // No allowlist configured -> any canonical path passes; this
        // preserves the pre-SaaS local-trust behavior for operators
        // running the server locally without setting LOCTREE_MCP_ALLOWED_ROOTS.
        enforce_allowed_root(Path::new("/anywhere"), None)
            .expect("unset allowlist must be a no-op");
    }

    #[tokio::test]
    async fn resolve_existing_project_path_rejects_traversal() {
        let err = LoctreeServer::resolve_existing_project_path("../etc/passwd")
            .expect_err("traversal must reject");
        let msg = format!("{err:#}");
        assert!(
            msg.contains("Invalid project path") || msg.contains(".."),
            "error message should explain the rejection, got: {msg}"
        );
    }

    #[tokio::test]
    async fn resolve_existing_project_path_rejects_null_byte() {
        let err = LoctreeServer::resolve_existing_project_path("/tmp/abc\0def")
            .expect_err("NUL byte must reject");
        let msg = format!("{err:#}");
        assert!(
            msg.contains("Invalid project path") || msg.contains("NUL"),
            "error message should explain the rejection, got: {msg}"
        );
    }

    #[tokio::test]
    async fn resolve_existing_project_path_rejects_empty() {
        let err = LoctreeServer::resolve_existing_project_path("").expect_err("empty must reject");
        let msg = format!("{err:#}");
        assert!(msg.contains("Invalid project path"));
    }

    #[tokio::test]
    async fn context_tool_returns_model_readable_pretty_json() {
        let project = fixture_project();
        let output = context_output(project.path(), |_| {}).await;

        assert!(
            output.lines().count() > 1,
            "context output must not be one huge line"
        );
        assert!(
            output.contains("\n  \"protocol\""),
            "top-level JSON should be pretty-printed"
        );
        assert!(
            output.contains("\n    \"schema_version\""),
            "nested context data should be readable without char slicing"
        );
        serde_json::from_str::<serde_json::Value>(&output).expect("pretty output remains JSON");
    }

    #[tokio::test]
    async fn context_tool_respects_no_aicx() {
        let project = fixture_project();
        let output = context_output(project.path(), |params| {
            params.with_aicx = false;
            params.no_aicx = true;
        })
        .await;
        let response: serde_json::Value =
            serde_json::from_str(&output).expect("valid context response");

        assert!(response["data"]["memory"].is_null());
        assert_eq!(response["sections_skipped"], serde_json::json!(["memory"]));
    }

    #[tokio::test]
    async fn context_tool_with_file_param() {
        let project = fixture_project();
        let output = context_output(project.path(), |params| {
            params.file = Some("src/foo.rs".to_string());
        })
        .await;
        let response: serde_json::Value =
            serde_json::from_str(&output).expect("valid context response");

        assert_eq!(response["status"], "complete");
        assert!(response["data"].get("project").is_some());
        assert!(response["data"].get("structural").is_some());
    }

    #[tokio::test]
    async fn context_tool_materializes_context_atlas_pointer() {
        let project = fixture_project();
        let output = context_output(project.path(), |_| {}).await;
        let response: Value = serde_json::from_str(&output).expect("valid context response");

        assert_eq!(response["protocol"], "loctree.context_atlas.v1");
        assert_eq!(response["status"], "complete");
        assert!(response["atlas"].is_object());
        assert!(
            response["sections_loaded"]
                .as_array()
                .unwrap()
                .contains(&Value::String("receipt".to_string()))
        );
        assert!(
            response
                .pointer("/receipt/snapshot/fingerprint/value")
                .is_some()
        );
        assert!(response.pointer("/data/structural").is_some());
        assert!(response.pointer("/data/runtime").is_some());
    }

    #[tokio::test]
    async fn context_tool_returns_authority_labels() {
        let project = fixture_project();
        let output = context_output(project.path(), |params| {
            params.file = Some("src/foo.rs".to_string());
        })
        .await;
        let value: Value = serde_json::from_str(&output).expect("valid json");

        assert!(value.pointer("/data/authority/repo_verified").is_some());
        assert!(value.pointer("/data/authority/loctree_derived").is_some());
        assert!(value.pointer("/data/authority/semantic_guess").is_some());
    }

    #[tokio::test]
    async fn repo_view_exposes_snapshot_authority() {
        let project = fixture_project();
        let server = LoctreeServer::new();
        let output = server
            .repo_view(Parameters(ForAiParams {
                project: project.path().display().to_string(),
                force_no_git: true,
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("valid repo-view json");

        assert!(value.pointer("/snapshot/fingerprint/value").is_some());
        assert!(value.pointer("/snapshot/git/commit").is_some());
        assert!(value.pointer("/snapshot/staleness/stale").is_some());
    }

    #[tokio::test]
    async fn repo_view_reports_atlas_available_when_receipt_matches_snapshot() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        // Materialize atlas via context() — receipt.json mirrors the live snapshot.
        let _ = server.context(Parameters(params_for(project.path()))).await;

        let output = server
            .repo_view(Parameters(ForAiParams {
                project: project.path().display().to_string(),
                force_no_git: true,
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("valid repo-view json");

        assert_eq!(
            value["context_atlas"]["status"],
            "atlas_available",
            "context_atlas payload: {}",
            serde_json::to_string_pretty(&value["context_atlas"]).unwrap_or_default()
        );
        assert_eq!(
            value["context_atlas"]["atlas_snapshot"], value["context_atlas"]["current_snapshot"],
            "fresh atlas must echo the live snapshot tag"
        );
    }

    #[tokio::test]
    async fn repo_view_reports_atlas_stale_when_receipt_mismatches_snapshot() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        let _ = server.context(Parameters(params_for(project.path()))).await;
        let receipt_path = atlas_dir_for_project(project.path()).join("receipt.json");
        let raw = fs::read_to_string(&receipt_path).expect("read receipt");
        let mut receipt: Value = serde_json::from_str(&raw).expect("parse receipt");
        receipt["snapshot"] = Value::String("different-branch@deadbeef".to_string());
        fs::write(
            &receipt_path,
            serde_json::to_string_pretty(&receipt).expect("re-serialize receipt"),
        )
        .expect("write mutated receipt");

        let output = server
            .repo_view(Parameters(ForAiParams {
                project: project.path().display().to_string(),
                force_no_git: true,
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("valid repo-view json");

        assert_eq!(value["context_atlas"]["status"], "atlas_stale");
        assert_eq!(
            value["context_atlas"]["atlas_snapshot"],
            "different-branch@deadbeef"
        );
        assert_ne!(
            value["context_atlas"]["atlas_snapshot"],
            value["context_atlas"]["current_snapshot"]
        );
        assert!(
            value["context_atlas"]["message"]
                .as_str()
                .unwrap_or("")
                .contains("misrepresent"),
            "stale atlas message must warn that cards no longer reflect the tree"
        );
    }

    #[tokio::test]
    async fn repo_view_reports_unknown_freshness_when_receipt_missing() {
        let project = fixture_project();
        let server = LoctreeServer::new();

        let _ = server.context(Parameters(params_for(project.path()))).await;
        let receipt_path = atlas_dir_for_project(project.path()).join("receipt.json");
        fs::remove_file(&receipt_path).expect("remove receipt");

        let output = server
            .repo_view(Parameters(ForAiParams {
                project: project.path().display().to_string(),
                force_no_git: true,
            }))
            .await;
        let value: Value = serde_json::from_str(&output).expect("valid repo-view json");

        assert_eq!(value["context_atlas"]["status"], "atlas_unknown_freshness");
        assert!(value["context_atlas"]["atlas_snapshot"].is_null());
    }

    #[test]
    fn public_mcp_tool_surface_is_polarized_to_ten_tools() {
        // The MCP surface stays intentionally small. Eight map/context tools,
        // the literal-only `suppressions` inventory, and the polarization-gate
        // `prism` tool — anything else belongs in the `loct` CLI
        // (health/findings/audit/coverage). Adding a tool here is a
        // surface-area decision; rename or update the assertion deliberately.
        //
        // `suppressions` joined on 2026-05-17 to close the silencer-surface
        // gap recorded in `~/.vibecrafted/loctree/loctree-fail.md` (existing
        // logic under `analyzer/search.rs::search_suppressions` was invisible
        // agent-side; this tool exposes it). Free-tier scope is locked to
        // literal detection. Semantic enrichment is paid-tier Wave 7+.
        let source = include_str!("main.rs");
        let mut tools = Vec::new();
        let mut in_tool_attr = false;
        for line in source.lines() {
            let line = line.trim();
            if line == "#[tool(" {
                in_tool_attr = true;
                continue;
            }
            if !in_tool_attr {
                continue;
            }
            if let Some(rest) = line.strip_prefix("name = \"")
                && let Some((name, _)) = rest.split_once('"')
            {
                tools.push(name.to_string());
            }
            if line == ")]" {
                in_tool_attr = false;
            }
        }

        assert_eq!(
            tools,
            vec![
                "context",
                "repo-view",
                "slice",
                "find",
                "impact",
                "tree",
                "focus",
                "follow",
                "suppressions",
                "prism",
            ]
        );
    }

    /// Tier-boundary regression guard: the `suppressions` MCP tool MUST
    /// stay literal-only in its public description. If a future change
    /// adds semantic enrichment without an explicit feature-flag boundary,
    /// this test fails loudly. This protects the free-tier promise (see
    /// `~/.vibecrafted/loctree/loctree-fail.md` 2026-05-17 addendum +
    /// `loctree::analyzer::suppression_inventory` module docs).
    #[test]
    fn suppressions_mcp_tool_description_advertises_literal_only_free_tier() {
        let source = include_str!("main.rs");
        // Find the tool-description block for `name = "suppressions"`.
        let mut found = false;
        let mut description_line = String::new();
        let mut prev_is_tool_attr = false;
        let mut in_block = false;
        for line in source.lines() {
            let trimmed = line.trim();
            if trimmed == "#[tool(" {
                prev_is_tool_attr = true;
                in_block = false;
                continue;
            }
            if prev_is_tool_attr {
                if trimmed.starts_with("name = \"suppressions\"") {
                    in_block = true;
                }
                prev_is_tool_attr = false;
            }
            if in_block && trimmed.starts_with("description = \"") {
                description_line = trimmed.to_string();
                found = true;
                break;
            }
        }
        assert!(
            found,
            "suppressions tool description not found in main.rs — did it get renamed?"
        );
        let desc_lower = description_line.to_lowercase();
        assert!(
            desc_lower.contains("literal"),
            "suppressions tool description MUST advertise 'literal' detection \
             to keep the free-tier boundary explicit. Found: {description_line}"
        );
        assert!(
            desc_lower.contains("free-tier") || desc_lower.contains("paid-tier"),
            "suppressions tool description MUST name the tier boundary \
             explicitly (free-tier scope OR paid-tier Wave 7+ delta). \
             Found: {description_line}"
        );
    }
}