jonesy 0.9.0

Jonesy is here to help you not panic!
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
//! LSP server for jonesy panic point diagnostics.
//!
//! This module implements a Language Server Protocol server that publishes
//! panic point diagnostics to IDEs and code editors. It runs alongside
//! rust-analyzer, publishing its own diagnostics.
//!
//! File watching is implemented natively using the `notify` crate for reliable
//! detection of binary changes, rather than relying on LSP client file watchers.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::Duration;
use tokio::sync::{Mutex, RwLock};
use tower_lsp::jsonrpc::Result;
use tower_lsp::lsp_types::notification::Progress;
use tower_lsp::lsp_types::request::WorkDoneProgressCreate;
use tower_lsp::lsp_types::*;
use tower_lsp::{Client, LanguageServer, LspService, Server};

use crate::call_tree::CrateCodePoint;
use crate::cargo::{find_binary, find_library};
use crate::file_watcher::{self, WatcherConfig};
use crate::project_context::ProjectContext;
use notify::RecommendedWatcher;

/// Counter for generating unique progress tokens
static PROGRESS_TOKEN_COUNTER: AtomicU32 = AtomicU32::new(0);

/// State shared across the LSP server
struct ServerState {
    /// Workspace root path
    workspace_root: Option<PathBuf>,
    /// Cached panic points by file URI
    panic_points: HashMap<Url, Vec<CrateCodePoint>>,
    /// Files that have been opened (for re-publishing after analysis)
    opened_files: HashSet<Url>,
}

impl ServerState {
    fn new() -> Self {
        Self {
            workspace_root: None,
            panic_points: HashMap::new(),
            opened_files: HashSet::new(),
        }
    }
}

/// The jonesy LSP server backend
struct JonesyLspServer {
    client: Client,
    state: Arc<RwLock<ServerState>>,
    /// Lock to serialize analysis runs and prevent out-of-order diagnostics
    analysis_lock: Arc<Mutex<()>>,
    /// Native file watcher - must be kept alive for watcher to function.
    /// Stored separately from the events receiver which is consumed by the debounce task.
    #[allow(dead_code)] // Kept alive to maintain file watching
    watcher: Arc<RwLock<Option<RecommendedWatcher>>>,
}

impl JonesyLspServer {
    pub fn new(client: Client) -> Self {
        Self {
            client,
            state: Arc::new(RwLock::new(ServerState::new())),
            analysis_lock: Arc::new(Mutex::new(())),
            watcher: Arc::new(RwLock::new(None)),
        }
    }

    /// Convert a CrateCodePoint to an LSP Diagnostic
    fn code_point_to_diagnostic(point: &CrateCodePoint) -> Diagnostic {
        // Get all causes sorted by error code for determinism
        let sorted_causes: Vec<_> = {
            let mut causes: Vec<_> = point.causes.iter().collect();
            causes.sort_by_key(|c| c.error_code());
            causes
        };

        // Build message showing all causes
        let (message, suggestion, error_code, docs_url) = if sorted_causes.is_empty() {
            ("potential panic point".to_string(), None, None, None)
        } else {
            let descriptions: Vec<_> = sorted_causes
                .iter()
                .map(|c| format!("{}/{}: {}", c.error_code(), c.id(), c.description()))
                .collect();
            let primary = sorted_causes[0];
            (
                format!("panic point: {}", descriptions.join(", ")),
                Some(
                    primary
                        .format_suggestion(point.is_direct_panic, point.called_function.as_deref()),
                ),
                Some(primary.error_code().to_string()),
                Url::parse(&primary.docs_url()).ok(),
            )
        };

        let range = Range {
            start: Position {
                line: point.line.saturating_sub(1), // LSP uses 0-based lines
                character: point.column.unwrap_or(1).saturating_sub(1),
            },
            end: Position {
                line: point.line.saturating_sub(1),
                character: point.column.unwrap_or(1).saturating_sub(1) + 10, // Approximate width
            },
        };

        // Store cause info in data field for use by code actions
        // Use sorted_causes for consistency with the displayed message
        let cause_ids: Vec<String> = sorted_causes.iter().map(|c| c.id().to_string()).collect();
        let data = serde_json::json!({
            "causes": cause_ids,
            "function": &point.name,
            "file": &point.file,
            "called_function": &point.called_function,
            "is_direct_panic": point.is_direct_panic,
        });

        // Create code_description with documentation URL if available
        let code_description = docs_url.map(|href| CodeDescription { href });

        let mut diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            code: error_code.map(NumberOrString::String),
            code_description,
            source: Some("jonesy".to_string()),
            message,
            related_information: None,
            tags: None,
            data: Some(data),
        };

        // Add suggestion as related information if available
        if let Some(help) = suggestion {
            if !help.is_empty() {
                diagnostic.message = format!("{}\nhelp: {}", diagnostic.message, help);
            }
        }

        diagnostic
    }

    /// Create a progress token and request the client to show progress UI.
    /// Returns the token if successful, None if the client doesn't support it.
    async fn create_progress(&self) -> Option<ProgressToken> {
        let token_id = PROGRESS_TOKEN_COUNTER.fetch_add(1, Ordering::SeqCst);
        let token = ProgressToken::Number(token_id as i32);

        // Request the client to create a progress indicator
        match self
            .client
            .send_request::<WorkDoneProgressCreate>(WorkDoneProgressCreateParams {
                token: token.clone(),
            })
            .await
        {
            Ok(()) => Some(token),
            Err(e) => {
                // Client may not support progress - log and continue without it
                self.client
                    .log_message(MessageType::LOG, format!("Progress not supported: {}", e))
                    .await;
                None
            }
        }
    }

    /// Send a progress begin notification
    async fn progress_begin(&self, token: &ProgressToken, title: &str, message: Option<&str>) {
        self.client
            .send_notification::<Progress>(ProgressParams {
                token: token.clone(),
                value: ProgressParamsValue::WorkDone(WorkDoneProgress::Begin(
                    WorkDoneProgressBegin {
                        title: title.to_string(),
                        cancellable: Some(false),
                        message: message.map(String::from),
                        percentage: Some(0),
                    },
                )),
            })
            .await;
    }

    /// Send a progress report notification
    async fn progress_report(&self, token: &ProgressToken, message: &str, percentage: u32) {
        self.client
            .send_notification::<Progress>(ProgressParams {
                token: token.clone(),
                value: ProgressParamsValue::WorkDone(WorkDoneProgress::Report(
                    WorkDoneProgressReport {
                        cancellable: Some(false),
                        message: Some(message.to_string()),
                        percentage: Some(percentage),
                    },
                )),
            })
            .await;
    }

    /// Send a progress end notification
    async fn progress_end(&self, token: &ProgressToken, message: &str) {
        self.client
            .send_notification::<Progress>(ProgressParams {
                token: token.clone(),
                value: ProgressParamsValue::WorkDone(WorkDoneProgress::End(WorkDoneProgressEnd {
                    message: Some(message.to_string()),
                })),
            })
            .await;
    }

    /// Register file watchers for binaries and config files.
    /// Watches target/debug/ for binary changes and config files (jonesy.toml, Cargo.toml).
    async fn register_file_watchers(&self) {
        // Clone workspace_root and release lock before async operations
        let workspace_root = {
            let state = self.state.read().await;
            state.workspace_root.clone()
        };
        let Some(workspace_root) = workspace_root else {
            return;
        };

        // Build glob patterns for target/debug/ binaries
        let target_debug = workspace_root.join("target/debug");
        let target_debug_str = target_debug.to_string_lossy();

        // Watch for all files in target/debug/ (binaries, rlibs, dylibs)
        let mut watchers = vec![
            FileSystemWatcher {
                glob_pattern: GlobPattern::String(format!("{}/*", target_debug_str)),
                kind: Some(WatchKind::Create | WatchKind::Change),
            },
            // Also watch for dSYM bundles on macOS
            FileSystemWatcher {
                glob_pattern: GlobPattern::String(format!("{}/*.dSYM/**", target_debug_str)),
                kind: Some(WatchKind::Create | WatchKind::Change),
            },
        ];

        // Watch config files (jonesy.toml and Cargo.toml files)
        let config_files = find_config_files(&workspace_root);
        for config_path in &config_files {
            watchers.push(FileSystemWatcher {
                glob_pattern: GlobPattern::String(config_path.to_string_lossy().to_string()),
                kind: Some(WatchKind::Create | WatchKind::Change | WatchKind::Delete),
            });
        }

        let registration_options = DidChangeWatchedFilesRegistrationOptions { watchers };

        let registration = Registration {
            id: "jonesy-file-watcher".to_string(),
            method: "workspace/didChangeWatchedFiles".to_string(),
            register_options: Some(serde_json::to_value(registration_options).unwrap()),
        };

        match self.client.register_capability(vec![registration]).await {
            Ok(()) => {
                self.client
                    .log_message(
                        MessageType::INFO,
                        format!(
                            "Watching {} for binary changes and {} config file(s)",
                            target_debug_str,
                            config_files.len()
                        ),
                    )
                    .await;
            }
            Err(e) => {
                self.client
                    .log_message(
                        MessageType::WARNING,
                        format!("Failed to register file watchers: {}", e),
                    )
                    .await;
            }
        }
    }

    /// Start native file watching using the `notify` crate.
    ///
    /// This provides reliable detection of binary changes, unlike LSP file watchers
    /// which many IDEs don't implement for paths outside source directories.
    ///
    /// Returns true if native watching started successfully, false otherwise.
    /// LSP file watchers should only be registered as fallback when this returns false.
    async fn start_native_file_watcher(&self) -> bool {
        let workspace_root = {
            let state = self.state.read().await;
            state.workspace_root.clone()
        };

        let Some(workspace_root) = workspace_root else {
            return false;
        };

        let target_dir = workspace_root.join("target/debug");
        let config_files = find_config_files(&workspace_root);

        let config = WatcherConfig {
            target_dir: target_dir.clone(),
            config_files: config_files.clone(),
            debounce: Duration::from_millis(500),
        };

        // Start the file watcher
        let watcher_handle = match file_watcher::start_watching(config) {
            Ok(handle) => handle,
            Err(e) => {
                self.client
                    .log_message(
                        MessageType::WARNING,
                        format!("Failed to start native file watcher: {}", e),
                    )
                    .await;
                return false;
            }
        };

        self.client
            .log_message(
                MessageType::INFO,
                format!("Native file watcher started for {}", target_dir.display()),
            )
            .await;

        // Destructure handle to get events receiver and watcher separately
        let file_watcher::WatcherHandle { events, watcher } = watcher_handle;

        // Store watcher to keep it alive for the server's lifetime
        *self.watcher.write().await = Some(watcher);

        // Create debounced event stream from the events receiver
        let debounced = file_watcher::debounced_events(events, Duration::from_millis(500)).await;

        // Clone what we need for the spawned task
        let client = self.client.clone();
        let state = self.state.clone();
        let analysis_lock = self.analysis_lock.clone();

        // Spawn task to listen for file changes and trigger analysis
        tokio::spawn(async move {
            let mut debounced = debounced;

            while debounced.recv().await.is_some() {
                client
                    .log_message(MessageType::INFO, "File change detected, re-analyzing...")
                    .await;

                // Run analysis (using the same logic as analyze_and_publish)
                run_analysis_task(&client, &state, &analysis_lock).await;
            }
        });

        true
    }

    /// Analyze the workspace and publish diagnostics
    /// Returns true if analysis succeeded, false otherwise
    async fn analyze_and_publish(&self) -> bool {
        // Serialize analysis runs to prevent out-of-order diagnostics
        let _guard = self.analysis_lock.lock().await;

        // Extract workspace root early and release state lock
        let (workspace_root, target_dir) = {
            let state = self.state.read().await;
            let Some(root) = state.workspace_root.clone() else {
                self.client
                    .log_message(MessageType::WARNING, "No workspace root set")
                    .await;
                return false;
            };
            let target_dir = root.join("target").to_string_lossy().to_string();
            (root, target_dir)
        };

        self.client
            .log_message(
                MessageType::INFO,
                format!("Analyzing workspace: {}", workspace_root.display()),
            )
            .await;

        // First, discover workspace structure
        let workspace_info = {
            let workspace_root = workspace_root.clone();
            tokio::task::spawn_blocking(move || discover_workspace(&workspace_root))
                .await
                .ok()
                .flatten()
        };

        if let Some(info) = &workspace_info {
            self.client
                .log_message(
                    MessageType::INFO,
                    format!("Workspace members: {}", info.members.join(", ")),
                )
                .await;
            self.client
                .log_message(
                    MessageType::INFO,
                    format!(
                        "Found {} targets: {}",
                        info.targets.len(),
                        info.targets.join(", ")
                    ),
                )
                .await;
        }

        // Get list of targets to analyze
        let targets = {
            let workspace_root = workspace_root.clone();
            tokio::task::spawn_blocking(move || find_workspace_binaries(&workspace_root))
                .await
                .ok()
                .and_then(|r| r.ok())
                .unwrap_or_default()
        };

        if targets.is_empty() {
            self.client
                .log_message(MessageType::WARNING, "No targets found to analyze")
                .await;
            return false;
        }

        self.client
            .log_message(
                MessageType::INFO,
                format!("Starting analysis of {} targets...", targets.len()),
            )
            .await;

        // Create progress indicator for IDE status bar
        let progress_token = self.create_progress().await;
        if let Some(ref token) = progress_token {
            self.progress_begin(token, "Panic Analysis", Some("Analyzing targets..."))
                .await;
        }

        // Build ProjectContext once for the workspace
        let project_context = {
            let root = workspace_root.clone();
            tokio::task::spawn_blocking(move || ProjectContext::from_project_root(&root))
                .await
                .unwrap_or_else(|e| Err(format!("Failed to build project context: {e}")))
        };
        let project_context = match project_context {
            Ok(ctx) => Arc::new(ctx),
            Err(e) => {
                self.client
                    .log_message(MessageType::ERROR, format!("ProjectContext error: {e}"))
                    .await;
                if let Some(ref token) = progress_token {
                    self.progress_end(token, "ProjectContext error").await;
                }
                return false;
            }
        };

        // Track all diagnostics by file URI (accumulates across targets)
        let mut points_by_file: HashMap<Url, Vec<CrateCodePoint>> = HashMap::new();
        let mut seen: std::collections::HashSet<(String, u32, u32)> =
            std::collections::HashSet::new();
        let mut total_points = 0usize;

        // Analyze each target and publish diagnostics incrementally
        let total_targets = targets.len();
        for (target_idx, target) in targets.iter().enumerate() {
            let target_name = target
                .file_name()
                .map(|n| n.to_string_lossy().to_string())
                .unwrap_or_else(|| "unknown".to_string());

            // Update progress indicator
            if let Some(ref token) = progress_token {
                let percentage = (((target_idx + 1) * 100) / total_targets) as u32;
                self.progress_report(
                    token,
                    &format!(
                        "Analyzing {} ({}/{})",
                        target_name,
                        target_idx + 1,
                        total_targets
                    ),
                    percentage,
                )
                .await;
            }

            let analysis_result = {
                let target = target.clone();
                let project_context = Arc::clone(&project_context);
                tokio::task::spawn_blocking(move || {
                    analyze_single_target(&target, &project_context)
                })
                .await
            };

            match analysis_result {
                Ok(Ok(points)) => {
                    // Filter to new points only (dedup across targets)
                    let new_points: Vec<_> = points
                        .into_iter()
                        .filter(|p| {
                            let key = (p.file.clone(), p.line, p.column.unwrap_or(0));
                            seen.insert(key)
                        })
                        .collect();

                    let point_count = new_points.len();
                    total_points += point_count;

                    self.client
                        .log_message(
                            MessageType::INFO,
                            format!("  {} - {} new panic points", target_name, point_count),
                        )
                        .await;

                    // Group new points by file and publish incrementally
                    let mut files_updated: std::collections::HashSet<Url> =
                        std::collections::HashSet::new();

                    for point in new_points {
                        // Skip files in target/ directory
                        if point.file.starts_with(&target_dir) {
                            continue;
                        }

                        let raw_path = PathBuf::from(&point.file);
                        let file_path = if raw_path.is_absolute() {
                            raw_path
                        } else {
                            workspace_root.join(raw_path)
                        };

                        if let Ok(uri) = Url::from_file_path(&file_path) {
                            files_updated.insert(uri.clone());
                            points_by_file.entry(uri).or_default().push(point);
                        }
                    }

                    // Publish updated diagnostics for files that changed
                    for uri in files_updated {
                        if let Some(points) = points_by_file.get(&uri) {
                            let diagnostics: Vec<Diagnostic> =
                                points.iter().map(Self::code_point_to_diagnostic).collect();

                            self.client
                                .publish_diagnostics(uri.clone(), diagnostics, None)
                                .await;
                        }
                    }
                }
                Ok(Err(e)) => {
                    self.client
                        .log_message(
                            MessageType::LOG,
                            format!("  {} - skipped: {}", target_name, e),
                        )
                        .await;
                }
                Err(_) => {
                    self.client
                        .log_message(
                            MessageType::WARNING,
                            format!("  {} - analysis failed", target_name),
                        )
                        .await;
                }
            }
        }

        // Update state with final results
        let mut state = self.state.write().await;
        let old_files: std::collections::HashSet<_> = state.panic_points.keys().cloned().collect();
        let new_files: std::collections::HashSet<_> = points_by_file.keys().cloned().collect();
        state.panic_points = points_by_file;
        drop(state);

        // Clear diagnostics for files that no longer have panic points
        for uri in old_files.difference(&new_files) {
            self.client
                .publish_diagnostics(uri.clone(), vec![], None)
                .await;
        }

        // Complete progress indicator
        if let Some(ref token) = progress_token {
            self.progress_end(
                token,
                &format!(
                    "Found {} panic points in {} files",
                    total_points,
                    new_files.len()
                ),
            )
            .await;
        }

        self.client
            .log_message(
                MessageType::INFO,
                format!(
                    "Analysis complete: {} panic points in {} files",
                    total_points,
                    new_files.len()
                ),
            )
            .await;

        // Re-publish diagnostics to files that were opened before/during analysis
        // Snapshot all data while holding the lock once, then publish outside the lock
        let republish: Vec<(Url, Vec<Diagnostic>)> = {
            let state = self.state.read().await;
            state
                .opened_files
                .iter()
                .filter_map(|uri| {
                    state.panic_points.get(uri).map(|points| {
                        let diagnostics =
                            points.iter().map(Self::code_point_to_diagnostic).collect();
                        (uri.clone(), diagnostics)
                    })
                })
                .collect()
        };

        for (uri, diagnostics) in republish {
            if !diagnostics.is_empty() {
                self.client
                    .publish_diagnostics(uri, diagnostics, None)
                    .await;
            }
        }
        true
    }

    /// Create a code action that inserts or extends an inline allow comment.
    /// If the line already has a `// jonesy:allow(...)` comment, the new cause
    /// is merged into the existing parenthesised list instead of appending a
    /// second comment.
    fn create_inline_allow_action(
        uri: &Url,
        range: Range,
        cause: &str,
        diagnostic: &Diagnostic,
    ) -> Option<CodeAction> {
        let title = if cause == "*" {
            "Allow all panics on this line".to_string()
        } else {
            format!("Allow '{}' on this line", cause)
        };

        // Try to read the line to check for an existing jonesy:allow comment
        // Accept both "// jonesy:allow(" and "// jonesy: allow("
        let existing_allow = uri.to_file_path().ok().and_then(|path| {
            let content = std::fs::read_to_string(&path).ok()?;
            let line = content.lines().nth(range.start.line as usize)?;
            let allow_start = line
                .find("// jonesy:allow(")
                .or_else(|| line.find("// jonesy: allow("))?;
            let paren_start = line[allow_start..].find('(')? + allow_start + 1;
            let rest = &line[paren_start..];
            let paren_end = rest.find(')')?;
            let existing_causes = &rest[..paren_end];
            Some((
                allow_start as u32,
                existing_causes.to_string(),
                line.len() as u32,
            ))
        });

        let edit = if let Some((col_start, existing_causes, _line_len)) = existing_allow {
            // Merge: replace the existing comment with combined causes
            let mut causes: Vec<&str> = existing_causes.split(',').map(|s| s.trim()).collect();
            if !causes.contains(&cause) {
                causes.push(cause);
            }
            let merged = causes.join(", ");
            let comment = format!("// jonesy:allow({})", merged);
            TextEdit {
                range: Range {
                    start: Position {
                        line: range.start.line,
                        character: col_start,
                    },
                    end: Position {
                        line: range.start.line,
                        character: 10000, // Replace to end of line
                    },
                },
                new_text: comment,
            }
        } else {
            // No existing comment — append new one at end of line
            TextEdit {
                range: Range {
                    start: Position {
                        line: range.start.line,
                        character: 10000,
                    },
                    end: Position {
                        line: range.start.line,
                        character: 10000,
                    },
                },
                new_text: format!(" // jonesy:allow({})", cause),
            }
        };

        let mut changes = HashMap::new();
        changes.insert(uri.clone(), vec![edit]);

        Some(CodeAction {
            title,
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: Some(vec![diagnostic.clone()]),
            edit: Some(WorkspaceEdit {
                changes: Some(changes),
                document_changes: None,
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(cause != "*"), // Prefer specific cause over wildcard
            disabled: None,
            data: None,
        })
    }

    /// Create a code action that adds a file-scoped rule to jonesy.toml.
    fn create_file_allow_action(
        uri: &Url,
        cause: &str,
        workspace_root: &Path,
        diagnostic: &Diagnostic,
    ) -> Option<CodeAction> {
        // Extract filename from URI
        let filename = uri.path().rsplit('/').next()?;

        let title = format!("Allow '{}' in {}", cause, filename);
        let rule_text = format!(
            "\n[[rules]]\npath = \"**/{}\"\nallow = [\"{}\"]\n",
            filename, cause
        );

        let jonesy_toml_path = workspace_root.join("jonesy.toml");
        let jonesy_toml_uri = Url::from_file_path(&jonesy_toml_path).ok()?;

        // Check if jonesy.toml exists and get its length
        let (file_exists, file_length) = if jonesy_toml_path.exists() {
            let content = std::fs::read_to_string(&jonesy_toml_path).unwrap_or_default();
            let lines = content.lines().count() as u32;
            (true, lines)
        } else {
            (false, 0)
        };

        let mut document_changes = Vec::new();

        // If file doesn't exist, create it first
        if !file_exists {
            document_changes.push(DocumentChangeOperation::Op(ResourceOp::Create(
                CreateFile {
                    uri: jonesy_toml_uri.clone(),
                    options: Some(CreateFileOptions {
                        overwrite: Some(false),
                        ignore_if_exists: Some(true),
                    }),
                    annotation_id: None,
                },
            )));
        }

        // Add the rule to the file
        let edit = TextEdit {
            range: Range {
                start: Position {
                    line: file_length,
                    character: 0,
                },
                end: Position {
                    line: file_length,
                    character: 0,
                },
            },
            new_text: rule_text,
        };

        document_changes.push(DocumentChangeOperation::Edit(TextDocumentEdit {
            text_document: OptionalVersionedTextDocumentIdentifier {
                uri: jonesy_toml_uri,
                version: None,
            },
            edits: vec![OneOf::Left(edit)],
        }));

        Some(CodeAction {
            title,
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: Some(vec![diagnostic.clone()]),
            edit: Some(WorkspaceEdit {
                changes: None,
                document_changes: Some(DocumentChanges::Operations(document_changes)),
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: None,
        })
    }

    /// Create a code action that adds a function-scoped rule to jonesy.toml.
    fn create_function_allow_action(
        function: &str,
        cause: &str,
        workspace_root: &Path,
        diagnostic: &Diagnostic,
    ) -> Option<CodeAction> {
        // Use full function path for precise matching
        let title = format!("Allow '{}' in this function", cause);
        let rule_text = format!(
            "\n[[rules]]\nfunction = \"{}\"\nallow = [\"{}\"]\n",
            function, cause
        );

        let jonesy_toml_path = workspace_root.join("jonesy.toml");
        let jonesy_toml_uri = Url::from_file_path(&jonesy_toml_path).ok()?;

        // Check if jonesy.toml exists and get its length
        let (file_exists, file_length) = if jonesy_toml_path.exists() {
            let content = std::fs::read_to_string(&jonesy_toml_path).unwrap_or_default();
            let lines = content.lines().count() as u32;
            (true, lines)
        } else {
            (false, 0)
        };

        let mut document_changes = Vec::new();

        // If file doesn't exist, create it first
        if !file_exists {
            document_changes.push(DocumentChangeOperation::Op(ResourceOp::Create(
                CreateFile {
                    uri: jonesy_toml_uri.clone(),
                    options: Some(CreateFileOptions {
                        overwrite: Some(false),
                        ignore_if_exists: Some(true),
                    }),
                    annotation_id: None,
                },
            )));
        }

        // Add the rule to the file
        let edit = TextEdit {
            range: Range {
                start: Position {
                    line: file_length,
                    character: 0,
                },
                end: Position {
                    line: file_length,
                    character: 0,
                },
            },
            new_text: rule_text,
        };

        document_changes.push(DocumentChangeOperation::Edit(TextDocumentEdit {
            text_document: OptionalVersionedTextDocumentIdentifier {
                uri: jonesy_toml_uri,
                version: None,
            },
            edits: vec![OneOf::Left(edit)],
        }));

        Some(CodeAction {
            title,
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: Some(vec![diagnostic.clone()]),
            edit: Some(WorkspaceEdit {
                changes: None,
                document_changes: Some(DocumentChanges::Operations(document_changes)),
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: None,
        })
    }

    /// Create a code action that adds a function-scoped rule to jonesy.toml
    /// to silence all panics from calls to a specific function.
    /// This is for indirect panics where the panic originates in a called function.
    fn create_called_function_allow_action(
        called_function: &str,
        cause: &str,
        workspace_root: &Path,
        diagnostic: &Diagnostic,
    ) -> Option<CodeAction> {
        let title = format!("Allow '{cause}' on calls to '{called_function}()'");
        let rule_text =
            format!("\n[[rules]]\nfunction = \"{called_function}\"\nallow = [\"{cause}\"]\n");

        let jonesy_toml_path = workspace_root.join("jonesy.toml");
        let jonesy_toml_uri = Url::from_file_path(&jonesy_toml_path).ok()?;

        let (file_exists, file_length) = if jonesy_toml_path.exists() {
            let content = std::fs::read_to_string(&jonesy_toml_path).unwrap_or_default();
            let lines = content.lines().count() as u32;
            (true, lines)
        } else {
            (false, 0)
        };

        let mut document_changes = Vec::new();

        if !file_exists {
            document_changes.push(DocumentChangeOperation::Op(ResourceOp::Create(
                CreateFile {
                    uri: jonesy_toml_uri.clone(),
                    options: Some(CreateFileOptions {
                        overwrite: Some(false),
                        ignore_if_exists: Some(true),
                    }),
                    annotation_id: None,
                },
            )));
        }

        let edit = TextEdit {
            range: Range {
                start: Position {
                    line: file_length,
                    character: 0,
                },
                end: Position {
                    line: file_length,
                    character: 0,
                },
            },
            new_text: rule_text,
        };

        document_changes.push(DocumentChangeOperation::Edit(TextDocumentEdit {
            text_document: OptionalVersionedTextDocumentIdentifier {
                uri: jonesy_toml_uri,
                version: None,
            },
            edits: vec![OneOf::Left(edit)],
        }));

        Some(CodeAction {
            title,
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: Some(vec![diagnostic.clone()]),
            edit: Some(WorkspaceEdit {
                changes: None,
                document_changes: Some(DocumentChanges::Operations(document_changes)),
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: None,
        })
    }

    /// Create a code action that adds a module-scoped rule to jonesy.toml.
    /// Returns the path pattern (e.g., "**/tests/**") and whether it applies.
    fn get_module_pattern(uri: &Url) -> Option<(&'static str, &'static str)> {
        let path = uri.path();
        // Check for common test directories/files
        if path.contains("/tests/") {
            Some(("**/tests/**", "tests"))
        } else if path.contains("/benches/") {
            Some(("**/benches/**", "benches"))
        } else if path.contains("/examples/") {
            Some(("**/examples/**", "examples"))
        } else if path.ends_with("_test.rs") {
            Some(("**/*_test.rs", "test files"))
        } else if path.ends_with("_tests.rs") {
            Some(("**/*_tests.rs", "test files"))
        } else {
            None
        }
    }

    fn create_module_allow_action(
        uri: &Url,
        cause: &str,
        workspace_root: &Path,
        diagnostic: &Diagnostic,
    ) -> Option<CodeAction> {
        let (pattern, module_name) = Self::get_module_pattern(uri)?;

        let title = format!("Allow '{}' in {}", cause, module_name);
        let rule_text = format!(
            "\n[[rules]]\npath = \"{}\"\nallow = [\"{}\"]\n",
            pattern, cause
        );

        let jonesy_toml_path = workspace_root.join("jonesy.toml");
        let jonesy_toml_uri = Url::from_file_path(&jonesy_toml_path).ok()?;

        // Check if jonesy.toml exists and get its length
        let (file_exists, file_length) = if jonesy_toml_path.exists() {
            let content = std::fs::read_to_string(&jonesy_toml_path).unwrap_or_default();
            let lines = content.lines().count() as u32;
            (true, lines)
        } else {
            (false, 0)
        };

        let mut document_changes = Vec::new();

        // If file doesn't exist, create it first
        if !file_exists {
            document_changes.push(DocumentChangeOperation::Op(ResourceOp::Create(
                CreateFile {
                    uri: jonesy_toml_uri.clone(),
                    options: Some(CreateFileOptions {
                        overwrite: Some(false),
                        ignore_if_exists: Some(true),
                    }),
                    annotation_id: None,
                },
            )));
        }

        // Add the rule to the file
        let edit = TextEdit {
            range: Range {
                start: Position {
                    line: file_length,
                    character: 0,
                },
                end: Position {
                    line: file_length,
                    character: 0,
                },
            },
            new_text: rule_text,
        };

        document_changes.push(DocumentChangeOperation::Edit(TextDocumentEdit {
            text_document: OptionalVersionedTextDocumentIdentifier {
                uri: jonesy_toml_uri,
                version: None,
            },
            edits: vec![OneOf::Left(edit)],
        }));

        Some(CodeAction {
            title,
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: Some(vec![diagnostic.clone()]),
            edit: Some(WorkspaceEdit {
                changes: None,
                document_changes: Some(DocumentChanges::Operations(document_changes)),
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: None,
        })
    }

    /// Create a code action that adds a crate-level allow rule to jonesy.toml.
    fn create_crate_allow_action(
        cause: &str,
        workspace_root: &Path,
        diagnostic: &Diagnostic,
    ) -> Option<CodeAction> {
        let title = format!("Allow '{}' in this crate", cause);

        let jonesy_toml_path = workspace_root.join("jonesy.toml");
        let jonesy_toml_uri = Url::from_file_path(&jonesy_toml_path).ok()?;

        // Read existing content to check if allow already exists
        let (file_exists, existing_content) = if jonesy_toml_path.exists() {
            let content = std::fs::read_to_string(&jonesy_toml_path).unwrap_or_default();
            (true, content)
        } else {
            (false, String::new())
        };

        // Build the new allow line
        let new_allow = format!("allow = [\"{}\"]", cause);

        // Find where sections start (root-level keys must appear before any [section])
        let first_section_pos = existing_content
            .find("\n[")
            .or_else(|| {
                if existing_content.starts_with('[') {
                    Some(0)
                } else {
                    None
                }
            })
            .unwrap_or(existing_content.len());

        // Only look for root-level allow (before any section headers)
        let root_content = &existing_content[..first_section_pos];

        // Determine the edit based on existing content
        let (edit_range, new_text) = if let Some(start_idx) = root_content.find("allow = [") {
            // Update existing root-level allow line
            let prefix = &existing_content[..start_idx];
            let line_num = prefix.lines().count() as u32;
            let line_start = prefix.rfind('\n').map(|i| i + 1).unwrap_or(0);
            let char_offset = (start_idx - line_start) as u32;

            // Find the end of the allow array
            if let Some(end_bracket) = existing_content[start_idx..].find(']') {
                let end_pos = start_idx + end_bracket + 1;
                let old_allow = &existing_content[start_idx..end_pos];

                // Parse existing causes and add new one if not present
                let mut causes: Vec<String> = old_allow
                    .trim_start_matches("allow = [")
                    .trim_end_matches(']')
                    .split(',')
                    .map(|s| s.trim().trim_matches('"').to_string())
                    .filter(|s| !s.is_empty())
                    .collect();

                if causes.contains(&cause.to_string()) {
                    return None; // Already allowed
                }
                causes.push(cause.to_string());

                let new_allow_line = format!(
                    "allow = [{}]",
                    causes
                        .iter()
                        .map(|c| format!("\"{}\"", c))
                        .collect::<Vec<_>>()
                        .join(", ")
                );

                let end_line = existing_content[..end_pos].lines().count() as u32 - 1;
                let end_char =
                    (end_pos - existing_content[..end_pos].rfind('\n').unwrap_or(0)) as u32;

                (
                    Range {
                        start: Position {
                            line: line_num.saturating_sub(1),
                            character: char_offset,
                        },
                        end: Position {
                            line: end_line,
                            character: end_char,
                        },
                    },
                    new_allow_line,
                )
            } else {
                return None;
            }
        } else {
            // Add new allow line at the beginning of the file
            (
                Range {
                    start: Position {
                        line: 0,
                        character: 0,
                    },
                    end: Position {
                        line: 0,
                        character: 0,
                    },
                },
                format!("{}\n", new_allow),
            )
        };

        let mut document_changes = Vec::new();

        // If file doesn't exist, create it first
        if !file_exists {
            document_changes.push(DocumentChangeOperation::Op(ResourceOp::Create(
                CreateFile {
                    uri: jonesy_toml_uri.clone(),
                    options: Some(CreateFileOptions {
                        overwrite: Some(false),
                        ignore_if_exists: Some(true),
                    }),
                    annotation_id: None,
                },
            )));
        }

        let edit = TextEdit {
            range: edit_range,
            new_text,
        };

        document_changes.push(DocumentChangeOperation::Edit(TextDocumentEdit {
            text_document: OptionalVersionedTextDocumentIdentifier {
                uri: jonesy_toml_uri,
                version: None,
            },
            edits: vec![OneOf::Left(edit)],
        }));

        Some(CodeAction {
            title,
            kind: Some(CodeActionKind::QUICKFIX),
            diagnostics: Some(vec![diagnostic.clone()]),
            edit: Some(WorkspaceEdit {
                changes: None,
                document_changes: Some(DocumentChanges::Operations(document_changes)),
                change_annotations: None,
            }),
            command: None,
            is_preferred: Some(false),
            disabled: None,
            data: None,
        })
    }
}

#[tower_lsp::async_trait]
impl LanguageServer for JonesyLspServer {
    async fn initialize(&self, params: InitializeParams) -> Result<InitializeResult> {
        // Store workspace root - try root_uri first, then fallback to workspace_folders
        let workspace_path = if let Some(root_uri) = params.root_uri {
            root_uri.to_file_path().ok()
        } else if let Some(folders) = params.workspace_folders {
            folders.first().and_then(|f| f.uri.to_file_path().ok())
        } else {
            None
        };

        if let Some(path) = workspace_path {
            let mut state = self.state.write().await;
            state.workspace_root = Some(path);
        }

        Ok(InitializeResult {
            capabilities: ServerCapabilities {
                text_document_sync: Some(TextDocumentSyncCapability::Options(
                    TextDocumentSyncOptions {
                        open_close: Some(true),
                        change: Some(TextDocumentSyncKind::INCREMENTAL),
                        will_save: None,
                        will_save_wait_until: None,
                        save: Some(TextDocumentSyncSaveOptions::Supported(true)),
                    },
                )),
                execute_command_provider: Some(ExecuteCommandOptions {
                    commands: vec!["jonesy.analyze".to_string()],
                    work_done_progress_options: WorkDoneProgressOptions::default(),
                }),
                code_action_provider: Some(CodeActionProviderCapability::Simple(true)),
                ..Default::default()
            },
            server_info: Some(ServerInfo {
                name: "jonesy".to_string(),
                version: Some(crate::args::VERSION.to_string()),
            }),
        })
    }

    async fn initialized(&self, _: InitializedParams) {
        self.client
            .log_message(MessageType::INFO, "Jonesy LSP server initialized")
            .await;

        // Start native file watcher for reliable binary change detection
        let native_watcher_started = self.start_native_file_watcher().await;

        // Only register LSP file watchers as fallback if native watcher failed
        if !native_watcher_started {
            self.client
                .log_message(
                    MessageType::INFO,
                    "Falling back to LSP file watchers (may not work for binary changes)",
                )
                .await;
            self.register_file_watchers().await;
        }

        // Run initial analysis
        self.analyze_and_publish().await;
    }

    async fn shutdown(&self) -> Result<()> {
        Ok(())
    }

    async fn did_open(&self, params: DidOpenTextDocumentParams) {
        let uri = params.text_document.uri;

        // Track opened file for re-publishing diagnostics
        self.state.write().await.opened_files.insert(uri.clone());

        // If we have cached diagnostics for this file, publish them now
        let state = self.state.read().await;
        if let Some(points) = state.panic_points.get(&uri) {
            let diagnostics: Vec<Diagnostic> =
                points.iter().map(Self::code_point_to_diagnostic).collect();
            drop(state); // Release lock before async call

            if !diagnostics.is_empty() {
                self.client
                    .publish_diagnostics(uri, diagnostics, None)
                    .await;
            }
        }
    }

    async fn did_change(&self, _params: DidChangeTextDocumentParams) {
        // No-op: we analyze binaries, not source text
    }

    async fn did_close(&self, params: DidCloseTextDocumentParams) {
        // Remove from opened files tracking
        self.state
            .write()
            .await
            .opened_files
            .remove(&params.text_document.uri);
    }

    async fn did_save(&self, _params: DidSaveTextDocumentParams) {
        // No-op: we watch target/debug/ for binary changes instead of
        // re-analyzing on every file save. This avoids redundant analysis
        // when the user saves files without building.
        //
        // Analysis is triggered by:
        // 1. did_change_watched_files (when binaries or config files change)
        // 2. Manual "jonesy.analyze" command
    }

    async fn did_change_watched_files(&self, params: DidChangeWatchedFilesParams) {
        // Re-analyze when watched files change (binaries or config files)
        let changed_paths: Vec<_> = params
            .changes
            .iter()
            .filter_map(|c| c.uri.to_file_path().ok())
            .collect();

        if changed_paths.is_empty() {
            return;
        }

        // Categorize changes for logging
        let config_changes: Vec<_> = changed_paths
            .iter()
            .filter(|p| {
                p.file_name()
                    .map(|n| n == "jonesy.toml" || n == "Cargo.toml")
                    .unwrap_or(false)
            })
            .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
            .collect();

        let binary_changes: Vec<_> = changed_paths
            .iter()
            .filter(|p| {
                p.file_name()
                    .map(|n| n != "jonesy.toml" && n != "Cargo.toml")
                    .unwrap_or(true)
            })
            .filter_map(|p| p.file_name().map(|n| n.to_string_lossy().to_string()))
            .collect();

        // Log what changed
        if !config_changes.is_empty() {
            self.client
                .log_message(
                    MessageType::INFO,
                    format!("Config changes detected: {}", config_changes.join(", ")),
                )
                .await;

            // Re-register watchers in case workspace membership changed
            // (e.g., Cargo.toml added/removed workspace members)
            self.register_file_watchers().await;
        }
        if !binary_changes.is_empty() {
            self.client
                .log_message(
                    MessageType::INFO,
                    format!("Binary changes detected: {}", binary_changes.join(", ")),
                )
                .await;
        }

        self.analyze_and_publish().await;
    }

    async fn code_action(&self, params: CodeActionParams) -> Result<Option<CodeActionResponse>> {
        let mut actions: Vec<CodeActionOrCommand> = Vec::new();

        // Get workspace root for jonesy.toml path
        let workspace_root = {
            let state = self.state.read().await;
            state.workspace_root.clone()
        };

        // Filter to jonesy diagnostics only
        let jonesy_diagnostics: Vec<_> = params
            .context
            .diagnostics
            .iter()
            .filter(|d| d.source.as_deref() == Some("jonesy"))
            .collect();

        for diag in jonesy_diagnostics {
            // Extract cause info from diagnostic data
            if let Some(data) = &diag.data {
                let causes: Vec<String> = data
                    .get("causes")
                    .and_then(|v| serde_json::from_value(v.clone()).ok())
                    .unwrap_or_default();
                let function: String = data
                    .get("function")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let called_function: Option<String> = data
                    .get("called_function")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());

                // Track which causes we've added actions for (avoid duplicates)
                let mut seen_causes = std::collections::HashSet::new();

                for cause in &causes {
                    if !seen_causes.insert(cause.clone()) {
                        continue;
                    }

                    // Action 1: Allow on this line (inline comment)
                    if let Some(action) = Self::create_inline_allow_action(
                        &params.text_document.uri,
                        diag.range,
                        cause,
                        diag,
                    ) {
                        actions.push(CodeActionOrCommand::CodeAction(action));
                    }

                    // Action 2: Allow in this file (scoped rule in jonesy.toml)
                    if let Some(ref root) = workspace_root {
                        if let Some(action) = Self::create_file_allow_action(
                            &params.text_document.uri,
                            cause,
                            root,
                            diag,
                        ) {
                            actions.push(CodeActionOrCommand::CodeAction(action));
                        }

                        // Action 3: Allow in this function (scoped rule in jonesy.toml)
                        if !function.is_empty() {
                            if let Some(action) =
                                Self::create_function_allow_action(&function, cause, root, diag)
                            {
                                actions.push(CodeActionOrCommand::CodeAction(action));
                            }
                        }

                        // Action 4: Allow this cause on calls to called function
                        if let Some(ref called_fn) = called_function {
                            if let Some(action) = Self::create_called_function_allow_action(
                                called_fn, cause, root, diag,
                            ) {
                                actions.push(CodeActionOrCommand::CodeAction(action));
                            }
                        }

                        // Action 5: Allow in module (tests, benches, examples)
                        if let Some(action) = Self::create_module_allow_action(
                            &params.text_document.uri,
                            cause,
                            root,
                            diag,
                        ) {
                            actions.push(CodeActionOrCommand::CodeAction(action));
                        }

                        // Action 6: Allow in this crate (global allow)
                        if let Some(action) = Self::create_crate_allow_action(cause, root, diag) {
                            actions.push(CodeActionOrCommand::CodeAction(action));
                        }
                    }
                }

                // Action 7: Allow all panics on this line (wildcard)
                if causes.len() > 1 {
                    if let Some(action) = Self::create_inline_allow_action(
                        &params.text_document.uri,
                        diag.range,
                        "*",
                        diag,
                    ) {
                        actions.push(CodeActionOrCommand::CodeAction(action));
                    }
                }
            }
        }

        // Always add the manual analyze action
        let analyze_action = CodeAction {
            title: "Run Jonesy Panic Analysis".to_string(),
            kind: Some(CodeActionKind::SOURCE),
            diagnostics: None,
            edit: None,
            command: Some(Command {
                title: "Run Jonesy Panic Analysis".to_string(),
                command: "jonesy.analyze".to_string(),
                arguments: None,
            }),
            is_preferred: Some(false),
            disabled: None,
            data: None,
        };
        actions.push(CodeActionOrCommand::CodeAction(analyze_action));

        Ok(Some(actions))
    }

    async fn execute_command(
        &self,
        params: ExecuteCommandParams,
    ) -> Result<Option<serde_json::Value>> {
        if params.command == "jonesy.analyze" {
            let success = self.analyze_and_publish().await;
            Ok(Some(serde_json::json!({"success": success})))
        } else {
            Ok(None)
        }
    }
}

/// Run analysis from a spawned task (file watcher callback).
///
/// This is a standalone function that can be called from background tasks
/// without needing a reference to the full JonesyLspServer.
///
/// Uses caching in `target/jonesy/` to avoid re-analyzing unchanged targets.
async fn run_analysis_task(
    client: &Client,
    state: &Arc<RwLock<ServerState>>,
    analysis_lock: &Arc<Mutex<()>>,
) {
    use crate::analysis_cache::{AnalysisCache, build_workspace_state};

    // Serialize analysis runs
    let _guard = analysis_lock.lock().await;

    // Get workspace root
    let workspace_root = {
        let state = state.read().await;
        state.workspace_root.clone()
    };

    let Some(workspace_root) = workspace_root else {
        return;
    };

    let target_dir = workspace_root.join("target").to_string_lossy().to_string();

    // Load analysis cache
    let mut cache = {
        let root = workspace_root.clone();
        tokio::task::spawn_blocking(move || AnalysisCache::load(&root))
            .await
            .unwrap_or_default()
    };

    // Build current workspace state and detect changes
    let current_workspace_state = {
        let root = workspace_root.clone();
        tokio::task::spawn_blocking(move || build_workspace_state(&root))
            .await
            .unwrap_or_default()
    };

    let workspace_changes = cache.detect_workspace_changes(&current_workspace_state);
    let mut force_full_analysis = workspace_changes.needs_full_reanalysis();

    // Check if config files (jonesy.toml, Cargo.toml) have changed.
    // Config changes affect all targets, so force a full re-analysis.
    // Snapshot current hashes NOW so we persist exactly what we analyzed against,
    // even if the file changes again during the analysis run.
    let config_files = find_config_files(&workspace_root);
    let mut config_snapshots: Vec<(PathBuf, u64)> = Vec::new();
    for config_path in &config_files {
        let config_deleted = !config_path.exists() && cache.has_config(config_path);
        if config_deleted || (config_path.exists() && cache.config_changed(config_path)) {
            client
                .log_message(
                    MessageType::INFO,
                    format!(
                        "Config changed: {}",
                        config_path
                            .file_name()
                            .unwrap_or_default()
                            .to_string_lossy()
                    ),
                )
                .await;
            force_full_analysis = true;
            if config_deleted {
                cache.remove_config(config_path);
            } else {
                // Snapshot the hash now, before analysis starts
                let hash = crate::analysis_cache::hash_file_content(config_path).unwrap_or(0);
                config_snapshots.push((config_path.clone(), hash));
            }
        }
    }

    if workspace_changes.has_changes() {
        let change_summary = format_change_summary(&workspace_changes, &current_workspace_state);
        client.log_message(MessageType::INFO, change_summary).await;
    }

    // Get targets
    let targets = {
        let root = workspace_root.clone();
        tokio::task::spawn_blocking(move || find_workspace_binaries(&root))
            .await
            .ok()
            .and_then(|r| r.ok())
            .unwrap_or_default()
    };

    if targets.is_empty() {
        return;
    }

    // Build ProjectContext once for the workspace
    let project_context = {
        let root = workspace_root.clone();
        tokio::task::spawn_blocking(move || ProjectContext::from_project_root(&root))
            .await
            .unwrap_or_else(|e| Err(format!("Failed to build project context: {e}")))
    };
    let project_context = match project_context {
        Ok(ctx) => Arc::new(ctx),
        Err(e) => {
            client
                .log_message(MessageType::ERROR, format!("ProjectContext error: {e}"))
                .await;
            return;
        }
    };

    // Track diagnostics
    let mut points_by_file: HashMap<Url, Vec<CrateCodePoint>> = HashMap::new();
    let mut seen: HashSet<(String, u32, u32)> = HashSet::new();
    let mut analyzed_count = 0usize;
    let mut skipped_count = 0usize;

    // Analyze each target (skip unchanged ones unless force_full_analysis or workspace changes affect it)
    for target in &targets {
        // Check if target needs re-analysis
        let needs_analysis = force_full_analysis
            || cache.target_needs_analysis(target)
            || workspace_changes.affects_target(target);

        if !needs_analysis {
            skipped_count += 1;
            continue;
        }

        analyzed_count += 1;
        let analysis_result = {
            let target = target.clone();
            let project_context = Arc::clone(&project_context);
            tokio::task::spawn_blocking(move || analyze_single_target(&target, &project_context))
                .await
        };

        if let Ok(Ok(points)) = analysis_result {
            let point_count = points.len();
            let new_points: Vec<_> = points
                .into_iter()
                .filter(|p| {
                    let key = (p.file.clone(), p.line, p.column.unwrap_or(0));
                    seen.insert(key)
                })
                .collect();

            // Update cache for this target
            cache.update_target(target, point_count);

            // Group by file
            for point in new_points {
                if point.file.starts_with(&target_dir) {
                    continue;
                }

                let raw_path = PathBuf::from(&point.file);
                let file_path = if raw_path.is_absolute() {
                    raw_path
                } else {
                    workspace_root.join(raw_path)
                };

                if let Ok(uri) = Url::from_file_path(&file_path) {
                    points_by_file.entry(uri).or_default().push(point);
                }
            }
        }
    }

    // Persist the config hashes snapshotted BEFORE analysis started.
    // Using the pre-analysis snapshot (not current on-disk content) ensures that
    // if the config changed again during the run, the next watcher event will
    // still detect that change and re-analyze.
    for (config_path, hash) in &config_snapshots {
        cache.update_config_with_hash(config_path, *hash);
    }

    // Update workspace state in cache and save
    cache.update_workspace(current_workspace_state);
    cache.prune_stale_targets();
    let save_result = {
        let root = workspace_root.clone();
        tokio::task::spawn_blocking(move || cache.save(&root)).await
    };
    if let Ok(Err(e)) = save_result {
        client
            .log_message(MessageType::WARNING, format!("Failed to save cache: {}", e))
            .await;
    }

    // Log analysis summary
    if skipped_count > 0 {
        client
            .log_message(
                MessageType::LOG,
                format!(
                    "Analyzed {} targets, skipped {} unchanged",
                    analyzed_count, skipped_count
                ),
            )
            .await;
    }

    // Update state and publish diagnostics
    // When some targets were skipped, merge with existing state to preserve their diagnostics
    let old_files: HashSet<_>;
    let new_files: HashSet<_> = points_by_file.keys().cloned().collect();

    {
        let mut state = state.write().await;
        old_files = state.panic_points.keys().cloned().collect();

        if skipped_count > 0 {
            // Merge: update analyzed files, keep diagnostics from skipped targets
            for (uri, points) in points_by_file.clone() {
                state.panic_points.insert(uri, points);
            }
        } else {
            // Full analysis: replace entirely
            state.panic_points = points_by_file.clone();
        }
    }

    // Publish diagnostics for files with panic points
    for (uri, points) in &points_by_file {
        let diagnostics: Vec<Diagnostic> = points
            .iter()
            .map(JonesyLspServer::code_point_to_diagnostic)
            .collect();
        client
            .publish_diagnostics(uri.clone(), diagnostics, None)
            .await;
    }

    // Clear diagnostics for files that no longer have panic points
    // Only do this when all targets were analyzed (no skipped targets)
    if skipped_count == 0 {
        for uri in old_files.difference(&new_files) {
            client.publish_diagnostics(uri.clone(), vec![], None).await;
        }
    }

    // Report deduplicated totals from state (includes merged results from skipped targets)
    let (total_files, published_points) = {
        let state = state.read().await;
        (
            state.panic_points.len(),
            state
                .panic_points
                .values()
                .map(|points| points.len())
                .sum::<usize>(),
        )
    };

    client
        .log_message(
            MessageType::INFO,
            format!(
                "Analysis complete: {} panic points in {} files",
                published_points, total_files
            ),
        )
        .await;
}

/// Info about workspace structure (for logging before analysis)
struct WorkspaceInfo {
    members: Vec<String>,
    targets: Vec<String>,
}

// ============================================================================
// Pure helper functions - extracted for unit testing
// These can be used in analyze_and_publish/run_analysis_task in the future
// to reduce code duplication. For now they're tested independently.
// ============================================================================

/// Format a workspace/package change summary for logging.
/// Single-package crates get "Package changes: ..." (no members count),
/// workspaces get "Workspace changes: ... members, ...".
fn format_change_summary(
    changes: &crate::analysis_cache::WorkspaceChanges,
    workspace_state: &crate::analysis_cache::WorkspaceState,
) -> String {
    let (members, binaries, libraries) = changes.change_counts();
    if workspace_state.is_single_package() {
        format!(
            "Package changes: {} binaries, {} library affected",
            binaries, libraries,
        )
    } else {
        format!(
            "Workspace changes: {} members, {} binaries, {} libraries affected",
            members, binaries, libraries,
        )
    }
}

/// Deduplicate code points by (file, line, column).
///
/// Points are considered duplicates if they have the same file path, line number,
/// and column (or both have no column). This handles the case where multiple
/// targets report the same panic point from shared code.
#[cfg(test)]
fn deduplicate_code_points(points: Vec<CrateCodePoint>) -> Vec<CrateCodePoint> {
    let mut seen: HashSet<(String, u32, u32)> = HashSet::new();
    points
        .into_iter()
        .filter(|p| {
            let key = (p.file.clone(), p.line, p.column.unwrap_or(0));
            seen.insert(key)
        })
        .collect()
}

/// Group code points by file URI, filtering out paths in target/ directory.
///
/// Returns a HashMap where keys are file URIs and values are the code points
/// found in that file. Points with paths inside the target directory are excluded.
#[cfg(test)]
fn group_points_by_uri(
    points: Vec<CrateCodePoint>,
    workspace_root: &Path,
    target_dir: &str,
) -> HashMap<Url, Vec<CrateCodePoint>> {
    let mut points_by_file: HashMap<Url, Vec<CrateCodePoint>> = HashMap::new();

    for point in points {
        // Skip files in target/ directory
        if point.file.starts_with(target_dir) {
            continue;
        }

        let raw_path = PathBuf::from(&point.file);
        let file_path = if raw_path.is_absolute() {
            raw_path
        } else {
            workspace_root.join(raw_path)
        };

        if let Ok(uri) = Url::from_file_path(&file_path) {
            points_by_file.entry(uri).or_default().push(point);
        }
    }

    points_by_file
}

/// Result of analyzing workspace targets.
#[cfg(test)]
#[derive(Debug, Default)]
struct AnalysisResult {
    /// All code points found, deduplicated across targets
    points: Vec<CrateCodePoint>,
    /// Total number of panic points found (before deduplication)
    total_count: usize,
    /// Number of targets that were successfully analyzed
    analyzed_count: usize,
    /// Number of targets that failed or were skipped
    skipped_count: usize,
}

/// Analyze all targets in a workspace and return deduplicated results.
///
/// This is the core analysis logic extracted from `analyze_and_publish` and
/// `run_analysis_task` for easier testing. It runs analysis on each target
/// synchronously and returns all unique panic points.
#[cfg(test)]
fn analyze_workspace_targets(
    targets: &[PathBuf],
    project_context: &ProjectContext,
) -> AnalysisResult {
    let mut result = AnalysisResult::default();
    let mut seen: HashSet<(String, u32, u32)> = HashSet::new();

    for target in targets {
        match analyze_single_target(target, project_context) {
            Ok(points) => {
                result.analyzed_count += 1;
                let point_count = points.len();
                result.total_count += point_count;

                // Filter to new points only (dedup across targets)
                let new_points: Vec<_> = points
                    .into_iter()
                    .filter(|p| {
                        let key = (p.file.clone(), p.line, p.column.unwrap_or(0));
                        seen.insert(key)
                    })
                    .collect();

                result.points.extend(new_points);
            }
            Err(_) => {
                result.skipped_count += 1;
            }
        }
    }

    result
}

/// Quickly discover workspace structure without running full analysis
fn discover_workspace(workspace_root: &Path) -> Option<WorkspaceInfo> {
    let cargo_toml = workspace_root.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_toml).ok()?;
    let manifest = cargo_toml::Manifest::from_slice(content.as_bytes()).ok()?;

    let mut members = Vec::new();
    let mut targets = Vec::new();

    // Get workspace members
    if let Some(workspace) = &manifest.workspace {
        for member in &workspace.members {
            if member.contains('*') {
                // Expand glob
                for path in expand_workspace_glob(workspace_root, member) {
                    if let Some(name) = path.file_name() {
                        members.push(name.to_string_lossy().to_string());
                    }
                }
            } else {
                members.push(member.clone());
            }
        }
    } else if let Some(pkg) = &manifest.package {
        members.push(pkg.name.clone());
    }

    // Get targets
    if let Ok(found_targets) = find_workspace_binaries(workspace_root) {
        for target in found_targets {
            if let Some(name) = target.file_name() {
                targets.push(name.to_string_lossy().to_string());
            }
        }
    }

    Some(WorkspaceInfo { members, targets })
}

/// Analyze a single target (binary or library) and return panic points.
/// This reuses the same analysis functions as the CLI for consistency.
fn analyze_single_target(
    target_path: &Path,
    project_context: &ProjectContext,
) -> std::result::Result<Vec<CrateCodePoint>, String> {
    use crate::analysis::{analyze_archive, analyze_binary_target};
    use crate::args::OutputFormat;
    use crate::config::Config;
    use crate::sym::SymbolTable;
    use goblin::mach::Mach::{Binary, Fat};
    use goblin::mach::SingleArch;
    use goblin::mach::constants::cputype::{CPU_TYPE_ARM64, CPU_TYPE_X86_64};

    let binary_buffer =
        std::fs::read(target_path).map_err(|e| format!("Failed to read target: {}", e))?;

    let symbols =
        SymbolTable::from(&binary_buffer).map_err(|e| format!("Failed to read symbols: {}", e))?;

    let config = Config::load_for_project(Path::new(project_context.project_root()), None)
        .unwrap_or_else(|_| Config::with_defaults());

    // Use quiet output format (no progress display in LSP)
    let output = OutputFormat::quiet();

    match &symbols {
        SymbolTable::MachO(Binary(_)) => {
            let result = analyze_binary_target(
                &symbols,
                &binary_buffer,
                target_path,
                false, // show_timings
                &config,
                &output,
                project_context,
            )?;
            Ok(result.code_points)
        }
        SymbolTable::MachO(Fat(fat)) => {
            // Fat binary - find native architecture slice and analyze it
            // Prefer slice matching the current host architecture
            let preferred_cputype = match std::env::consts::ARCH {
                "aarch64" => Some(CPU_TYPE_ARM64),
                "x86_64" => Some(CPU_TYPE_X86_64),
                _ => None,
            };

            // Find host-native slice, or fall back to first available
            let mut selected_macho = None;
            for entry in fat.into_iter() {
                match entry {
                    Ok(SingleArch::MachO(macho)) => {
                        if preferred_cputype
                            .map(|cpu| macho.header.cputype == cpu)
                            .unwrap_or(false)
                        {
                            selected_macho = Some(macho);
                            break;
                        }
                        // Keep first as fallback
                        if selected_macho.is_none() {
                            selected_macho = Some(macho);
                        }
                    }
                    Ok(SingleArch::Archive(_)) => continue, // Skip archive slices
                    Err(_) => continue,
                }
            }

            match selected_macho {
                Some(_macho) => {
                    // Fat binary: re-parse buffer to get SymbolTable for selected arch
                    let fat_symbols = SymbolTable::from(&binary_buffer)
                        .map_err(|e| format!("Failed to parse fat binary: {e}"))?;
                    let result = analyze_binary_target(
                        &fat_symbols,
                        &binary_buffer,
                        target_path,
                        false, // show_timings
                        &config,
                        &output,
                        project_context,
                    )?;
                    Ok(result.code_points)
                }
                None => Err("Fat binary contains no analyzable MachO slices".to_string()),
            }
        }
        SymbolTable::Elf(_) => {
            let result = analyze_binary_target(
                &symbols,
                &binary_buffer,
                target_path,
                false, // show_timings
                &config,
                &output,
                project_context,
            )?;
            Ok(result.code_points)
        }
        SymbolTable::Archive(archive) => {
            let result = analyze_archive(
                archive,
                &binary_buffer,
                target_path,
                false, // show_timings
                &config,
                &output,
                project_context,
            )?;
            Ok(result.code_points)
        }
    }
}

/// Find all config files that affect jonesy analysis.
/// Returns paths to jonesy.toml and all Cargo.toml files (workspace + members).
fn find_config_files(workspace_root: &Path) -> Vec<PathBuf> {
    let mut config_files = Vec::new();

    // Always watch jonesy.toml if it exists (or might be created)
    config_files.push(workspace_root.join("jonesy.toml"));

    // Watch workspace Cargo.toml
    let cargo_toml = workspace_root.join("Cargo.toml");
    if !cargo_toml.exists() {
        return config_files;
    }
    config_files.push(cargo_toml.clone());

    // Parse manifest to find workspace members
    let Ok(content) = std::fs::read_to_string(&cargo_toml) else {
        return config_files;
    };
    let Ok(manifest) = cargo_toml::Manifest::from_slice(content.as_bytes()) else {
        return config_files;
    };

    // Add Cargo.toml for each workspace member
    if let Some(workspace) = &manifest.workspace {
        for member in &workspace.members {
            let member_paths: Vec<PathBuf> = if member.contains('*') {
                expand_workspace_glob(workspace_root, member)
            } else {
                vec![workspace_root.join(member)]
            };

            for member_path in member_paths {
                let member_cargo = member_path.join("Cargo.toml");
                if member_cargo.exists() {
                    config_files.push(member_cargo);
                }
            }
        }
    }

    // Deduplicate paths (can occur with overlapping glob patterns)
    config_files.sort();
    config_files.dedup();
    config_files
}

/// Find binary and library files in the workspace
fn find_workspace_binaries(workspace_root: &Path) -> std::result::Result<Vec<PathBuf>, String> {
    let target_debug = workspace_root.join("target/debug");
    if !target_debug.exists() {
        return Ok(Vec::new());
    }

    // Look for Cargo.toml to find binary names
    let cargo_toml = workspace_root.join("Cargo.toml");
    if !cargo_toml.exists() {
        return Ok(Vec::new());
    }

    let content = std::fs::read_to_string(&cargo_toml)
        .map_err(|e| format!("Failed to read Cargo.toml: {}", e))?;

    let manifest = cargo_toml::Manifest::from_slice(content.as_bytes())
        .map_err(|e| format!("Failed to parse Cargo.toml: {}", e))?;

    let mut targets = Vec::new();

    // Check for package binaries and libraries (non-virtual workspace or single crate)
    if manifest.package.is_some() {
        // Complete the manifest to discover implicit targets (src/main.rs, src/lib.rs, etc.)
        let mut completed_manifest = manifest.clone();
        completed_manifest
            .complete_from_path_and_workspace::<toml::Value>(
                &cargo_toml,
                None::<(&cargo_toml::Manifest<toml::Value>, &std::path::Path)>,
            )
            .map_err(|e| {
                format!(
                    "Failed to complete manifest {}: {}",
                    cargo_toml.display(),
                    e
                )
            })?;
        collect_binaries_from_manifest(&completed_manifest, &target_debug, &mut targets);
    }

    // Check for workspace members
    if let Some(workspace) = &manifest.workspace {
        for member in &workspace.members {
            let member_paths: Vec<PathBuf> = if member.contains('*') {
                // Expand glob patterns like "crates/*"
                expand_workspace_glob(workspace_root, member)
            } else {
                vec![workspace_root.join(member)]
            };

            for member_path in member_paths {
                let member_cargo = member_path.join("Cargo.toml");
                let member_content = match std::fs::read_to_string(&member_cargo) {
                    Ok(content) => content,
                    Err(e) => {
                        eprintln!("Warning: Failed to read {}: {}", member_cargo.display(), e);
                        continue;
                    }
                };
                let mut member_manifest =
                    match cargo_toml::Manifest::from_slice(member_content.as_bytes()) {
                        Ok(m) => m,
                        Err(e) => {
                            eprintln!("Warning: Failed to parse {}: {}", member_cargo.display(), e);
                            continue;
                        }
                    };
                // Complete the manifest to discover implicit targets
                // Continue on error - don't let one bad member break the whole workspace
                if let Err(e) = member_manifest.complete_from_path_and_workspace(
                    &member_cargo,
                    Some((&manifest, cargo_toml.as_path())),
                ) {
                    eprintln!(
                        "Warning: Failed to complete {}: {}",
                        member_cargo.display(),
                        e
                    );
                    continue;
                }
                collect_binaries_from_manifest(&member_manifest, &target_debug, &mut targets);
            }
        }
    }

    Ok(targets)
}

/// Collect binaries from a completed manifest into the targets vector
fn collect_binaries_from_manifest(
    manifest: &cargo_toml::Manifest,
    target_debug: &Path,
    targets: &mut Vec<PathBuf>,
) {
    let Some(pkg) = &manifest.package else {
        return;
    };
    let pkg_name = &pkg.name;

    // Check for [[bin]] targets (populated by complete_from_path_and_workspace)
    // No fallback probe needed - complete_from_path_and_workspace populates bin if there's a binary
    for bin in &manifest.bin {
        let bin_name = bin.name.as_deref().unwrap_or(pkg_name);
        if let Some(bin_path) = find_binary(target_debug, bin_name) {
            if !targets.contains(&bin_path) {
                targets.push(bin_path);
            }
        }
    }

    // Check for library target
    if manifest.lib.is_some() {
        let lib_name = manifest
            .lib
            .as_ref()
            .and_then(|lib| lib.name.as_deref())
            .unwrap_or(pkg_name);
        if let Some(lib_path) = find_library(target_debug, lib_name) {
            if !targets.contains(&lib_path) {
                targets.push(lib_path);
            }
        }
    }
}

/// Expand a workspace glob pattern like "crates/*" or "crates/**" to actual paths
fn expand_workspace_glob(workspace_root: &Path, pattern: &str) -> Vec<PathBuf> {
    // Build full glob pattern rooted at workspace
    let full_pattern = workspace_root.join(pattern);
    let pattern_str = full_pattern.to_string_lossy();

    // Use glob to expand the pattern
    match glob::glob(&pattern_str) {
        Ok(paths) => paths
            .filter_map(|p| p.ok())
            .filter(|p| p.is_dir() && p.join("Cargo.toml").exists())
            .collect(),
        Err(_) => Vec::new(),
    }
}

/// Run the LSP server
pub async fn run_lsp_server() {
    let stdin = tokio::io::stdin();
    let stdout = tokio::io::stdout();

    let (service, socket) = LspService::new(JonesyLspServer::new);
    Server::new(stdin, stdout, socket).serve(service).await;
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Mutex;

    /// Mutex to serialize tests that build and inspect workspace_test artifacts.
    /// Without this, parallel tests can trigger concurrent cargo builds that
    /// temporarily remove artifacts during rebuilds (especially under coverage).
    static WORKSPACE_TEST_LOCK: Mutex<()> = Mutex::new(());

    /// Find the workspace root by looking for Cargo.toml with [workspace]
    fn find_workspace_root() -> PathBuf {
        let mut current = std::env::current_dir().unwrap();
        loop {
            let cargo_toml = current.join("Cargo.toml");
            if cargo_toml.exists() {
                let content = std::fs::read_to_string(&cargo_toml).unwrap_or_default();
                if content.contains("[workspace]") {
                    return current;
                }
            }
            if !current.pop() {
                panic!("Could not find workspace root");
            }
        }
    }

    /// Build workspace_test, holding WORKSPACE_TEST_LOCK to prevent parallel
    /// tests from interfering with each other's build artifacts.
    fn build_workspace_test(workspace_test_dir: &Path) -> std::sync::MutexGuard<'static, ()> {
        let guard = WORKSPACE_TEST_LOCK.lock().unwrap();

        let status = std::process::Command::new("cargo")
            .arg("build")
            .current_dir(workspace_test_dir)
            .status()
            .expect("Failed to build workspace_test");
        assert!(status.success(), "Failed to build workspace_test");

        // Verify all expected artifacts exist (CI builds take ~2s, wait up to 4s)
        let target_debug = workspace_test_dir.join("target/debug");
        let expected = [
            "crate_a",
            "crate_b_bin",
            "libcrate_b_lib.rlib",
            "libcrate_c.rlib",
        ];

        for _ in 0..8 {
            let all_exist = expected.iter().all(|name| target_debug.join(name).exists());
            if all_exist {
                return guard;
            }
            std::thread::sleep(std::time::Duration::from_millis(500));
        }

        // Final check with diagnostic output
        let missing: Vec<_> = expected
            .iter()
            .filter(|name| !target_debug.join(name).exists())
            .collect();
        if !missing.is_empty() {
            panic!(
                "Build artifacts not found after waiting: {:?}. target/debug contents: {:?}",
                missing,
                std::fs::read_dir(&target_debug)
                    .map(|entries| entries
                        .filter_map(|e| e.ok())
                        .map(|e| e.file_name().to_string_lossy().to_string())
                        .collect::<Vec<_>>())
                    .unwrap_or_default()
            );
        }
        guard
    }

    #[test]
    fn test_find_workspace_binaries_with_custom_lib_name() {
        // Use workspace_test example which has a crate with custom [lib] name
        let workspace_root = find_workspace_root();
        let workspace_test_dir = workspace_root.join("examples").join("workspace_test");

        // Hold the lock through assertions so no parallel test can rebuild artifacts
        let _guard = build_workspace_test(&workspace_test_dir);

        // Find targets
        let targets =
            find_workspace_binaries(&workspace_test_dir).expect("Should find workspace binaries");

        // Extract just the file names for easier comparison
        let target_names: Vec<String> = targets
            .iter()
            .filter_map(|p| p.file_name())
            .map(|n| n.to_string_lossy().to_string())
            .collect();

        // Expected targets:
        // - crate_a (binary from crate_a)
        // - crate_b_bin (binary from crate_b, explicit [[bin]] name)
        // - libcrate_b_lib.rlib (library from crate_b, [lib] name = "crate_b_lib")
        // - libcrate_c.rlib (library-only crate)

        assert!(
            target_names.iter().any(|n| n == "crate_a"),
            "Should find crate_a binary. Found: {:?}",
            target_names
        );
        assert!(
            target_names.iter().any(|n| n == "crate_b_bin"),
            "Should find crate_b_bin binary. Found: {:?}",
            target_names
        );
        assert!(
            target_names.iter().any(|n| n == "libcrate_b_lib.rlib"),
            "Should find libcrate_b_lib.rlib (custom [lib] name). Found: {:?}",
            target_names
        );
        assert!(
            target_names.iter().any(|n| n == "libcrate_c.rlib"),
            "Should find libcrate_c.rlib (library-only crate). Found: {:?}",
            target_names
        );
    }

    #[test]
    fn test_lsp_analysis_matches_cli() {
        use std::collections::HashSet;

        // Use workspace_test example
        let workspace_root = find_workspace_root();
        let workspace_test_dir = workspace_root.join("examples").join("workspace_test");

        // Hold the lock through the entire test so no parallel test can rebuild artifacts
        let _guard = build_workspace_test(&workspace_test_dir);

        // Run CLI and capture panic points
        let cli_output = std::process::Command::new(workspace_root.join("target/debug/jonesy"))
            .arg("--quiet")
            .current_dir(&workspace_test_dir)
            .output()
            .expect("Failed to run jonesy CLI");

        let cli_stdout = String::from_utf8_lossy(&cli_output.stdout);

        // Parse CLI output for panic points (top-level lines starting with " --> ")
        // Skip nested points (lines in the call tree that are indented)
        let cli_points: HashSet<(String, u32)> = cli_stdout
            .lines()
            .filter(|line| line.starts_with(" --> ")) // Only top-level points
            .filter_map(|line| {
                // Parse " --> path/to/file.rs:123:45"
                let arrow_pos = line.find(" --> ")?;
                let location = &line[arrow_pos + 5..];
                let parts: Vec<&str> = location.split(':').collect();
                if parts.len() >= 2 {
                    let file = parts[0].trim();
                    let line_num: u32 = parts[1].parse().ok()?;
                    // Normalize path - extract just the relative part
                    let file = file
                        .rsplit("workspace_test/")
                        .next()
                        .unwrap_or(file)
                        .to_string();
                    Some((file, line_num))
                } else {
                    None
                }
            })
            .collect();

        // Run LSP-style analysis using the same functions
        let targets =
            find_workspace_binaries(&workspace_test_dir).expect("Should find workspace binaries");

        let project_context = ProjectContext::from_project_root(&workspace_test_dir)
            .expect("Should build project context");

        let mut lsp_points: HashSet<(String, u32)> = HashSet::new();

        for target in &targets {
            let result = analyze_single_target(target, &project_context);
            if let Ok(points) = result {
                for point in points {
                    // Normalize path
                    let file = point
                        .file
                        .rsplit("workspace_test/")
                        .next()
                        .unwrap_or(&point.file)
                        .to_string();
                    lsp_points.insert((file, point.line));
                }
            }
        }

        // Compare: LSP should find at least as many points as CLI
        let missing_in_lsp: Vec<_> = cli_points.difference(&lsp_points).collect();
        let extra_in_lsp: Vec<_> = lsp_points.difference(&cli_points).collect();

        if !missing_in_lsp.is_empty() {
            eprintln!("CLI found but LSP missed:");
            for (file, line) in &missing_in_lsp {
                eprintln!("  {}:{}", file, line);
            }
        }

        if !extra_in_lsp.is_empty() {
            eprintln!("LSP found but CLI missed:");
            for (file, line) in &extra_in_lsp {
                eprintln!("  {}:{}", file, line);
            }
        }

        // The LSP should find all points the CLI finds
        assert!(
            missing_in_lsp.is_empty(),
            "LSP analysis should find all panic points that CLI finds. \
             Missing {} points, extra {} points. CLI found {}, LSP found {}",
            missing_in_lsp.len(),
            extra_in_lsp.len(),
            cli_points.len(),
            lsp_points.len()
        );
    }

    #[test]
    fn test_create_inline_allow_action() {
        let uri = Url::parse("file:///tmp/test.rs").unwrap();
        let range = Range {
            start: Position {
                line: 10,
                character: 5,
            },
            end: Position {
                line: 10,
                character: 15,
            },
        };
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };

        // Test specific cause
        let action =
            JonesyLspServer::create_inline_allow_action(&uri, range, "unwrap", &diagnostic)
                .unwrap();
        assert_eq!(action.title, "Allow 'unwrap' on this line");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
        assert!(action.is_preferred.unwrap_or(false)); // Specific cause is preferred

        // Verify the edit inserts the comment
        let edit = action.edit.unwrap();
        let changes = edit.changes.unwrap();
        let edits = changes.get(&uri).unwrap();
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, " // jonesy:allow(unwrap)");

        // Test wildcard
        let action =
            JonesyLspServer::create_inline_allow_action(&uri, range, "*", &diagnostic).unwrap();
        assert_eq!(action.title, "Allow all panics on this line");
        assert!(!action.is_preferred.unwrap_or(true)); // Wildcard is not preferred
    }

    #[test]
    fn test_create_inline_allow_action_merges_causes() {
        use std::io::Write;

        // Create a temp file with an existing inline allow
        let dir = tempfile::tempdir().unwrap();
        let file_path = dir.path().join("test.rs");
        let mut f = std::fs::File::create(&file_path).unwrap();
        writeln!(f, "fn main() {{").unwrap();
        writeln!(f, "    let x = foo(); // jonesy:allow(bounds)").unwrap();
        writeln!(f, "}}").unwrap();

        let uri = Url::from_file_path(&file_path).unwrap();
        let range = Range {
            start: Position {
                line: 1, // the line with the existing allow
                character: 4,
            },
            end: Position {
                line: 1,
                character: 10,
            },
        };
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };

        // Adding "overflow" should merge with existing "bounds"
        let action =
            JonesyLspServer::create_inline_allow_action(&uri, range, "overflow", &diagnostic)
                .unwrap();
        let edit = action.edit.unwrap();
        let changes = edit.changes.unwrap();
        let edits = changes.get(&uri).unwrap();
        assert_eq!(edits.len(), 1);
        assert_eq!(edits[0].new_text, "// jonesy:allow(bounds, overflow)");

        // Adding "bounds" again should not duplicate
        let action =
            JonesyLspServer::create_inline_allow_action(&uri, range, "bounds", &diagnostic)
                .unwrap();
        let edit = action.edit.unwrap();
        let changes = edit.changes.unwrap();
        let edits = changes.get(&uri).unwrap();
        assert_eq!(edits[0].new_text, "// jonesy:allow(bounds)");
    }

    #[test]
    fn test_create_file_allow_action() {
        let uri = Url::parse("file:///workspace/src/main.rs").unwrap();
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");

        let action =
            JonesyLspServer::create_file_allow_action(&uri, "unwrap", &workspace_root, &diagnostic)
                .unwrap();

        assert_eq!(action.title, "Allow 'unwrap' in main.rs");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));

        // Verify the edit targets jonesy.toml
        let edit = action.edit.unwrap();
        let doc_changes = edit.document_changes.unwrap();
        match doc_changes {
            DocumentChanges::Operations(ops) => {
                // Should have at least a text edit (possibly a create file too)
                assert!(!ops.is_empty());
            }
            _ => panic!("Expected Operations"),
        }
    }

    #[test]
    fn test_create_function_allow_action() {
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");

        let action = JonesyLspServer::create_function_allow_action(
            "my_crate::module::parse_config",
            "unwrap",
            &workspace_root,
            &diagnostic,
        )
        .unwrap();

        // Uses full function path for precise matching
        assert_eq!(action.title, "Allow 'unwrap' in this function");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
    }

    #[test]
    fn test_create_called_function_allow_action() {
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");

        let action = JonesyLspServer::create_called_function_allow_action(
            "my_crate::config::Config::parse",
            "expect",
            &workspace_root,
            &diagnostic,
        )
        .unwrap();

        assert_eq!(
            action.title,
            "Allow 'expect' on calls to 'my_crate::config::Config::parse()'"
        );
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));

        // Verify the generated config rule uses the specific cause, not wildcard
        let edit = action.edit.unwrap();
        let changes = edit.document_changes.unwrap();
        if let DocumentChanges::Operations(ops) = changes {
            let has_correct_rule = ops.iter().any(|op| {
                if let DocumentChangeOperation::Edit(text_edit) = op {
                    text_edit.edits.iter().any(|e| {
                        if let OneOf::Left(te) = e {
                            te.new_text
                                .contains("function = \"my_crate::config::Config::parse\"")
                                && te.new_text.contains("allow = [\"expect\"]")
                        } else {
                            false
                        }
                    })
                } else {
                    false
                }
            });
            assert!(
                has_correct_rule,
                "Rule should use specific cause 'expect', not wildcard"
            );
        } else {
            panic!("Expected Operations variant");
        }
    }

    #[test]
    fn test_create_module_allow_action_tests() {
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");
        let uri = Url::parse("file:///workspace/tests/integration.rs").unwrap();

        let action = JonesyLspServer::create_module_allow_action(
            &uri,
            "unwrap",
            &workspace_root,
            &diagnostic,
        )
        .unwrap();

        assert_eq!(action.title, "Allow 'unwrap' in tests");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
    }

    #[test]
    fn test_create_module_allow_action_benches() {
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");
        let uri = Url::parse("file:///workspace/benches/bench.rs").unwrap();

        let action = JonesyLspServer::create_module_allow_action(
            &uri,
            "panic",
            &workspace_root,
            &diagnostic,
        )
        .unwrap();

        assert_eq!(action.title, "Allow 'panic' in benches");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
    }

    #[test]
    fn test_create_module_allow_action_none_for_src() {
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");
        let uri = Url::parse("file:///workspace/src/main.rs").unwrap();

        // Should return None for regular src files
        let action = JonesyLspServer::create_module_allow_action(
            &uri,
            "unwrap",
            &workspace_root,
            &diagnostic,
        );

        assert!(action.is_none());
    }

    #[test]
    fn test_create_crate_allow_action() {
        let range = Range::default();
        let diagnostic = Diagnostic {
            range,
            severity: Some(DiagnosticSeverity::WARNING),
            source: Some("jonesy".to_string()),
            message: "test".to_string(),
            ..Default::default()
        };
        let workspace_root = PathBuf::from("/workspace");

        let action =
            JonesyLspServer::create_crate_allow_action("unwrap", &workspace_root, &diagnostic)
                .unwrap();

        assert_eq!(action.title, "Allow 'unwrap' in this crate");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
    }

    #[test]
    fn test_find_config_files() {
        use std::collections::HashSet;

        // Use workspace_test example which has multiple workspace members
        let workspace_root = find_workspace_root();
        let workspace_test_dir = workspace_root.join("examples").join("workspace_test");

        let config_files = find_config_files(&workspace_test_dir);

        // Collect unique full paths to verify no duplicates
        let unique_paths: HashSet<String> = config_files
            .iter()
            .map(|p| p.to_string_lossy().to_string())
            .collect();

        // Verify no duplicates (set size should equal vec size)
        assert_eq!(
            config_files.len(),
            unique_paths.len(),
            "Config files should not contain duplicates. Found {} paths but {} unique.",
            config_files.len(),
            unique_paths.len()
        );

        // Should always include jonesy.toml (even if it doesn't exist)
        assert!(
            config_files.iter().any(|p| p.ends_with("jonesy.toml")),
            "Should include jonesy.toml path. Found: {:?}",
            config_files
        );

        // Should include workspace Cargo.toml
        assert!(
            config_files.iter().any(|p| {
                p.parent()
                    .map(|parent| parent.ends_with("workspace_test"))
                    .unwrap_or(false)
                    && p.ends_with("Cargo.toml")
            }),
            "Should include workspace Cargo.toml. Found: {:?}",
            config_files
        );

        // Should include each member's Cargo.toml
        for member in ["crate_a", "crate_b", "crate_c"] {
            assert!(
                config_files.iter().any(|p| {
                    p.parent()
                        .map(|parent| parent.ends_with(member))
                        .unwrap_or(false)
                        && p.ends_with("Cargo.toml")
                }),
                "Should include {}/Cargo.toml. Found: {:?}",
                member,
                config_files
            );
        }

        // Total should be exactly 5: jonesy.toml + workspace Cargo.toml + 3 members
        assert_eq!(
            config_files.len(),
            5,
            "Should find exactly 5 config files. Found: {:?}",
            config_files
        );
    }

    // ========================================================================
    // Unit tests for pure helper functions
    // ========================================================================

    fn make_code_point(file: &str, line: u32, column: Option<u32>) -> CrateCodePoint {
        CrateCodePoint {
            file: file.to_string(),
            line,
            column,
            name: "test_func".to_string(),
            causes: HashSet::new(),
            children: Vec::new(),
            is_direct_panic: false,
            called_function: None,
        }
    }

    #[test]
    fn test_deduplicate_code_points_empty() {
        let points: Vec<CrateCodePoint> = vec![];
        let result = deduplicate_code_points(points);
        assert!(result.is_empty());
    }

    #[test]
    fn test_deduplicate_code_points_no_duplicates() {
        let points = vec![
            make_code_point("src/main.rs", 10, Some(5)),
            make_code_point("src/main.rs", 20, Some(10)),
            make_code_point("src/lib.rs", 10, Some(5)),
        ];
        let result = deduplicate_code_points(points);
        assert_eq!(result.len(), 3);
    }

    #[test]
    fn test_deduplicate_code_points_with_duplicates() {
        let points = vec![
            make_code_point("src/main.rs", 10, Some(5)),
            make_code_point("src/main.rs", 10, Some(5)), // duplicate
            make_code_point("src/main.rs", 20, Some(10)),
            make_code_point("src/main.rs", 10, Some(5)), // duplicate
        ];
        let result = deduplicate_code_points(points);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].line, 10);
        assert_eq!(result[1].line, 20);
    }

    #[test]
    fn test_deduplicate_code_points_column_matters() {
        // Same file and line, different columns - NOT duplicates
        let points = vec![
            make_code_point("src/main.rs", 10, Some(5)),
            make_code_point("src/main.rs", 10, Some(15)),
        ];
        let result = deduplicate_code_points(points);
        assert_eq!(result.len(), 2);
    }

    #[test]
    fn test_deduplicate_code_points_none_column() {
        // None columns are treated as 0 for deduplication
        let points = vec![
            make_code_point("src/main.rs", 10, None),
            make_code_point("src/main.rs", 10, None), // duplicate
            make_code_point("src/main.rs", 10, Some(0)), // also duplicate (None -> 0)
        ];
        let result = deduplicate_code_points(points);
        assert_eq!(result.len(), 1);
    }

    #[test]
    fn test_group_points_by_uri_empty() {
        let points: Vec<CrateCodePoint> = vec![];
        let workspace_root = PathBuf::from("/workspace");
        let result = group_points_by_uri(points, &workspace_root, "/workspace/target");
        assert!(result.is_empty());
    }

    #[test]
    fn test_group_points_by_uri_filters_target_dir() {
        let points = vec![
            make_code_point("/workspace/src/main.rs", 10, Some(5)),
            make_code_point("/workspace/target/debug/build/foo.rs", 20, Some(10)), // filtered
            make_code_point("/workspace/src/lib.rs", 30, Some(15)),
        ];
        let workspace_root = PathBuf::from("/workspace");
        let result = group_points_by_uri(points, &workspace_root, "/workspace/target");

        assert_eq!(result.len(), 2);
        assert!(result.keys().all(|uri| !uri.path().contains("/target/")));
    }

    #[test]
    fn test_group_points_by_uri_groups_by_file() {
        let points = vec![
            make_code_point("/workspace/src/main.rs", 10, Some(5)),
            make_code_point("/workspace/src/main.rs", 20, Some(10)),
            make_code_point("/workspace/src/lib.rs", 30, Some(15)),
        ];
        let workspace_root = PathBuf::from("/workspace");
        let result = group_points_by_uri(points, &workspace_root, "/workspace/target");

        assert_eq!(result.len(), 2);

        let main_uri = Url::from_file_path("/workspace/src/main.rs").unwrap();
        let lib_uri = Url::from_file_path("/workspace/src/lib.rs").unwrap();

        assert_eq!(result.get(&main_uri).unwrap().len(), 2);
        assert_eq!(result.get(&lib_uri).unwrap().len(), 1);
    }

    #[test]
    fn test_group_points_by_uri_relative_paths() {
        // Relative paths should be joined with workspace_root
        let points = vec![
            make_code_point("src/main.rs", 10, Some(5)),
            make_code_point("src/lib.rs", 20, Some(10)),
        ];
        let workspace_root = PathBuf::from("/workspace");
        let result = group_points_by_uri(points, &workspace_root, "/workspace/target");

        assert_eq!(result.len(), 2);

        let main_uri = Url::from_file_path("/workspace/src/main.rs").unwrap();
        assert!(result.contains_key(&main_uri));
    }

    #[test]
    fn test_analyze_workspace_targets_empty() {
        let targets: Vec<PathBuf> = vec![];
        let project_context = ProjectContext::default();
        let result = analyze_workspace_targets(&targets, &project_context);

        assert!(result.points.is_empty());
        assert_eq!(result.total_count, 0);
        assert_eq!(result.analyzed_count, 0);
        assert_eq!(result.skipped_count, 0);
    }

    #[test]
    fn test_analyze_workspace_targets_nonexistent() {
        // Non-existent targets should be skipped
        let targets = vec![PathBuf::from("/nonexistent/binary")];
        let project_context = ProjectContext::default();
        let result = analyze_workspace_targets(&targets, &project_context);

        assert!(result.points.is_empty());
        assert_eq!(result.analyzed_count, 0);
        assert_eq!(result.skipped_count, 1);
    }

    #[test]
    fn test_analyze_workspace_targets_real_binary() {
        // Test with a real binary from the workspace
        let workspace_root = find_workspace_root();
        let panic_example = workspace_root.join("examples/panic");

        // Build the example first
        let status = std::process::Command::new("cargo")
            .arg("build")
            .current_dir(&panic_example)
            .status();

        if status.is_err() || !status.unwrap().success() {
            // Skip test if build fails
            return;
        }

        let binary = panic_example.join("target/debug/panic");
        if !binary.exists() {
            return;
        }

        let targets = vec![binary];
        let project_context = ProjectContext::from_project_root(&panic_example)
            .expect("Should build project context for panic example");
        let result = analyze_workspace_targets(&targets, &project_context);

        assert_eq!(result.analyzed_count, 1);
        assert_eq!(result.skipped_count, 0);
        // The panic example should have many panic points
        assert!(
            result.total_count > 0,
            "Should find panic points in panic example"
        );
    }

    #[test]
    fn test_analysis_result_default() {
        let result = AnalysisResult::default();
        assert!(result.points.is_empty());
        assert_eq!(result.total_count, 0);
        assert_eq!(result.analyzed_count, 0);
        assert_eq!(result.skipped_count, 0);
    }

    // ========================================================================
    // Tests for code_point_to_diagnostic
    // ========================================================================

    #[test]
    fn test_code_point_to_diagnostic_empty_causes() {
        let point = make_code_point("src/main.rs", 42, Some(10));
        let diag = JonesyLspServer::code_point_to_diagnostic(&point);

        assert_eq!(diag.severity, Some(DiagnosticSeverity::WARNING));
        assert_eq!(diag.source, Some("jonesy".to_string()));
        assert_eq!(diag.message, "potential panic point");
        assert!(diag.code.is_none());
        assert!(diag.code_description.is_none());
        // LSP uses 0-based lines
        assert_eq!(diag.range.start.line, 41);
        assert_eq!(diag.range.start.character, 9);
    }

    #[test]
    fn test_code_point_to_diagnostic_single_cause() {
        use crate::panic_cause::PanicCause;

        let mut causes = HashSet::new();
        causes.insert(PanicCause::Unwrap);

        let point = CrateCodePoint {
            file: "src/main.rs".to_string(),
            line: 10,
            column: Some(5),
            name: "my_func".to_string(),
            causes,
            children: Vec::new(),
            is_direct_panic: true,
            called_function: None,
        };

        let diag = JonesyLspServer::code_point_to_diagnostic(&point);

        assert!(diag.message.contains("unwrap"));
        // Single cause should also show JP code in message (consistent with multi-cause)
        assert!(
            diag.message.contains("JP006"),
            "Single-cause message should include error code. Got: {}",
            diag.message
        );
        assert!(diag.code.is_some());
        assert!(diag.code_description.is_some());
        // Should have help message for direct panic
        assert!(diag.message.contains("help:"));
    }

    #[test]
    fn test_code_point_to_diagnostic_multiple_causes() {
        use crate::panic_cause::PanicCause;

        let mut causes = HashSet::new();
        causes.insert(PanicCause::Unwrap);
        causes.insert(PanicCause::Expect);

        let point = CrateCodePoint {
            file: "src/main.rs".to_string(),
            line: 10,
            column: Some(5),
            name: "my_func".to_string(),
            causes,
            children: Vec::new(),
            is_direct_panic: false,
            called_function: Some("risky_fn".to_string()),
        };

        let diag = JonesyLspServer::code_point_to_diagnostic(&point);

        // Multiple causes shown in message
        assert!(diag.message.contains("JP"));
        // Data should contain cause info
        assert!(diag.data.is_some());
        let data = diag.data.unwrap();
        let causes_arr: Vec<String> = serde_json::from_value(data["causes"].clone()).unwrap();
        assert_eq!(causes_arr.len(), 2);
    }

    #[test]
    fn test_code_point_to_diagnostic_no_column() {
        let point = make_code_point("src/main.rs", 100, None);
        let diag = JonesyLspServer::code_point_to_diagnostic(&point);

        // No column defaults to 1, then subtract 1 for 0-based = 0
        assert_eq!(diag.range.start.character, 0);
    }

    #[test]
    fn test_code_point_to_diagnostic_line_1() {
        // Edge case: line 1 should not underflow
        let point = make_code_point("src/main.rs", 1, Some(1));
        let diag = JonesyLspServer::code_point_to_diagnostic(&point);

        assert_eq!(diag.range.start.line, 0);
        assert_eq!(diag.range.start.character, 0);
    }

    // ========================================================================
    // Tests for get_module_pattern
    // ========================================================================

    #[test]
    fn test_get_module_pattern_tests_dir() {
        let uri = Url::parse("file:///workspace/tests/unit_tests.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert_eq!(result, Some(("**/tests/**", "tests")));
    }

    #[test]
    fn test_get_module_pattern_benches_dir() {
        let uri = Url::parse("file:///workspace/benches/perf.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert_eq!(result, Some(("**/benches/**", "benches")));
    }

    #[test]
    fn test_get_module_pattern_examples_dir() {
        let uri = Url::parse("file:///workspace/examples/demo.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert_eq!(result, Some(("**/examples/**", "examples")));
    }

    #[test]
    fn test_get_module_pattern_test_suffix() {
        let uri = Url::parse("file:///workspace/src/parser_test.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert_eq!(result, Some(("**/*_test.rs", "test files")));
    }

    #[test]
    fn test_get_module_pattern_tests_suffix() {
        let uri = Url::parse("file:///workspace/src/parser_tests.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert_eq!(result, Some(("**/*_tests.rs", "test files")));
    }

    #[test]
    fn test_get_module_pattern_regular_src() {
        let uri = Url::parse("file:///workspace/src/parser.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert!(result.is_none());
    }

    #[test]
    fn test_get_module_pattern_main_rs() {
        let uri = Url::parse("file:///workspace/src/main.rs").unwrap();
        let result = JonesyLspServer::get_module_pattern(&uri);
        assert!(result.is_none());
    }

    // ========================================================================
    // Tests for expand_workspace_glob
    // ========================================================================

    #[test]
    fn test_expand_workspace_glob_nonexistent_dir() {
        let workspace_root = PathBuf::from("/nonexistent/path");
        let result = expand_workspace_glob(&workspace_root, "crates/*");
        assert!(result.is_empty());
    }

    #[test]
    fn test_expand_workspace_glob_real_workspace() {
        let workspace_root = find_workspace_root();
        let result = expand_workspace_glob(&workspace_root, "examples/*");

        // Should find example crates
        assert!(!result.is_empty(), "Should find example directories");

        // All results should have Cargo.toml
        for path in &result {
            assert!(
                path.join("Cargo.toml").exists(),
                "{} should have Cargo.toml",
                path.display()
            );
        }
    }

    // ========================================================================
    // Tests for discover_workspace
    // ========================================================================

    #[test]
    fn test_discover_workspace_real() {
        let workspace_root = find_workspace_root();
        let info = discover_workspace(&workspace_root);

        assert!(info.is_some());
        let info = info.unwrap();

        // Should have workspace members
        assert!(!info.members.is_empty());
    }

    #[test]
    fn test_discover_workspace_single_crate() {
        let workspace_root = find_workspace_root();
        let panic_example = workspace_root.join("examples/panic");

        let info = discover_workspace(&panic_example);
        assert!(info.is_some());
        let info = info.unwrap();

        // Single crate should have the package name as a member
        assert!(!info.members.is_empty());
    }

    #[test]
    fn test_discover_workspace_nonexistent() {
        let workspace_root = PathBuf::from("/nonexistent/path");
        let info = discover_workspace(&workspace_root);
        assert!(info.is_none());
    }

    // ========================================================================
    // Tests for find_workspace_binaries edge cases
    // ========================================================================

    #[test]
    fn test_find_workspace_binaries_no_cargo_toml() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_no_cargo");
        let _ = std::fs::create_dir_all(&temp_dir);

        let result = find_workspace_binaries(&temp_dir);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());

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

    #[test]
    fn test_find_workspace_binaries_no_target() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_no_target");
        let _ = std::fs::create_dir_all(&temp_dir);

        // Create minimal Cargo.toml
        std::fs::write(
            temp_dir.join("Cargo.toml"),
            r#"[package]
name = "test"
version = "0.1.0"
"#,
        )
        .unwrap();

        let result = find_workspace_binaries(&temp_dir);
        assert!(result.is_ok());
        assert!(result.unwrap().is_empty());

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

    // ========================================================================
    // Tests for find_config_files edge cases
    // ========================================================================

    #[test]
    fn test_find_config_files_no_cargo_toml() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_config_no_cargo");
        let _ = std::fs::create_dir_all(&temp_dir);

        let files = find_config_files(&temp_dir);

        // Should always include jonesy.toml path
        assert!(files.iter().any(|p| p.ends_with("jonesy.toml")));
        // But not much else without Cargo.toml
        assert_eq!(files.len(), 1);

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

    #[test]
    fn test_find_config_files_single_crate() {
        let temp_dir = std::env::temp_dir().join("jonesy_test_config_single");
        let _ = std::fs::create_dir_all(&temp_dir);

        // Create minimal Cargo.toml (not a workspace)
        std::fs::write(
            temp_dir.join("Cargo.toml"),
            r#"[package]
name = "test"
version = "0.1.0"
"#,
        )
        .unwrap();

        let files = find_config_files(&temp_dir);

        // Should include jonesy.toml and Cargo.toml
        assert!(files.iter().any(|p| p.ends_with("jonesy.toml")));
        assert!(files.iter().any(|p| p.ends_with("Cargo.toml")));
        assert_eq!(files.len(), 2);

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

    #[test]
    fn test_format_change_summary_single_package() {
        use crate::analysis_cache::{AnalysisCache, build_workspace_state};

        // Single package: use a simple crate (e.g., one of our examples)
        let workspace_root = find_workspace_root();
        let example_dir = workspace_root.join("examples").join("rlib");
        let state = build_workspace_state(&example_dir);
        assert!(state.is_single_package());

        // Simulate a library change by detecting changes vs an empty cache
        let cache = AnalysisCache::default();
        let changes = cache.detect_workspace_changes(&state);

        let summary = format_change_summary(&changes, &state);
        assert!(
            summary.starts_with("Package changes:"),
            "Single package should use 'Package changes' format. Got: {}",
            summary
        );
        assert!(
            summary.contains("library"),
            "Should mention library. Got: {}",
            summary
        );
    }

    #[test]
    fn test_format_change_summary_workspace() {
        use crate::analysis_cache::{AnalysisCache, build_workspace_state};

        // Workspace: use the jonesy project root (which has workspace members)
        let workspace_root = find_workspace_root();
        let state = build_workspace_state(&workspace_root);
        assert!(!state.is_single_package());

        // Simulate changes by detecting vs an empty cache
        let cache = AnalysisCache::default();
        let changes = cache.detect_workspace_changes(&state);

        let summary = format_change_summary(&changes, &state);
        assert!(
            summary.starts_with("Workspace changes:"),
            "Workspace should use 'Workspace changes' format. Got: {}",
            summary
        );
        assert!(
            summary.contains("members"),
            "Should mention members. Got: {}",
            summary
        );
    }
}