ripr 0.6.0

Find static mutation-exposure gaps before expensive mutation testing
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
use super::actions::code_action_response;
use super::backend::{
    Backend, RefreshLogSummary, refresh_completed_log_message, refresh_failed_log_message,
};
use super::capabilities::{initialize_result, root_from_initialize_params};
use super::config::LspAnalysisConfig;
use super::diagnostics::{
    DiagnosticBatch, WorkspaceDiagnostics, diagnostic_for_classified_seam, diagnostic_for_finding,
    diagnostic_refresh_plan, diagnostic_severity_for_class, take_all_uris,
    workspace_diagnostic_batches, workspace_diagnostic_batches_with_config,
    workspace_diagnostics_with_config,
};
use super::gap_artifacts::{
    GapArtifactIdentity, GapArtifactKind, GapArtifactRejection, ValidatedGapArtifact,
};
use super::hover::{classified_seam_hover_response, hover_response, hover_with_snapshot_status};
use super::state::{AnalysisSnapshot, DocumentStore, RefreshMetadata, format_duration};
use super::uri::{encode_uri_path, file_uri_for_path, file_uris_match, path_from_file_uri};
use super::{
    COLLECT_CONTEXT_COMMAND, COLLECT_EVIDENCE_CONTEXT_COMMAND, COPY_AFTER_SNAPSHOT_COMMAND,
    COPY_AGENT_BRIEF_COMMAND, COPY_AGENT_PACKET_COMMAND, COPY_AGENT_RECEIPT_COMMAND,
    COPY_AGENT_VERIFY_COMMAND, COPY_CONTEXT_COMMAND, COPY_SUGGESTED_ASSERTION_COMMAND,
    COPY_TARGETED_TEST_BRIEF_COMMAND, HOVER_TEXT, OPEN_RELATED_TEST_COMMAND, REFRESH_COMMAND,
};
use crate::app::Mode;
use crate::domain::{
    Confidence, DeltaKind, ExposureClass, Finding, LanguageId, LanguageStatus, OracleKind,
    OracleStrength, OwnerKind, Probe, ProbeFamily, ProbeId, RelatedTest, RevealEvidence,
    RiprEvidence, SourceLocation, StageEvidence, StageState, StaticLimitKind,
};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tower_lsp_server::LanguageServer;
use tower_lsp_server::ls_types::{
    CodeActionContext, CodeActionOrCommand, CodeActionParams, DiagnosticSeverity,
    DidChangeTextDocumentParams, DidCloseTextDocumentParams, DidOpenTextDocumentParams,
    ExecuteCommandParams, HoverContents, HoverParams, HoverProviderCapability, InitializeParams,
    MarkedString, NumberOrString, Position, Range, TextDocumentContentChangeEvent,
    TextDocumentIdentifier, TextDocumentItem, TextDocumentPositionParams,
    TextDocumentSyncCapability, TextDocumentSyncKind, VersionedTextDocumentIdentifier,
    WorkspaceFolder,
};
use tower_lsp_server::{LspService, Server};

#[test]
fn initialize_result_exposes_existing_lsp_capabilities() -> Result<(), String> {
    let result = initialize_result();

    assert_eq!(
        result.capabilities.text_document_sync,
        Some(TextDocumentSyncCapability::Kind(TextDocumentSyncKind::FULL))
    );
    assert_eq!(
        result.capabilities.hover_provider,
        Some(HoverProviderCapability::Simple(true))
    );
    let Some(provider) = result.capabilities.execute_command_provider else {
        return Err("expected execute command provider".to_string());
    };
    let commands = provider.commands;
    assert_eq!(
        commands,
        vec![
            REFRESH_COMMAND,
            COLLECT_CONTEXT_COMMAND,
            COLLECT_EVIDENCE_CONTEXT_COMMAND
        ]
    );
    Ok(())
}

#[test]
fn framed_lsp_protocol_smoke_exercises_tower_server() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;

    runtime.block_on(async {
        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
        let (client_read, mut client_write) = tokio::io::split(client_io);
        let (server_read, server_write) = tokio::io::split(server_io);
        let (service, socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let mut server_task = tokio::spawn(async move {
            Server::new(server_read, server_write, socket)
                .serve(service)
                .await;
        });
        let mut client_read = client_read;
        let text_uri = "file:///workspace/src/lib.rs";

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "processId": null,
                    "rootUri": "file:///target/ripr/lsp-protocol-smoke-missing-root",
                    "capabilities": {}
                }
            }),
        )
        .await?;
        let initialize = read_lsp_response(&mut client_read, 1).await?;
        assert_eq!(
            initialize["result"]["capabilities"]["executeCommandProvider"]["commands"][0],
            REFRESH_COMMAND
        );
        assert_eq!(
            initialize["result"]["capabilities"]["executeCommandProvider"]["commands"][1],
            COLLECT_CONTEXT_COMMAND
        );
        assert_eq!(
            initialize["result"]["capabilities"]["executeCommandProvider"]["commands"][2],
            COLLECT_EVIDENCE_CONTEXT_COMMAND
        );
        assert_eq!(
            initialize["result"]["capabilities"]["hoverProvider"],
            serde_json::Value::Bool(true)
        );

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "initialized",
                "params": {}
            }),
        )
        .await?;
        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "textDocument/didOpen",
                "params": {
                    "textDocument": {
                        "uri": text_uri,
                        "languageId": "rust",
                        "version": 1,
                        "text": "pub fn demo() -> bool { true }\n"
                    }
                }
            }),
        )
        .await?;
        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "workspace/executeCommand",
                "params": {
                    "command": REFRESH_COMMAND,
                    "arguments": []
                }
            }),
        )
        .await?;
        let (refresh, notifications) =
            read_lsp_response_with_notifications(&mut client_read, 2).await?;
        assert!(refresh.get("error").is_none());
        assert_eq!(refresh["result"], serde_json::Value::Null);
        let notification_messages = log_notification_messages(&notifications);
        assert!(
            notification_messages
                .iter()
                .any(|message| message.contains("ripr analysis refresh started"))
        );
        assert!(
            notification_messages
                .iter()
                .any(|message| message.contains("ripr analysis refresh failed after"))
        );

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 3,
                "method": "textDocument/hover",
                "params": {
                    "textDocument": { "uri": text_uri },
                    "position": { "line": 0, "character": 4 }
                }
            }),
        )
        .await?;
        let hover = read_lsp_response(&mut client_read, 3).await?;
        let hover_value = hover["result"]["contents"]["value"]
            .as_str()
            .ok_or_else(|| "expected hover markdown value".to_string())?;
        assert!(hover_value.contains("ripr estimates static RIPR exposure"));

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 4,
                "method": "textDocument/codeAction",
                "params": {
                    "textDocument": { "uri": text_uri },
                    "range": {
                        "start": { "line": 0, "character": 0 },
                        "end": { "line": 0, "character": 4 }
                    },
                    "context": { "diagnostics": [] }
                }
            }),
        )
        .await?;
        let actions = read_lsp_response(&mut client_read, 4).await?;
        assert_eq!(
            actions["result"][0]["title"],
            "Refresh Analysis - Saved Workspace Check"
        );
        assert_eq!(actions["result"][0]["command"]["command"], REFRESH_COMMAND);

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 5,
                "method": "shutdown",
                "params": null
            }),
        )
        .await?;
        let shutdown = read_lsp_response(&mut client_read, 5).await?;
        assert!(shutdown.get("error").is_none());
        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "exit",
                "params": null
            }),
        )
        .await?;
        client_write
            .shutdown()
            .await
            .map_err(|err| format!("failed to close test client: {err}"))?;
        match tokio::time::timeout(std::time::Duration::from_secs(2), &mut server_task).await {
            Ok(join_result) => {
                join_result.map_err(|err| format!("LSP server task failed: {err}"))?;
            }
            Err(_) => {
                server_task.abort();
                return Err("LSP server did not stop after exit notification".to_string());
            }
        }
        Ok(())
    })
}

#[test]
fn framed_lsp_protocol_smoke_logs_successful_refresh_completion() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;

    runtime.block_on(async {
        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
        let (client_read, mut client_write) = tokio::io::split(client_io);
        let (server_read, server_write) = tokio::io::split(server_io);
        let (service, socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let mut server_task = tokio::spawn(async move {
            Server::new(server_read, server_write, socket)
                .serve(service)
                .await;
        });
        let mut client_read = client_read;
        // Keep this protocol smoke bounded now that seam diagnostics default on;
        // whole-repo inventory behavior is covered by fixture and report tests.
        let repo_root =
            Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/boundary_gap/input");
        let root_uri = file_uri_for_path(&repo_root)?;

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "processId": null,
                    "rootUri": root_uri.as_str(),
                    "initializationOptions": {
                        "baseRef": "HEAD",
                        "checkMode": "instant"
                    },
                    "capabilities": {}
                }
            }),
        )
        .await?;
        let initialize = read_lsp_response(&mut client_read, 1).await?;
        assert!(initialize.get("error").is_none());

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "workspace/executeCommand",
                "params": {
                    "command": REFRESH_COMMAND,
                    "arguments": []
                }
            }),
        )
        .await?;
        let (refresh, notifications) =
            read_lsp_response_with_notifications(&mut client_read, 2).await?;
        assert!(refresh.get("error").is_none());
        assert_eq!(refresh["result"], serde_json::Value::Null);
        let notification_messages = log_notification_messages(&notifications);
        assert!(
            notification_messages
                .iter()
                .any(|message| message.contains("ripr analysis refresh started"))
        );
        assert!(
            notification_messages
                .iter()
                .any(|message| message.contains("ripr analysis refresh completed in"))
        );

        let (text_uri, seam_diagnostic) =
            published_seam_diagnostic(&notifications, "67fc764ba37d77bd")?;
        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 3,
                "method": "textDocument/hover",
                "params": {
                    "textDocument": { "uri": text_uri },
                    "position": { "line": 1, "character": 1 }
                }
            }),
        )
        .await?;
        let hover = read_lsp_response(&mut client_read, 3).await?;
        let hover_value = hover["result"]["contents"]["value"]
            .as_str()
            .ok_or_else(|| "expected seam hover markdown value".to_string())?;
        assert!(
            hover_value.contains("## Missing discriminator"),
            "expected seam hover to name missing discriminator, got {hover_value}"
        );
        assert!(
            hover_value.contains("## Related tests"),
            "expected seam hover to name related tests, got {hover_value}"
        );
        assert!(
            hover_value.contains("## Next step"),
            "expected seam hover to name next step, got {hover_value}"
        );
        assert!(
            hover_value.contains("## Suggested test shape"),
            "expected seam hover to name suggested test shape, got {hover_value}"
        );
        assert!(
            hover_value.contains("## Handoff, verify, and receipt commands"),
            "expected seam hover to name handoff, verify, and receipt commands, got {hover_value}"
        );
        assert!(
            hover_value.contains("## Limits"),
            "expected seam hover to name static limits, got {hover_value}"
        );

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 4,
                "method": "textDocument/codeAction",
                "params": {
                    "textDocument": { "uri": text_uri },
                    "range": seam_diagnostic["range"].clone(),
                    "context": { "diagnostics": [seam_diagnostic] }
                }
            }),
        )
        .await?;
        let code_actions = read_lsp_response(&mut client_read, 4).await?;
        let titles = code_actions["result"]
            .as_array()
            .ok_or_else(|| "expected codeAction result array".to_string())?
            .iter()
            .filter_map(|action| action.get("title").and_then(serde_json::Value::as_str))
            .collect::<Vec<_>>();
        for expected in [
            "Inspect Test Gap - Copy Context",
            "Write targeted test: copy brief",
            "Verify after test: copy verify command",
            "Review result: copy receipt command",
        ] {
            assert!(
                titles.contains(&expected),
                "expected protocol code actions to contain {expected}, got {titles:?}"
            );
        }

        let seam_id = seam_diagnostic["data"]["seam_id"]
            .as_str()
            .ok_or_else(|| "expected seam diagnostic data.seam_id".to_string())?;
        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 5,
                "method": "workspace/executeCommand",
                "params": {
                    "command": COLLECT_EVIDENCE_CONTEXT_COMMAND,
                    "arguments": [{
                        "seam_id": seam_id,
                        "uri": text_uri,
                        "line": 2
                    }]
                }
            }),
        )
        .await?;
        let context_packet = read_lsp_response(&mut client_read, 5).await?;
        assert_eq!(
            context_packet["result"]["schema_version"],
            serde_json::Value::String("0.1".to_string())
        );
        assert_eq!(context_packet["result"]["seam_id"], seam_id);
        assert_eq!(
            context_packet["result"]["evidence_path"]["discriminate"],
            "present"
        );
        assert_eq!(
            context_packet["result"]["missing_discriminator"],
            "discount_threshold (equality boundary)"
        );
        assert!(
            context_packet["result"]["related_test"]
                .as_str()
                .is_some_and(|value| value.contains("tests/pricing.rs"))
        );
        assert!(
            context_packet["result"]["agent_brief_command"]
                .as_str()
                .is_some_and(|value| value.starts_with("ripr agent brief --root . --seam-id "))
        );
        assert!(
            context_packet["result"]["verify_command"]
                .as_str()
                .is_some_and(|value| value.contains("ripr agent verify --root ."))
        );
        assert!(
            context_packet["result"]["receipt_command"]
                .as_str()
                .is_some_and(|value| value.contains("ripr agent receipt --root ."))
        );
        assert_eq!(
            context_packet["result"]["limits_note"],
            "Static evidence only; no runtime mutation execution."
        );

        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 6,
                "method": "shutdown",
                "params": null
            }),
        )
        .await?;
        let shutdown = read_lsp_response(&mut client_read, 6).await?;
        assert!(shutdown.get("error").is_none());
        write_lsp_message(
            &mut client_write,
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "exit",
                "params": null
            }),
        )
        .await?;
        client_write
            .shutdown()
            .await
            .map_err(|err| format!("failed to close test client: {err}"))?;
        match tokio::time::timeout(std::time::Duration::from_secs(2), &mut server_task).await {
            Ok(join_result) => {
                join_result.map_err(|err| format!("LSP server task failed: {err}"))?;
            }
            Err(_) => {
                server_task.abort();
                return Err("LSP server did not stop after exit notification".to_string());
            }
        }
        Ok(())
    })
}

fn published_seam_diagnostic(
    notifications: &[serde_json::Value],
    seam_id: &str,
) -> Result<(String, serde_json::Value), String> {
    for notification in notifications {
        if notification
            .get("method")
            .and_then(serde_json::Value::as_str)
            != Some("textDocument/publishDiagnostics")
        {
            continue;
        }
        let Some(uri) = notification
            .get("params")
            .and_then(|params| params.get("uri"))
            .and_then(serde_json::Value::as_str)
        else {
            continue;
        };
        let Some(diagnostics) = notification
            .get("params")
            .and_then(|params| params.get("diagnostics"))
            .and_then(serde_json::Value::as_array)
        else {
            continue;
        };
        for diagnostic in diagnostics {
            if diagnostic
                .get("data")
                .and_then(|data| data.get("seam_id"))
                .and_then(serde_json::Value::as_str)
                == Some(seam_id)
            {
                return Ok((uri.to_string(), diagnostic.clone()));
            }
        }
    }
    Err(format!(
        "expected published seam diagnostic with seam_id {seam_id}"
    ))
}

#[test]
fn hover_response_keeps_current_guidance_text() -> Result<(), String> {
    let hover = hover_response();

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert_eq!(markup.value, HOVER_TEXT);
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn hover_for_position_uses_latest_matching_diagnostic() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected diagnostic hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("**ripr** `weakly_exposed`"));
            assert!(markup.value.contains("Add an exact boundary assertion."));
            assert!(markup.value.contains("## RIPR Evidence"));
            assert!(markup.value.contains("* reach yes: related tests found"));
            assert!(
                markup
                    .value
                    .contains("* infection yes: predicate can alter branch behavior")
            );
            assert!(
                markup
                    .value
                    .contains("* propagation yes: branch influences return value")
            );
            assert!(
                markup
                    .value
                    .contains("* observation weak: return value asserted")
            );
            assert!(
                markup
                    .value
                    .contains("* discriminator weak: boundary value missing")
            );
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn hover_for_position_shows_snapshot_age_and_refresh_duration() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic],
        vec![finding],
    );
    diagnostics
        .snapshot
        .refresh
        .record_duration(Duration::from_millis(42));
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected diagnostic hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("Analysis snapshot: generated "));
            assert!(markup.value.contains(" ago; last refresh took 42 ms."));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn hover_for_position_adds_snapshot_status_to_seam_hover() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let seam = sample_classified_seam();
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let line = diagnostic.range.start.line;
    let mut diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic],
        Vec::new(),
    );
    diagnostics.snapshot.classified_seams = vec![seam];
    diagnostics
        .snapshot
        .refresh
        .record_duration(Duration::from_millis(11));
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, line, 1)) else {
        return Err("expected seam hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("**ripr** behavioral seam"));
            assert!(markup.value.contains("`weakly_gripped`"));
            assert!(markup.value.contains("Analysis snapshot: generated "));
            assert!(markup.value.contains(" ago; last refresh took 11 ms."));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn snapshot_status_leaves_non_markup_hover_content_unchanged() -> Result<(), String> {
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let snapshot =
        sample_analysis_snapshot(PathBuf::from("/workspace"), uri, Vec::new(), Vec::new());
    let hover = tower_lsp_server::ls_types::Hover {
        contents: HoverContents::Scalar(MarkedString::String("plain".to_string())),
        range: None,
    };

    let hover = hover_with_snapshot_status(hover, &snapshot);

    match hover.contents {
        HoverContents::Scalar(MarkedString::String(value)) => {
            assert_eq!(value, "plain");
            Ok(())
        }
        _ => Err("expected scalar hover".to_string()),
    }
}

#[test]
fn hover_fallback_to_diagnostic_without_matching_finding() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut mismatched_finding = sample_finding();
    mismatched_finding.id = "probe:other:1:predicate".to_string();
    mismatched_finding.probe.id.0 = "probe:other:1:predicate".to_string();
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![mismatched_finding],
    );
    let batches = vec![DiagnosticBatch {
        uri: uri.clone(),
        diagnostics: vec![diagnostic.clone()],
    }];
    let workspace_diagnostics = WorkspaceDiagnostics { snapshot, batches };
    let Some(_) = backend.refresh_plan(workspace_diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected diagnostic hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("**ripr** `weakly_exposed`"));
            assert!(markup.value.contains("Add an exact boundary assertion."));
            assert!(
                markup
                    .value
                    .contains("Finding: `probe:pricing:88:predicate`")
            );
            assert!(!markup.value.contains("## RIPR Evidence"));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn hover_for_position_returns_none_when_no_diagnostic_matches() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    assert!(
        backend
            .hover_for_position(&hover_params(uri, 0, 1))
            .is_none(),
        "expected None when no diagnostic matches position"
    );

    let generic = hover_response();
    match generic.contents {
        HoverContents::Markup(markup) => {
            assert_eq!(markup.value, HOVER_TEXT);
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn finding_hover_renders_related_tests_and_oracle_text() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let mut finding = sample_finding();
    finding.related_tests.push(RelatedTest {
        name: "discount_boundary_is_exact".to_string(),
        file: PathBuf::from("tests/pricing.rs"),
        line: 12,
        oracle: Some("assert_eq!(total, expected)".to_string()),
        oracle_kind: OracleKind::ExactValue,
        oracle_strength: OracleStrength::Strong,
    });
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected finding hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("## Related Tests"));
            assert!(
                markup
                    .value
                    .contains("`tests/pricing.rs:12` `discount_boundary_is_exact`")
            );
            assert!(
                markup
                    .value
                    .contains("\u{2014} strong exact_value oracle: assert_eq!(total, expected)")
            );
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn finding_hover_renders_weakness_section() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let mut finding = sample_finding();
    finding
        .missing
        .push("no equality-boundary case was found".to_string());
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected finding hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("## Weakness"));
            assert!(
                markup
                    .value
                    .contains("- no equality-boundary case was found")
            );
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn finding_hover_avoids_mutation_runtime_terms() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected finding hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            let banned: Vec<String> = vec![
                std::iter::once('k').chain("illed".chars()).collect(),
                std::iter::once('s').chain("urvived".chars()).collect(),
                std::iter::once('p').chain("roven".chars()).collect(),
                std::iter::once('a').chain("dequate".chars()).collect(),
                std::iter::once('u').chain("ntested".chars()).collect(),
            ];
            for term in banned {
                assert!(
                    !markup.value.to_ascii_lowercase().contains(&term),
                    "hover contained banned mutation-runtime term: {term}"
                );
            }
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn analysis_snapshot_finds_finding_from_diagnostic_data() -> Result<(), String> {
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        vec![finding],
    );

    let Some(found) = snapshot.finding_for_diagnostic(&diagnostic) else {
        return Err("expected finding from diagnostic data".to_string());
    };

    assert_eq!(found.id, "probe:pricing:88:predicate");
    assert_eq!(found.probe.expression, "amount >= threshold");
    Ok(())
}

#[test]
fn overlapping_diagnostics_prefer_seam_id_lookup_over_finding_id_lookup() -> Result<(), String> {
    // Regression for chatgpt-codex review on PR #242: when a Finding
    // diagnostic and a Seam diagnostic share the same line, the
    // backend's hover handler must prefer the seam-bearing one. The
    // batch builder pushes findings before seams in the per-uri
    // diagnostic vector, so a naive first-match scan would shadow the
    // new seam-evidence hover. Pin the priority by direct lookup.
    let finding = sample_finding();
    let finding_diag = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let mut seam_diag = finding_diag.clone();
    seam_diag.data = Some(serde_json::json!({
        "schema_version": "0.1",
        "seam_id": "f3c9e4d21a0b7c88",
        "seam_kind": "predicate_boundary",
        "grip_class": "weakly_gripped",
    }));
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    // Order matters here: finding diagnostic first, seam diagnostic
    // second — the same order the batch builder uses.
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![finding_diag.clone(), seam_diag.clone()],
        vec![finding],
    );

    // Both lookups exist in the snapshot. The backend's overlap fix
    // walks all matching diagnostics and prefers the seam-bearing
    // one. We verify the lookups individually here; the backend
    // ordering is exercised by `framed_lsp_protocol_smoke_exercises_tower_server`.
    if snapshot.finding_for_diagnostic(&finding_diag).is_none() {
        return Err("finding lookup should still resolve".to_string());
    }
    // The seam diagnostic carries seam_id but no matching seam in
    // classified_seams (the test snapshot helper has empty seams).
    // What matters is that classified_seam_for_diagnostic only fires
    // for diagnostics with data.seam_id — i.e., it does not match
    // finding_diag.
    if snapshot
        .classified_seam_for_diagnostic(&finding_diag)
        .is_some()
    {
        return Err(
            "classified_seam_for_diagnostic should reject diagnostics carrying finding_id only"
                .to_string(),
        );
    }
    Ok(())
}

#[test]
fn given_diagnostic_with_unknown_seam_id_when_lookup_runs_then_no_classified_seam_is_returned()
-> Result<(), String> {
    // Regression for the directive's "unknown seam_id falls back
    // safely" acceptance: a diagnostic carries data.seam_id but the
    // snapshot has no matching ClassifiedSeam (e.g., the snapshot was
    // refreshed and the seam was filtered out). Lookup must return
    // None so the backend falls through to finding hover or the
    // generic diagnostic hover; the LSP must not panic or hang.
    let finding = sample_finding();
    let mut diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    // Replace the diagnostic data with a synthetic seam_id that does
    // not appear in classified_seams. Drops the finding_id, mirroring
    // a seam evidence diagnostic.
    diagnostic.data = Some(serde_json::json!({
        "schema_version": "0.1",
        "seam_id": "deadbeef00000000",
        "seam_kind": "predicate_boundary",
        "grip_class": "weakly_gripped",
    }));
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        vec![finding],
    );

    if snapshot
        .classified_seam_for_diagnostic(&diagnostic)
        .is_some()
    {
        return Err("expected None for unknown seam_id".to_string());
    }
    if snapshot.finding_for_diagnostic(&diagnostic).is_some() {
        return Err(
            "expected None for finding_for_diagnostic when seam_id is set instead of finding_id"
                .to_string(),
        );
    }
    Ok(())
}

#[test]
fn given_finding_diagnostic_when_lookup_runs_then_finding_hover_path_still_resolves()
-> Result<(), String> {
    // Pre-4B Finding diagnostics still resolve through finding_for_diagnostic
    // even when the new seam-aware lookup is on the same snapshot.
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        vec![finding],
    );

    if snapshot
        .classified_seam_for_diagnostic(&diagnostic)
        .is_some()
    {
        return Err("Finding diagnostics carry finding_id, not seam_id; \
             classified_seam_for_diagnostic should return None"
            .to_string());
    }
    if snapshot.finding_for_diagnostic(&diagnostic).is_none() {
        return Err("expected Finding hover lookup to still work".to_string());
    }
    Ok(())
}

#[test]
fn refresh_plan_stores_latest_analysis_snapshot() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );

    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };
    let Some(latest) = backend.latest_analysis_snapshot() else {
        return Err("expected latest analysis snapshot".to_string());
    };

    assert_eq!(latest.root, PathBuf::from("/workspace"));
    assert_eq!(latest.base.as_deref(), Some("origin/main"));
    assert_eq!(latest.mode, Mode::Draft);
    assert_eq!(latest.findings.len(), 1);
    assert_eq!(latest.diagnostics_by_uri.len(), 1);
    Ok(())
}

#[test]
fn refresh_plan_stores_snapshot_refresh_metadata() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic],
        vec![finding],
    );
    diagnostics
        .snapshot
        .refresh
        .record_duration(Duration::from_millis(42));

    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };
    let Some(latest) = backend.latest_analysis_snapshot() else {
        return Err("expected latest analysis snapshot".to_string());
    };

    assert_eq!(latest.refresh.duration, Some(Duration::from_millis(42)));
    assert!(latest.refresh.age().is_some());
    assert_eq!(latest.diagnostic_count(), 1);
    assert_eq!(latest.diagnostic_uri_count(), 1);
    assert_eq!(latest.finding_count(), 1);
    assert_eq!(latest.seam_diagnostic_count(), 0);
    Ok(())
}

#[test]
fn refresh_completion_log_message_includes_duration_and_counts() -> Result<(), String> {
    let seam = sample_classified_seam();
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam];
    snapshot.refresh.record_duration(Duration::from_millis(17));

    let summary = RefreshLogSummary::from_snapshot(7, &snapshot);
    let message = refresh_completed_log_message(&summary, 1, 2);

    assert!(message.contains("ripr analysis refresh completed in 17 ms"));
    assert!(message.contains("generation=7"));
    assert!(message.contains("diagnostics=1"));
    assert!(message.contains("files=1"));
    assert!(message.contains("findings=0"));
    assert!(message.contains("preview_findings=0"));
    assert!(message.contains("static_limits=0"));
    assert!(message.contains("seam_diagnostics=1"));
    assert!(message.contains("gap_artifacts=0"));
    assert!(message.contains("actionable_gap_artifacts=0"));
    assert!(message.contains("preview_gap_artifacts=0"));
    assert!(message.contains("no_action_gap_artifacts=0"));
    assert!(message.contains("gap_static_limits=0"));
    assert!(message.contains("gap_artifact_rejections=0"));
    assert!(message.contains("gap_artifact_rejection_kinds="));
    assert!(message.contains("enabled_languages=1"));
    assert!(message.contains("enabled_language_names=rust"));
    assert!(message.contains("published_files=1"));
    assert!(message.contains("cleared_files=2"));
    Ok(())
}

#[test]
fn refresh_completion_log_message_counts_preview_findings_and_limits() -> Result<(), String> {
    let mut finding = sample_finding();
    finding.language = Some(LanguageId::Python);
    finding.language_status = Some(LanguageStatus::Preview);
    finding.static_limit_kind = Some(StaticLimitKind::MissingImportGraph);
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.py")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic],
        vec![finding],
    );

    let summary = RefreshLogSummary::from_snapshot(8, &snapshot);
    let message = refresh_completed_log_message(&summary, 1, 0);

    assert!(message.contains("preview_findings=1"));
    assert!(message.contains("static_limits=1"));
    Ok(())
}

#[test]
fn refresh_completion_log_message_counts_gap_artifact_state() -> Result<(), String> {
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &sample_finding());
    let uri = test_uri("file:///workspace/src/pricing.py")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic],
        Vec::new(),
    );
    snapshot.gap_artifacts.push(ValidatedGapArtifact {
        kind: GapArtifactKind::GapDecisionLedger,
        root: Some(".".to_string()),
        identities: vec![GapArtifactIdentity {
            canonical_gap_id: Some("gap:py:pricing".to_string()),
            seam_id: None,
            finding_id: None,
        }],
        language: Some(LanguageId::Python),
        language_status: Some(LanguageStatus::Preview),
        gap_state: Some("actionable".to_string()),
        related_paths: vec!["tests/test_pricing.py".to_string()],
        verify_commands: vec!["ripr agent verify --root . --json".to_string()],
        receipt_commands: vec!["ripr agent receipt --root . --json".to_string()],
        static_limit_kinds: vec!["missing_import_graph".to_string()],
        has_text_static_limit: false,
    });
    snapshot
        .gap_artifact_rejections
        .push(GapArtifactRejection::WrongRoot(
            "/other/workspace".to_string(),
        ));

    let summary = RefreshLogSummary::from_snapshot(9, &snapshot);
    let message = refresh_completed_log_message(&summary, 1, 0);

    assert!(message.contains("gap_artifacts=1"));
    assert!(message.contains("actionable_gap_artifacts=1"));
    assert!(message.contains("preview_gap_artifacts=1"));
    assert!(message.contains("no_action_gap_artifacts=0"));
    assert!(message.contains("gap_static_limits=1"));
    assert!(message.contains("gap_artifact_rejections=1"));
    assert!(message.contains("gap_artifact_rejection_kinds=wrong_root"));
    Ok(())
}

#[test]
fn refresh_completion_log_message_defaults_missing_duration_to_zero() -> Result<(), String> {
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic],
        vec![finding],
    );

    let summary = RefreshLogSummary::from_snapshot(3, &snapshot);
    let message = refresh_completed_log_message(&summary, 1, 0);

    assert!(message.contains("ripr analysis refresh completed in 0 ms"));
    Ok(())
}

#[test]
fn refresh_failure_log_message_includes_actionable_duration() {
    let message = refresh_failed_log_message(
        "workspace analysis failed: Cargo.toml not found",
        Duration::from_millis(9),
    );

    assert_eq!(
        message,
        "ripr analysis refresh failed after 9 ms: workspace analysis failed: Cargo.toml not found"
    );
}

#[test]
fn format_duration_renders_milliseconds_and_whole_seconds() {
    assert_eq!(format_duration(Duration::from_millis(9)), "9 ms");
    assert_eq!(format_duration(Duration::from_secs(1)), "1 second");
    assert_eq!(format_duration(Duration::from_secs(2)), "2 seconds");
}

#[test]
fn refresh_metadata_default_records_generation_time() {
    let metadata = RefreshMetadata::default();

    assert!(metadata.age().is_some());
    assert_eq!(metadata.duration, None);
}

#[test]
fn stale_refresh_generation_does_not_store_older_snapshot() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let Some(first_generation) = backend.next_refresh_generation() else {
        return Err("expected first generation".to_string());
    };
    let Some(second_generation) = backend.next_refresh_generation() else {
        return Err("expected second generation".to_string());
    };
    assert!(!backend.is_current_refresh_generation(first_generation));
    assert!(backend.is_current_refresh_generation(second_generation));

    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let current_uri = test_uri("file:///workspace/src/current.rs")?;
    let current = sample_workspace_diagnostics(
        PathBuf::from("/workspace/current"),
        current_uri,
        vec![diagnostic],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(current) else {
        return Err("expected current refresh plan".to_string());
    };

    if backend.is_current_refresh_generation(first_generation) {
        let stale = sample_workspace_diagnostics(
            PathBuf::from("/workspace/stale"),
            test_uri("file:///workspace/src/stale.rs")?,
            Vec::new(),
            Vec::new(),
        );
        let Some(_) = backend.refresh_plan(stale) else {
            return Err("expected stale refresh plan".to_string());
        };
    }

    let Some(latest) = backend.latest_analysis_snapshot() else {
        return Err("expected latest analysis snapshot".to_string());
    };
    assert_eq!(latest.root, PathBuf::from("/workspace/current"));
    Ok(())
}

#[test]
fn refresh_plan_rejects_mismatched_snapshot_and_batches() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let baseline = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding.clone()],
    );

    let Some(_) = backend.refresh_plan(baseline) else {
        return Err("expected baseline refresh plan".to_string());
    };
    let mismatched = WorkspaceDiagnostics {
        snapshot: sample_analysis_snapshot(
            PathBuf::from("/workspace"),
            uri.clone(),
            vec![diagnostic],
            vec![finding],
        ),
        batches: Vec::new(),
    };

    assert!(backend.refresh_plan(mismatched).is_none());
    let Some(latest) = backend.latest_analysis_snapshot() else {
        return Err("expected baseline snapshot to remain stored".to_string());
    };
    assert_eq!(latest.findings.len(), 1);
    assert_eq!(latest.diagnostics_by_uri.len(), 1);
    Ok(())
}

#[test]
fn code_action_response_keeps_current_commands() -> Result<(), String> {
    let mut finding = sample_finding();
    finding.related_tests.clear();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, None);

    let mut titles_kinds_and_commands = Vec::new();
    let mut command_arguments = Vec::new();
    for action in &actions {
        match action {
            CodeActionOrCommand::CodeAction(action) => {
                let Some(command) = &action.command else {
                    return Err("expected code action command".to_string());
                };
                let Some(kind) = &action.kind else {
                    return Err("expected code action kind".to_string());
                };
                titles_kinds_and_commands.push((
                    action.title.as_str(),
                    kind.as_str(),
                    command.title.as_str(),
                    command.command.as_str(),
                ));
                command_arguments.push(command.arguments.clone());
            }
            CodeActionOrCommand::Command(_) => {
                return Err("expected code action".to_string());
            }
        }
    }

    assert_eq!(
        titles_kinds_and_commands,
        vec![
            (
                "Inspect finding: copy context packet",
                "quickfix",
                "Inspect finding: copy context",
                COPY_CONTEXT_COMMAND,
            ),
            (
                "Refresh Analysis - Saved Workspace Check",
                "source",
                "Refresh Analysis - Saved Workspace Check",
                REFRESH_COMMAND,
            ),
        ]
    );
    let Some(Some(arguments)) = command_arguments.first() else {
        return Err("expected copy context arguments".to_string());
    };
    assert_eq!(arguments[0]["uri"], "file:///workspace/src/pricing.rs");
    assert_eq!(arguments[0]["line"], 88);
    assert_eq!(arguments[0]["finding_id"], "probe:pricing:88:predicate");
    assert_eq!(arguments[0]["probe_id"], "probe:pricing:88:predicate");
    Ok(())
}

#[test]
fn code_action_response_omits_context_action_without_ripr_diagnostic() -> Result<(), String> {
    let actions = code_action_response(&code_action_params(Vec::new())?, None);

    assert_eq!(actions.len(), 1);
    let CodeActionOrCommand::CodeAction(action) = &actions[0] else {
        return Err("expected code action".to_string());
    };
    let Some(command) = &action.command else {
        return Err("expected refresh command".to_string());
    };
    assert_eq!(command.command, REFRESH_COMMAND);
    Ok(())
}

#[test]
fn gap_code_actions_surface_bounded_repair_actions_when_artifact_is_valid() -> Result<(), String> {
    let root = unique_lsp_test_root("gap-actions")?;
    std::fs::create_dir_all(root.path().join("src"))
        .map_err(|err| format!("create src failed: {err}"))?;
    std::fs::create_dir_all(root.path().join("tests"))
        .map_err(|err| format!("create tests failed: {err}"))?;
    std::fs::write(
        root.path().join("tests/test_pricing.py"),
        "def test_discount_boundary():\n    assert price(10) == 9\n",
    )
    .map_err(|err| format!("write related test failed: {err}"))?;
    let uri = file_uri_for_path(&root.path().join("src/pricing.py"))?;
    let diagnostic = gap_action_diagnostic();
    let mut snapshot = sample_analysis_snapshot(
        root.path().to_path_buf(),
        uri.clone(),
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.gap_artifacts = vec![validated_gap_artifact()];

    let actions = code_action_response(
        &code_action_params_for(uri, diagnostic.range.start.line, vec![diagnostic])?,
        Some(&snapshot),
    );
    let commands = code_action_commands(&actions)?;

    assert_eq!(
        commands
            .iter()
            .map(|(title, command, _)| (title.as_str(), command.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("Copy first repair packet", COPY_CONTEXT_COMMAND),
            ("Inspect gap: copy repair packet", COPY_CONTEXT_COMMAND),
            (
                "Write targeted test: open best related test",
                OPEN_RELATED_TEST_COMMAND
            ),
            (
                "Verify after test: copy verify command",
                COPY_AGENT_VERIFY_COMMAND
            ),
            (
                "Review result: copy receipt command",
                COPY_AGENT_RECEIPT_COMMAND
            ),
            ("Inspect gap: copy static-limit note", COPY_CONTEXT_COMMAND),
            ("Refresh Analysis - Saved Workspace Check", REFRESH_COMMAND),
        ]
    );
    assert_eq!(commands[0].2[0]["label"], "first_repair_packet");
    assert_eq!(commands[0].2[0]["gap_identity"], "gap:py:pricing");
    assert_eq!(commands[0].2[0]["canonical_gap_id"], "gap:py:pricing");
    assert_eq!(
        commands[0].2[0]["verify_command"],
        "ripr agent verify --root . --json"
    );
    assert_eq!(
        commands[0].2[0]["receipt_command"],
        "ripr agent receipt --root . --json"
    );
    let packet = commands[0].2[0]["packet"]
        .as_str()
        .ok_or_else(|| "missing first repair packet text".to_string())?;
    assert!(
        packet.contains("RIPR first repair packet")
            && packet.contains("Language status: preview")
            && packet.contains("Static limit: missing_import_graph")
            && packet.contains("Suggested action:")
            && packet.contains("Verify command:")
            && packet.contains("Receipt command:")
            && packet
                .contains("Do not edit production code unless the packet explicitly scopes it."),
        "unexpected first repair packet:\n{packet}"
    );
    let static_limit_position = packet
        .find("Static limit: missing_import_graph")
        .ok_or_else(|| format!("missing static limit in first repair packet:\n{packet}"))?;
    let suggested_action_position = packet
        .find("Suggested action:")
        .ok_or_else(|| format!("missing suggested action in first repair packet:\n{packet}"))?;
    assert!(
        static_limit_position < suggested_action_position,
        "static limits must appear before action language:\n{packet}"
    );
    assert_eq!(commands[1].2[0]["label"], "gap_repair_packet");
    assert_eq!(commands[1].2[0]["canonical_gap_id"], "gap:py:pricing");
    assert_eq!(
        commands[1].2[0]["repair_route"]["related_test"],
        "tests/test_pricing.py::test_discount_boundary"
    );
    assert_eq!(
        commands[2].2[0]["uri"],
        file_uri_for_path(&root.path().join("tests/test_pricing.py"))?.as_str()
    );
    assert_eq!(commands[2].2[0]["line"], 2);
    assert_eq!(commands[2].2[0]["test_name"], "test_discount_boundary");
    assert_eq!(commands[3].2[0]["label"], "gap_verify");
    assert_eq!(
        commands[3].2[0]["command"],
        "ripr agent verify --root . --json"
    );
    assert_eq!(commands[4].2[0]["label"], "gap_receipt");
    assert_eq!(
        commands[4].2[0]["command"],
        "ripr agent receipt --root . --json"
    );
    assert!(
        commands[5].2[0]["note"]
            .as_str()
            .is_some_and(|note| note.contains("Static limit: missing_import_graph")),
        "expected static-limit note, got {:?}",
        commands[5].2[0]
    );
    Ok(())
}

#[test]
fn gap_code_actions_suppress_first_repair_packet_without_verify_or_receipt_command()
-> Result<(), String> {
    let root = unique_lsp_test_root("gap-first-repair-requires-commands")?;
    std::fs::create_dir_all(root.path().join("tests"))
        .map_err(|err| format!("create tests failed: {err}"))?;
    std::fs::write(
        root.path().join("tests/test_pricing.py"),
        "def test_discount_boundary():\n    assert price(10) == 9\n",
    )
    .map_err(|err| format!("write related test failed: {err}"))?;
    let uri = file_uri_for_path(&root.path().join("src/pricing.py"))?;
    let mut diagnostic = gap_action_diagnostic();
    let data = diagnostic
        .data
        .as_mut()
        .ok_or_else(|| "missing diagnostic data".to_string())?;
    data.as_object_mut()
        .ok_or_else(|| "expected object data".to_string())?
        .remove("receipt_command");
    let mut snapshot = sample_analysis_snapshot(
        root.path().to_path_buf(),
        uri.clone(),
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.gap_artifacts = vec![validated_gap_artifact()];

    let actions = code_action_response(
        &code_action_params_for(uri, diagnostic.range.start.line, vec![diagnostic])?,
        Some(&snapshot),
    );
    let commands = code_action_commands(&actions)?;

    assert!(
        commands
            .iter()
            .all(|(title, _, args)| title != "Copy first repair packet"
                && args
                    .first()
                    .is_none_or(|arg| arg["label"] != "first_repair_packet")),
        "first repair packet must be suppressed when receipt command is missing: {commands:?}"
    );
    assert!(
        commands
            .iter()
            .any(|(title, _, _)| title == "Inspect gap: copy repair packet"),
        "existing inspect action should remain available"
    );
    Ok(())
}

#[test]
fn gap_code_actions_fail_closed_without_valid_current_artifact() -> Result<(), String> {
    let diagnostic = gap_action_diagnostic();
    let uri = test_uri("file:///workspace/src/pricing.py")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        Vec::new(),
    );

    let actions = code_action_response(
        &code_action_params_for(uri, diagnostic.range.start.line, vec![diagnostic])?,
        Some(&snapshot),
    );
    let commands = code_action_commands(&actions)?;

    assert_eq!(
        commands
            .iter()
            .map(|(title, command, _)| (title.as_str(), command.as_str()))
            .collect::<Vec<_>>(),
        vec![("Refresh Analysis - Saved Workspace Check", REFRESH_COMMAND)],
        "stale or unvalidated gap diagnostics must not expose repair actions"
    );
    Ok(())
}

#[test]
fn gap_code_actions_omit_unsafe_related_paths_and_commands() -> Result<(), String> {
    let root = unique_lsp_test_root("gap-unsafe-actions")?;
    let uri = file_uri_for_path(&root.path().join("src/pricing.py"))?;
    let mut diagnostic = gap_action_diagnostic();
    let data = diagnostic
        .data
        .as_mut()
        .ok_or_else(|| "missing diagnostic data".to_string())?;
    data["repair_route"]["related_test"] = serde_json::json!("../outside.py::test_escape");
    data["verification_commands"] =
        serde_json::json!(["ripr agent verify --root ../outside --json"]);
    data["receipt_command"] = serde_json::json!("ripr agent receipt --root ../outside --json");
    data.as_object_mut()
        .ok_or_else(|| "expected object data".to_string())?
        .remove("static_limit_kind");
    data.as_object_mut()
        .ok_or_else(|| "expected object data".to_string())?
        .remove("static_limit_detail");
    let mut snapshot = sample_analysis_snapshot(
        root.path().to_path_buf(),
        uri.clone(),
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.gap_artifacts = vec![validated_gap_artifact()];

    let actions = code_action_response(
        &code_action_params_for(uri, diagnostic.range.start.line, vec![diagnostic])?,
        Some(&snapshot),
    );
    let commands = code_action_commands(&actions)?;

    assert_eq!(
        commands
            .iter()
            .map(|(title, command, _)| (title.as_str(), command.as_str()))
            .collect::<Vec<_>>(),
        vec![("Refresh Analysis - Saved Workspace Check", REFRESH_COMMAND)],
        "unsafe gap paths or command roots must leave refresh as the only action"
    );
    Ok(())
}

#[test]
fn seam_code_actions_surface_packet_assertion_related_test_and_refresh() -> Result<(), String> {
    let seam = sample_classified_seam();
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam.clone()];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    assert_eq!(
        commands
            .iter()
            .map(|(_, command, _)| command.as_str())
            .collect::<Vec<_>>(),
        vec![
            COPY_CONTEXT_COMMAND,
            COPY_TARGETED_TEST_BRIEF_COMMAND,
            COPY_AGENT_PACKET_COMMAND,
            COPY_AGENT_BRIEF_COMMAND,
            COPY_AFTER_SNAPSHOT_COMMAND,
            COPY_AGENT_VERIFY_COMMAND,
            COPY_AGENT_RECEIPT_COMMAND,
            COPY_SUGGESTED_ASSERTION_COMMAND,
            OPEN_RELATED_TEST_COMMAND,
            REFRESH_COMMAND,
        ]
    );
    assert_eq!(commands[0].0, "Inspect Test Gap - Copy Context");
    assert_eq!(commands[0].2[0]["seam_id"], seam.seam.id().as_str());
    assert_eq!(commands[0].2[0]["seam_kind"], "predicate_boundary");
    assert_eq!(commands[0].2[0]["line"], 88);
    assert_eq!(commands[1].0, "Write targeted test: copy brief");
    assert_eq!(commands[1].2[0]["seam_id"], seam.seam.id().as_str());
    assert!(
        commands[1].2[0]["brief"]
            .as_str()
            .is_some_and(|value| value.contains("Add a targeted test:")),
        "expected targeted test brief argument, got {:?}",
        commands[1].2
    );
    assert_eq!(commands[2].0, "Agent handoff: copy packet command");
    assert_eq!(commands[2].2[0]["label"], "agent_packet");
    assert_eq!(commands[2].2[0]["root"], ".");
    assert_eq!(commands[2].2[0]["base"], "origin/main");
    assert_eq!(commands[2].2[0]["mode"], "draft");
    assert_eq!(commands[2].2[0]["seam_id"], seam.seam.id().as_str());
    assert_eq!(commands[2].2[0]["seam_kind"], "predicate_boundary");
    assert_eq!(commands[2].2[0]["seam_file"], "src/pricing.rs");
    assert_eq!(commands[2].2[0]["owner"], "pricing::discounted_total");
    assert_eq!(commands[2].2[0]["line"], 88);
    assert_eq!(commands[2].2[0]["severity"], "warning");
    assert_eq!(
        commands[2].2[0]["target_artifact"],
        "target/ripr/agent/agent-packet.json"
    );
    assert_eq!(
        commands[2].2[0]["command"],
        format!(
            "ripr agent packet --root . --seam-id {} --json > target/ripr/agent/agent-packet.json",
            seam.seam.id().as_str()
        )
    );
    assert_eq!(commands[3].0, "Agent handoff: copy brief command");
    assert_eq!(
        commands[3].2[0]["command"],
        format!(
            "ripr agent brief --root . --seam-id {} --json > target/ripr/agent/agent-brief.json",
            seam.seam.id().as_str()
        )
    );
    assert_eq!(
        commands[4].0,
        "Verify after test: copy after-snapshot command"
    );
    assert_eq!(
        commands[4].2[0]["command"],
        "ripr check --root . --base origin/main --mode draft --format repo-exposure-json > target/ripr/pilot/after.repo-exposure.json"
    );
    assert_eq!(commands[5].0, "Verify after test: copy verify command");
    assert_eq!(
        commands[5].2[0]["command"],
        "ripr agent verify --root . --before target/ripr/pilot/repo-exposure.json --after target/ripr/pilot/after.repo-exposure.json --json > target/ripr/agent/agent-verify.json"
    );
    assert_eq!(commands[6].0, "Review result: copy receipt command");
    assert_eq!(
        commands[6].2[0]["command"],
        format!(
            "ripr agent receipt --root . --verify-json target/ripr/agent/agent-verify.json --seam-id {} --json --out target/ripr/agent/agent-receipt.json",
            seam.seam.id().as_str()
        )
    );
    assert_eq!(
        commands[7].0,
        "Write targeted test: copy suggested assertion"
    );
    assert!(
        commands[7].2[0]["assertion"]
            .as_str()
            .is_some_and(|value| value.contains("assert_eq!(discounted_total")),
        "expected assertion argument, got {:?}",
        commands[7].2
    );
    assert_eq!(commands[8].0, "Write targeted test: open best related test");
    assert_eq!(
        commands[8].2[0]["uri"],
        "file:///workspace/tests/pricing.rs"
    );
    assert_eq!(commands[8].2[0]["line"], 12);
    Ok(())
}

#[test]
fn agent_loop_command_payloads_stay_workspace_relative_for_platform_roots() -> Result<(), String> {
    let seam = sample_classified_seam();
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from(r"workspace root\ripr workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.base = Some("origin/main with space".to_string());
    snapshot.mode = Mode::Ready;
    snapshot.classified_seams = vec![seam.clone()];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    let expected_commands = [
        (
            COPY_AGENT_PACKET_COMMAND,
            "agent_packet",
            "target/ripr/agent/agent-packet.json",
            format!(
                "ripr agent packet --root . --seam-id {} --json > target/ripr/agent/agent-packet.json",
                seam.seam.id().as_str()
            ),
        ),
        (
            COPY_AGENT_BRIEF_COMMAND,
            "agent_brief",
            "target/ripr/agent/agent-brief.json",
            format!(
                "ripr agent brief --root . --seam-id {} --json > target/ripr/agent/agent-brief.json",
                seam.seam.id().as_str()
            ),
        ),
        (
            COPY_AFTER_SNAPSHOT_COMMAND,
            "after_snapshot",
            "target/ripr/pilot/after.repo-exposure.json",
            "ripr check --root . --base \"origin/main with space\" --mode ready --format repo-exposure-json > target/ripr/pilot/after.repo-exposure.json"
                .to_string(),
        ),
        (
            COPY_AGENT_VERIFY_COMMAND,
            "agent_verify",
            "target/ripr/agent/agent-verify.json",
            "ripr agent verify --root . --before target/ripr/pilot/repo-exposure.json --after target/ripr/pilot/after.repo-exposure.json --json > target/ripr/agent/agent-verify.json"
                .to_string(),
        ),
        (
            COPY_AGENT_RECEIPT_COMMAND,
            "agent_receipt",
            "target/ripr/agent/agent-receipt.json",
            format!(
                "ripr agent receipt --root . --verify-json target/ripr/agent/agent-verify.json --seam-id {} --json --out target/ripr/agent/agent-receipt.json",
                seam.seam.id().as_str()
            ),
        ),
    ];

    for (command_id, label, target_artifact, expected_command) in expected_commands {
        let argument = commands
            .iter()
            .find(|(_, command, _)| command == command_id)
            .and_then(|(_, _, arguments)| arguments.first())
            .ok_or_else(|| format!("missing command payload for {command_id}"))?;
        assert_eq!(argument["label"], label);
        assert_eq!(argument["root"], ".");
        assert_eq!(argument["base"], "origin/main with space");
        assert_eq!(argument["mode"], "ready");
        assert_eq!(argument["seam_id"], seam.seam.id().as_str());
        assert_eq!(argument["seam_file"], "src/pricing.rs");
        assert_eq!(argument["owner"], "pricing::discounted_total");
        assert_eq!(argument["severity"], "warning");
        assert_eq!(argument["target_artifact"], target_artifact);
        assert_eq!(argument["command"], expected_command);
        let copied = argument["command"]
            .as_str()
            .ok_or_else(|| "expected command string".to_string())?;
        assert!(
            !copied.contains('\\'),
            "copied commands should use workspace-relative slash paths, got {copied}"
        );
        assert!(
            !copied.contains("ripr workspace"),
            "copied commands should not leak platform-specific workspace roots, got {copied}"
        );
    }
    Ok(())
}

#[test]
fn seam_code_actions_fail_closed_for_stale_seam_diagnostic() -> Result<(), String> {
    let seam = sample_classified_seam();
    let mut diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    diagnostic.data = Some(serde_json::json!({
        "schema_version": "0.1",
        "seam_id": "deadbeef00000000",
        "seam_kind": "predicate_boundary",
    }));
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    assert_eq!(
        commands
            .iter()
            .map(|(title, command, _)| (title.as_str(), command.as_str()))
            .collect::<Vec<_>>(),
        vec![("Refresh Analysis - Saved Workspace Check", REFRESH_COMMAND)]
    );
    Ok(())
}

#[test]
fn seam_code_actions_keep_legacy_finding_context_when_both_diagnostics_are_present()
-> Result<(), String> {
    let seam = sample_classified_seam();
    let seam_diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let finding_diagnostic = diagnostic_for_finding(Path::new("/workspace"), &sample_finding());
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![seam_diagnostic.clone(), finding_diagnostic.clone()],
        vec![sample_finding()],
    );
    snapshot.classified_seams = vec![seam.clone()];
    let actions = code_action_response(
        &code_action_params(vec![seam_diagnostic, finding_diagnostic])?,
        Some(&snapshot),
    );

    let commands = code_action_commands(&actions)?;
    assert_eq!(
        commands
            .iter()
            .map(|(title, _, _)| title.as_str())
            .collect::<Vec<_>>(),
        vec![
            "Inspect Test Gap - Copy Context",
            "Write targeted test: copy brief",
            "Agent handoff: copy packet command",
            "Agent handoff: copy brief command",
            "Verify after test: copy after-snapshot command",
            "Verify after test: copy verify command",
            "Review result: copy receipt command",
            "Write targeted test: copy suggested assertion",
            "Write targeted test: open best related test",
            "Inspect finding: copy context packet",
            "Refresh Analysis - Saved Workspace Check",
        ]
    );
    assert_eq!(commands[0].2[0]["seam_id"], seam.seam.id().as_str());
    assert_eq!(commands[9].2[0]["finding_id"], "probe:pricing:88:predicate");
    assert_eq!(commands[9].2[0]["probe_id"], "probe:pricing:88:predicate");
    Ok(())
}

#[test]
fn seam_code_actions_open_strong_related_test_before_first_related_test() -> Result<(), String> {
    use crate::analysis::test_grip_evidence::{
        RelatedTestGrip, RelationConfidence, RelationReason,
    };

    let mut seam = sample_classified_seam();
    seam.evidence.related_tests = vec![
        RelatedTestGrip {
            test_name: "nearby_smoke_reaches_owner".to_string(),
            file: PathBuf::from("tests/smoke.rs"),
            line: 7,
            oracle_kind: OracleKind::SmokeOnly,
            oracle_strength: OracleStrength::Smoke,
            evidence_summary: "smoke-only assertion".to_string(),
            relation_reason: RelationReason::DirectOwnerCall,
            relation_confidence: RelationConfidence::High,
        },
        RelatedTestGrip {
            test_name: "below_threshold_has_no_discount".to_string(),
            file: PathBuf::from("tests/pricing.rs"),
            line: 12,
            oracle_kind: OracleKind::ExactValue,
            oracle_strength: OracleStrength::Strong,
            evidence_summary: "exact value assertion".to_string(),
            relation_reason: RelationReason::DirectOwnerCall,
            relation_confidence: RelationConfidence::Medium,
        },
    ];
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    let Some((_, command, args)) = commands
        .iter()
        .find(|(title, _, _)| title == "Write targeted test: open best related test")
    else {
        return Err(format!(
            "expected open related test action, got {commands:?}"
        ));
    };

    assert_eq!(command, OPEN_RELATED_TEST_COMMAND);
    assert_eq!(args[0]["uri"], "file:///workspace/tests/pricing.rs");
    assert_eq!(args[0]["test_name"], "below_threshold_has_no_discount");
    Ok(())
}

#[test]
fn seam_code_actions_open_highest_confidence_related_test_when_no_strong_test_exists()
-> Result<(), String> {
    use crate::analysis::test_grip_evidence::{
        RelatedTestGrip, RelationConfidence, RelationReason,
    };

    let mut seam = sample_classified_seam();
    seam.evidence.related_tests = vec![
        RelatedTestGrip {
            test_name: "opaque_fixture_hint".to_string(),
            file: PathBuf::from("tests/opaque.rs"),
            line: 3,
            oracle_kind: OracleKind::Unknown,
            oracle_strength: OracleStrength::None,
            evidence_summary: "opaque relation".to_string(),
            relation_reason: RelationReason::FixtureOwnerAffinity,
            relation_confidence: RelationConfidence::Opaque,
        },
        RelatedTestGrip {
            test_name: "low_confidence_smoke".to_string(),
            file: PathBuf::from("tests/low.rs"),
            line: 5,
            oracle_kind: OracleKind::SmokeOnly,
            oracle_strength: OracleStrength::Smoke,
            evidence_summary: "smoke-only assertion".to_string(),
            relation_reason: RelationReason::FixtureOwnerAffinity,
            relation_confidence: RelationConfidence::Low,
        },
        RelatedTestGrip {
            test_name: "medium_confidence_property".to_string(),
            file: PathBuf::from("tests/medium.rs"),
            line: 9,
            oracle_kind: OracleKind::RelationalCheck,
            oracle_strength: OracleStrength::Medium,
            evidence_summary: "medium oracle".to_string(),
            relation_reason: RelationReason::SameModule,
            relation_confidence: RelationConfidence::Medium,
        },
        RelatedTestGrip {
            test_name: "high_confidence_weak_assertion".to_string(),
            file: PathBuf::from("tests/high.rs"),
            line: 11,
            oracle_kind: OracleKind::RelationalCheck,
            oracle_strength: OracleStrength::Weak,
            evidence_summary: "weak oracle".to_string(),
            relation_reason: RelationReason::DirectOwnerCall,
            relation_confidence: RelationConfidence::High,
        },
    ];
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    let Some((_, command, args)) = commands
        .iter()
        .find(|(title, _, _)| title == "Write targeted test: open best related test")
    else {
        return Err(format!(
            "expected open related test action, got {commands:?}"
        ));
    };

    assert_eq!(command, OPEN_RELATED_TEST_COMMAND);
    assert_eq!(args[0]["uri"], "file:///workspace/tests/high.rs");
    assert_eq!(args[0]["test_name"], "high_confidence_weak_assertion");
    Ok(())
}

#[test]
fn seam_code_actions_omit_assertion_and_related_test_when_evidence_is_missing() -> Result<(), String>
{
    let seam = sample_side_effect_seam_without_related_tests();
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/service.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    assert_eq!(
        commands
            .iter()
            .map(|(_, command, _)| command.as_str())
            .collect::<Vec<_>>(),
        vec![
            COPY_CONTEXT_COMMAND,
            COPY_AGENT_PACKET_COMMAND,
            COPY_AGENT_BRIEF_COMMAND,
            COPY_AFTER_SNAPSHOT_COMMAND,
            COPY_AGENT_VERIFY_COMMAND,
            COPY_AGENT_RECEIPT_COMMAND,
            REFRESH_COMMAND
        ]
    );
    assert_eq!(commands[0].0, "Inspect Test Gap - Copy Context");
    assert_eq!(commands[1].0, "Agent handoff: copy packet command");
    assert_eq!(commands[5].0, "Review result: copy receipt command");
    Ok(())
}

#[test]
fn seam_code_actions_keep_targeted_brief_when_related_test_exists_without_assertion()
-> Result<(), String> {
    use crate::analysis::test_grip_evidence::{
        RelatedTestGrip, RelationConfidence, RelationReason,
    };

    let mut seam = sample_side_effect_seam_without_related_tests();
    seam.evidence.related_tests = vec![RelatedTestGrip {
        test_name: "publish_event_emits_bus_message".to_string(),
        file: PathBuf::from("tests/service.rs"),
        line: 21,
        oracle_kind: OracleKind::SmokeOnly,
        oracle_strength: OracleStrength::Smoke,
        evidence_summary: "related smoke test reaches event publishing".to_string(),
        relation_reason: RelationReason::DirectOwnerCall,
        relation_confidence: RelationConfidence::High,
    }];
    let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = test_uri("file:///workspace/src/service.rs")?;
    let mut snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri,
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.classified_seams = vec![seam];
    let actions = code_action_response(&code_action_params(vec![diagnostic])?, Some(&snapshot));

    let commands = code_action_commands(&actions)?;
    assert!(
        commands
            .iter()
            .any(|(_, command, _)| command == COPY_TARGETED_TEST_BRIEF_COMMAND),
        "expected targeted-test brief action when a related test exists, got {commands:?}"
    );
    assert!(
        commands
            .iter()
            .all(|(_, command, _)| command != COPY_SUGGESTED_ASSERTION_COMMAND),
        "expected no suggested assertion action for prose-only side-effect guidance, got {commands:?}"
    );
    let Some((_, command, args)) = commands
        .iter()
        .find(|(title, _, _)| title == "Write targeted test: open best related test")
    else {
        return Err(format!(
            "expected open related test action, got {commands:?}"
        ));
    };
    assert_eq!(command, OPEN_RELATED_TEST_COMMAND);
    assert_eq!(args[0]["uri"], "file:///workspace/tests/service.rs");
    assert_eq!(args[0]["line"], 21);
    Ok(())
}

#[test]
fn boundary_gap_lsp_diagnostics_match_fixture_expectation() -> Result<(), String> {
    let (diagnostics, _) = boundary_gap_lsp_fixture_outputs()?;
    assert_json_fixture("lsp-diagnostics.json", diagnostics)
}

#[test]
fn boundary_gap_lsp_code_actions_match_fixture_expectation() -> Result<(), String> {
    let (_, actions) = boundary_gap_lsp_fixture_outputs()?;
    assert_json_fixture("lsp-code-actions.json", actions)
}

#[test]
fn diagnostic_for_finding_preserves_lsp_payload_shape() -> Result<(), String> {
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    assert_eq!(diagnostic.range.start.line, 87);
    assert_eq!(diagnostic.range.start.character, 0);
    assert_eq!(diagnostic.range.end.line, 87);
    assert_eq!(diagnostic.range.end.character, 19);
    assert_eq!(diagnostic.severity, Some(DiagnosticSeverity::WARNING));
    assert_eq!(
        diagnostic.code,
        Some(NumberOrString::String("weakly_exposed".to_string()))
    );
    assert_eq!(diagnostic.source.as_deref(), Some("ripr"));
    assert_eq!(diagnostic.message, "Add an exact boundary assertion.");
    let Some(data) = diagnostic.data else {
        return Err("expected diagnostic data".to_string());
    };
    assert_eq!(data["schema_version"], "0.1");
    assert_eq!(data["finding_id"], "probe:pricing:88:predicate");
    assert_eq!(data["probe_id"], "probe:pricing:88:predicate");
    assert_eq!(data["classification"], "weakly_exposed");
    assert_eq!(data["probe_family"], "predicate");
    assert_eq!(data["confidence"], 0.75);
    assert_eq!(data["source_range"]["file"], "src/pricing.rs");
    assert_eq!(data["source_range"]["line"], 88);
    assert_eq!(data["source_range"]["column"], 1);
    Ok(())
}

#[test]
fn diagnostic_for_finding_uses_probe_column_and_expression_width() {
    let mut finding = sample_finding();
    finding.probe.location.column = 5;
    finding.probe.expression = "total".to_string();

    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    assert_eq!(diagnostic.range.start.line, 87);
    assert_eq!(diagnostic.range.start.character, 4);
    assert_eq!(diagnostic.range.end.line, 87);
    assert_eq!(diagnostic.range.end.character, 9);
}

#[test]
fn diagnostic_for_finding_uses_one_character_range_for_empty_expression() {
    let mut finding = sample_finding();
    finding.probe.location.column = 3;
    finding.probe.expression.clear();

    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    assert_eq!(diagnostic.range.start.character, 2);
    assert_eq!(diagnostic.range.end.character, 3);
}

#[test]
fn diagnostic_for_finding_attaches_related_test_information() -> Result<(), String> {
    let mut finding = sample_finding();
    finding.related_tests.push(RelatedTest {
        name: "discount_boundary_is_exact".to_string(),
        file: PathBuf::from("tests/pricing.rs"),
        line: 12,
        oracle: Some("assert_eq!(total, expected)".to_string()),
        oracle_kind: OracleKind::ExactValue,
        oracle_strength: OracleStrength::Strong,
    });

    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let Some(related) = diagnostic.related_information else {
        return Err("expected related diagnostic information".to_string());
    };

    assert_eq!(related.len(), 1);
    assert_eq!(
        related[0].location.uri.as_str(),
        "file:///workspace/tests/pricing.rs"
    );
    assert_eq!(related[0].location.range.start.line, 11);
    assert_eq!(
        related[0].message,
        "Related test `discount_boundary_is_exact` has strong oracle: assert_eq!(total, expected)"
    );
    Ok(())
}

#[test]
fn diagnostic_severity_tracks_static_exposure_class() {
    let cases = [
        (ExposureClass::Exposed, DiagnosticSeverity::INFORMATION),
        (ExposureClass::WeaklyExposed, DiagnosticSeverity::WARNING),
        (
            ExposureClass::ReachableUnrevealed,
            DiagnosticSeverity::WARNING,
        ),
        (ExposureClass::NoStaticPath, DiagnosticSeverity::WARNING),
        (ExposureClass::InfectionUnknown, DiagnosticSeverity::WARNING),
        (
            ExposureClass::PropagationUnknown,
            DiagnosticSeverity::INFORMATION,
        ),
        (
            ExposureClass::StaticUnknown,
            DiagnosticSeverity::INFORMATION,
        ),
    ];

    for (class, expected) in cases {
        assert_eq!(diagnostic_severity_for_class(&class), expected);
    }
}

#[test]
fn diagnostic_refresh_plan_clears_stale_previous_uris() -> Result<(), String> {
    let stale_uri = test_uri("file:///workspace/src/stale.rs")?;
    let current_uri = test_uri("file:///workspace/src/current.rs")?;
    let mut previous_uris = BTreeSet::new();
    previous_uris.insert(stale_uri.clone());
    previous_uris.insert(current_uri.clone());

    let plan = diagnostic_refresh_plan(
        &previous_uris,
        vec![DiagnosticBatch {
            uri: current_uri.clone(),
            diagnostics: Vec::new(),
        }],
    );

    assert_eq!(plan.publish_batches.len(), 1);
    assert_eq!(plan.publish_batches[0].uri, current_uri);
    assert_eq!(plan.clear_uris, vec![stale_uri]);
    assert_eq!(plan.current_uris.len(), 1);
    Ok(())
}

#[test]
fn take_all_uris_returns_and_clears_previous_diagnostic_uris() -> Result<(), String> {
    let first_uri = test_uri("file:///workspace/src/first.rs")?;
    let second_uri = test_uri("file:///workspace/src/second.rs")?;
    let mut uris = BTreeSet::new();
    uris.insert(first_uri.clone());
    uris.insert(second_uri.clone());

    let cleared = take_all_uris(&mut uris);

    assert_eq!(cleared, vec![first_uri, second_uri]);
    assert!(uris.is_empty());
    Ok(())
}

#[test]
fn refresh_failure_clear_helper_clears_tracked_diagnostics() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let tracked_uri = test_uri("file:///workspace/src/stale.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        tracked_uri.clone(),
        Vec::new(),
        Vec::new(),
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };
    assert!(backend.latest_analysis_snapshot().is_some());

    assert_eq!(backend.clear_all_diagnostic_uris(), vec![tracked_uri]);

    assert!(backend.clear_all_diagnostic_uris().is_empty());
    assert!(backend.latest_analysis_snapshot().is_none());
    Ok(())
}

#[test]
fn refresh_generation_marks_older_requests_stale() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();

    let Some(first) = backend.next_refresh_generation() else {
        return Err("expected first refresh generation".to_string());
    };
    assert!(backend.is_current_refresh_generation(first));

    let Some(second) = backend.next_refresh_generation() else {
        return Err("expected second refresh generation".to_string());
    };

    assert!(!backend.is_current_refresh_generation(first));
    assert!(backend.is_current_refresh_generation(second));
    Ok(())
}

#[test]
fn refresh_diagnostics_advances_generation_before_analysis() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();

    let Some(generation) = backend.next_refresh_generation() else {
        return Err("expected refresh generation".to_string());
    };

    assert_eq!(generation, 1);
    assert!(backend.is_current_refresh_generation(generation));
    assert!(backend.latest_analysis_snapshot().is_none());
    Ok(())
}

#[test]
fn document_store_tracks_open_change_and_close() -> Result<(), String> {
    let uri = test_uri("file:///workspace/src/lib.rs")?;
    let mut store = DocumentStore::default();

    store.open(DidOpenTextDocumentParams {
        text_document: TextDocumentItem::new(
            uri.clone(),
            "rust".to_string(),
            1,
            "fn old() {}".to_string(),
        ),
    });

    let Some(opened) = store.documents.get(&uri) else {
        return Err("expected opened document".to_string());
    };
    assert_eq!(opened.path, PathBuf::from("/workspace/src/lib.rs"));
    assert_eq!(opened.version, Some(1));
    assert_eq!(opened.text, "fn old() {}");

    store.change(DidChangeTextDocumentParams {
        text_document: VersionedTextDocumentIdentifier::new(uri.clone(), 2),
        content_changes: vec![TextDocumentContentChangeEvent {
            range: None,
            range_length: None,
            text: "fn new() {}".to_string(),
        }],
    });

    let Some(changed) = store.documents.get(&uri) else {
        return Err("expected changed document".to_string());
    };
    assert_eq!(changed.version, Some(2));
    assert_eq!(changed.text, "fn new() {}");

    store.close(DidCloseTextDocumentParams {
        text_document: TextDocumentIdentifier::new(uri.clone()),
    });

    assert!(!store.documents.contains_key(&uri));
    Ok(())
}

#[test]
fn document_store_creates_document_from_full_change_when_missing() -> Result<(), String> {
    let uri = test_uri("file:///workspace/src/lib.rs")?;
    let mut store = DocumentStore::default();

    store.change(DidChangeTextDocumentParams {
        text_document: VersionedTextDocumentIdentifier::new(uri.clone(), 7),
        content_changes: vec![TextDocumentContentChangeEvent {
            range: None,
            range_length: None,
            text: "fn discovered() {}".to_string(),
        }],
    });

    let Some(document) = store.documents.get(&uri) else {
        return Err("expected document from full change".to_string());
    };
    assert_eq!(document.version, Some(7));
    assert_eq!(document.text, "fn discovered() {}");
    Ok(())
}

#[test]
fn initialize_root_prefers_first_workspace_folder() -> Result<(), String> {
    let fallback = PathBuf::from("/fallback");
    let params = initialize_params(
        Some(vec![
            WorkspaceFolder {
                uri: test_uri("file:///workspace/main")?,
                name: "main".to_string(),
            },
            WorkspaceFolder {
                uri: test_uri("file:///workspace/other")?,
                name: "other".to_string(),
            },
        ]),
        Some(test_uri("file:///workspace/root-uri")?),
    );

    let root = root_from_initialize_params(&params, &fallback);

    assert_eq!(root, PathBuf::from("/workspace/main"));
    Ok(())
}

#[test]
fn initialize_root_uses_root_uri_when_workspace_folders_are_missing() -> Result<(), String> {
    let fallback = PathBuf::from("/fallback");
    let params = initialize_params(None, Some(test_uri("file:///workspace/root-uri")?));

    let root = root_from_initialize_params(&params, &fallback);

    assert_eq!(root, PathBuf::from("/workspace/root-uri"));
    Ok(())
}

#[test]
fn initialize_root_falls_back_to_process_cwd_when_no_lsp_root_exists() {
    let fallback = PathBuf::from("/fallback");
    let params = initialize_params(None, None);

    let root = root_from_initialize_params(&params, &fallback);

    assert_eq!(root, fallback);
}

#[test]
fn initialization_options_override_lsp_analysis_config() {
    let mut params = initialize_params(None, None);
    params.initialization_options = Some(serde_json::json!({
        "baseRef": "origin/release",
        "checkMode": "deep",
        "includeUnchangedTests": false,
    }));

    let config =
        LspAnalysisConfig::from_initialize_params(&params, crate::config::RiprConfig::default());
    let input = config.check_input(Path::new("/workspace"));

    assert_eq!(config.base_ref.as_deref(), Some("origin/release"));
    assert_eq!(config.mode, Mode::Deep);
    assert!(!config.include_unchanged_tests);
    assert_eq!(input.root, PathBuf::from("/workspace"));
    assert_eq!(input.base.as_deref(), Some("origin/release"));
    assert_eq!(input.mode, Mode::Deep);
    assert!(!input.include_unchanged_tests);
}

#[test]
fn initialization_options_allow_empty_base_ref_and_invalid_mode_falls_back() {
    let mut params = initialize_params(None, None);
    params.initialization_options = Some(serde_json::json!({
        "baseRef": "",
        "checkMode": "surprise",
    }));

    let config =
        LspAnalysisConfig::from_initialize_params(&params, crate::config::RiprConfig::default());

    assert_eq!(config.base_ref, None);
    assert_eq!(config.mode, Mode::Draft);
    assert!(config.include_unchanged_tests);
}

#[test]
fn initialization_options_accept_all_analysis_mode_labels() {
    let cases = [
        ("instant", Mode::Instant),
        ("draft", Mode::Draft),
        ("fast", Mode::Fast),
        ("deep", Mode::Deep),
        ("ready", Mode::Ready),
    ];

    for (label, expected) in cases {
        let mut params = initialize_params(None, None);
        params.initialization_options = Some(serde_json::json!({
            "checkMode": label,
        }));

        let config = LspAnalysisConfig::from_initialize_params(
            &params,
            crate::config::RiprConfig::default(),
        );

        assert_eq!(config.mode, expected);
    }
}

#[test]
fn default_lsp_analysis_config_matches_check_input_defaults() {
    let config = LspAnalysisConfig::default();
    let input = config.check_input(Path::new("/workspace"));

    assert_eq!(input.root, PathBuf::from("/workspace"));
    assert_eq!(input.base.as_deref(), Some("origin/main"));
    assert_eq!(input.mode, Mode::Draft);
    assert!(input.include_unchanged_tests);
    assert!(config.enable_seam_diagnostics);
}

#[test]
fn initialize_stores_lsp_analysis_config() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        let mut params = initialize_params(None, None);
        params.initialization_options = Some(serde_json::json!({
            "baseRef": "upstream/main",
            "checkMode": "fast",
        }));

        backend
            .initialize(params)
            .await
            .map_err(|err| format!("initialize failed: {err}"))?;
        let Some(config) = backend.analysis_config() else {
            return Err("expected backend analysis config".to_string());
        };

        assert_eq!(config.base_ref.as_deref(), Some("upstream/main"));
        assert_eq!(config.mode, Mode::Fast);
        Ok(())
    })
}

#[test]
fn initialize_with_invalid_languages_config_falls_back_to_rust_defaults() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let root = unique_lsp_test_root("invalid-languages-config")?;
        std::fs::write(
            root.path().join("ripr.toml"),
            r#"
[languages]
enabled = ["ruby"]
"#,
        )
        .map_err(|err| format!("write invalid config failed: {err}"))?;
        let config_error = match crate::config::load_for_root(root.path()) {
            Ok(_) => {
                return Err(
                    "invalid language config should stay owned by config parsing".to_string(),
                );
            }
            Err(err) => err,
        };
        assert!(
            config_error.contains("languages.enabled") && config_error.contains("ruby"),
            "expected config-owned language error, got: {config_error}"
        );

        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        backend
            .initialize(initialize_params(
                None,
                Some(file_uri_for_path(root.path())?),
            ))
            .await
            .map_err(|err| format!("initialize failed: {err}"))?;
        let Some(config) = backend.analysis_config() else {
            return Err("expected backend analysis config".to_string());
        };

        assert_eq!(config.repo_config().source_path(), None);
        assert_eq!(
            config.repo_config().languages().enabled(),
            &[LanguageId::Rust]
        );
        assert_eq!(config.mode, Mode::Draft);
        assert!(config.enable_seam_diagnostics);
        Ok(())
    })
}

#[test]
fn backend_starts_with_default_lsp_analysis_config() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();

    let Some(config) = backend.analysis_config() else {
        return Err("expected backend analysis config".to_string());
    };

    assert_eq!(config.base_ref.as_deref(), Some("origin/main"));
    assert_eq!(config.mode, Mode::Draft);
    assert!(config.include_unchanged_tests);
    assert!(config.enable_seam_diagnostics);
    Ok(())
}

#[test]
fn workspace_diagnostic_batches_uses_default_lsp_analysis_config() {
    let missing_root = Path::new("target/ripr/definitely-missing-lsp-root");

    assert!(workspace_diagnostic_batches(missing_root).is_err());
}

#[test]
fn boundary_gap_workspace_diagnostics_include_live_seam_diagnostic() -> Result<(), String> {
    let fixture_root = boundary_gap_fixture_root();
    let config = boundary_gap_lsp_config(crate::config::RiprConfig::default());

    let batches = workspace_diagnostic_batches_with_config(&fixture_root, &config)?;
    let seam_diagnostic = batches
        .iter()
        .flat_map(|batch| &batch.diagnostics)
        .any(|diagnostic| {
            diagnostic.source.as_deref() == Some("ripr")
                && diagnostic
                    .code
                    .as_ref()
                    .map(diagnostic_code_value)
                    .as_deref()
                    == Some("ripr-seam-weakly-gripped")
        });

    assert!(
        seam_diagnostic,
        "expected boundary_gap live workspace diagnostics to include ripr-seam-weakly-gripped"
    );
    Ok(())
}

#[test]
fn boundary_gap_lsp_explicit_rust_language_matches_default_projection() -> Result<(), String> {
    let fixture_root = boundary_gap_fixture_root();
    let default_config = boundary_gap_lsp_config(crate::config::RiprConfig::default());
    let rust_only_config = boundary_gap_lsp_config(crate::config::tests_only_parse(
        r#"
[languages]
enabled = ["rust"]
"#,
    )?);

    let default_projection = workspace_projection_contract(&fixture_root, &default_config)?;
    let rust_only_projection = workspace_projection_contract(&fixture_root, &rust_only_config)?;

    assert_eq!(
        rust_only_projection, default_projection,
        "explicit [languages] enabled = [\"rust\"] must preserve the saved-workspace Rust editor diagnostics, hover, actions, and status projection"
    );
    Ok(())
}

#[test]
fn boundary_gap_lsp_empty_languages_suppresses_saved_workspace_diagnostics() -> Result<(), String> {
    let fixture_root = boundary_gap_fixture_root();
    let config = boundary_gap_lsp_config(crate::config::tests_only_parse(
        r#"
[languages]
enabled = []
"#,
    )?);

    let diagnostics = workspace_diagnostics_with_config(&fixture_root, &config)?;
    let diagnostic_count = diagnostics
        .batches
        .iter()
        .map(|batch| batch.diagnostics.len())
        .sum::<usize>();

    assert_eq!(
        diagnostic_count, 0,
        "empty [languages] must publish no saved-workspace diagnostics"
    );
    assert!(
        diagnostics.snapshot.findings.is_empty(),
        "empty [languages] must not retain finding diagnostics in the LSP snapshot"
    );
    assert!(
        diagnostics.snapshot.classified_seams.is_empty(),
        "empty [languages] must not retain seam diagnostics in the LSP snapshot"
    );
    let summary = RefreshLogSummary::from_snapshot(1, &diagnostics.snapshot)
        .with_enabled_languages(config.repo_config().languages().enabled());
    let message = refresh_completed_log_message(&summary, 0, 1);
    assert!(
        message.contains("enabled_languages=0"),
        "empty [languages] refresh message must explain the language-disabled projection state"
    );
    assert!(
        message.contains("enabled_language_names="),
        "empty [languages] refresh message must include an empty language-name field"
    );
    Ok(())
}

#[test]
fn file_uri_to_path_decodes_spaces_and_windows_drive_prefix() -> Result<(), String> {
    let uri = test_uri(&format!("file:///{}{}", "C%3A", "/path/to/ripr%20repo"))?;

    let Some(path) = path_from_file_uri(&uri) else {
        return Err("expected path from file URI".to_string());
    };

    assert_eq!(
        path,
        PathBuf::from(format!("{}{}", "C:", "/path/to/ripr repo"))
    );
    Ok(())
}

#[test]
fn file_uri_to_path_returns_none_for_non_file_scheme() -> Result<(), String> {
    let uri = test_uri("https://example.com/workspace/src/lib.rs")?;

    assert!(path_from_file_uri(&uri).is_none());
    Ok(())
}

#[test]
fn file_uri_to_path_decodes_uppercase_hex_escape() -> Result<(), String> {
    let uri = test_uri("file:///workspace/src%2Dlib.rs")?;

    let Some(path) = path_from_file_uri(&uri) else {
        return Err("expected path from file URI".to_string());
    };
    assert_eq!(path, PathBuf::from("/workspace/src-lib.rs"));
    Ok(())
}

#[test]
fn file_uri_to_path_normalizes_backslash_separators() -> Result<(), String> {
    let drive = "C";
    let uri = test_uri(&format!("file:///{drive}:%5Cworkspace%5Csrc%5Clib.rs"))?;

    let Some(path) = path_from_file_uri(&uri) else {
        return Err("expected path from file URI".to_string());
    };
    assert_eq!(
        path,
        PathBuf::from(format!("{drive}:/workspace/src/lib.rs"))
    );
    Ok(())
}

#[test]
fn file_uri_for_path_uses_valid_encoded_file_uri() -> Result<(), String> {
    let uri = file_uri_for_path(&PathBuf::from("src lib.rs"))?;

    assert_eq!(uri.as_str(), "file:///src%20lib.rs");
    Ok(())
}

#[test]
fn uri_path_encoding_preserves_path_syntax_and_escapes_spaces() {
    assert_eq!(
        encode_uri_path("workspace/src lib.rs"),
        "workspace/src%20lib.rs"
    );
}

#[test]
fn file_uri_match_decodes_equivalent_file_paths() -> Result<(), String> {
    let encoded_uri = test_uri("file:///workspace/src%2Dlib.rs")?;
    let plain_uri = test_uri("file:///workspace/src-lib.rs")?;

    assert!(file_uris_match(&encoded_uri, &plain_uri));
    Ok(())
}

#[test]
fn file_uri_match_treats_windows_drive_paths_case_insensitively() -> Result<(), String> {
    let drive = "C";
    let stored_uri = test_uri(&format!("file:///{drive}:/Workspace/Src/lib.rs"))?;
    let queried_uri = test_uri(&format!(
        "file:///{drive}:/workspace/src/lib.rs",
        drive = drive.to_ascii_lowercase()
    ))?;

    assert!(file_uris_match(&stored_uri, &queried_uri));
    Ok(())
}

#[test]
fn file_uri_match_rejects_non_file_and_distinct_paths() -> Result<(), String> {
    let file_uri = test_uri("file:///workspace/src/lib.rs")?;
    let other_file_uri = test_uri("file:///workspace/src/other.rs")?;
    let non_file_uri = test_uri("https://example.com/workspace/src/lib.rs")?;

    assert!(!file_uris_match(&file_uri, &other_file_uri));
    assert!(!file_uris_match(&non_file_uri, &file_uri));
    assert!(!file_uris_match(&file_uri, &non_file_uri));
    Ok(())
}

#[test]
fn diagnostics_for_uri_matches_windows_drive_case_variants() -> Result<(), String> {
    let drive = "H";
    let root = format!("{drive}:/workspace");
    let stored_uri = test_uri(&format!("file:///{drive}:/workspace/src/pricing.rs"))?;
    let queried_uri = test_uri(&format!(
        "file:///{drive}:/workspace/src/pricing.rs",
        drive = drive.to_ascii_lowercase()
    ))?;
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new(&root), &finding);
    let snapshot = sample_analysis_snapshot(
        PathBuf::from(root),
        stored_uri,
        vec![diagnostic],
        vec![finding],
    );

    let Some(diagnostics) = snapshot.diagnostics_for_uri(&queried_uri) else {
        return Err("expected diagnostics for URI with lowercase drive letter".to_string());
    };

    assert_eq!(diagnostics.len(), 1);
    Ok(())
}

fn test_uri(uri: &str) -> Result<tower_lsp_server::ls_types::Uri, String> {
    uri.parse::<tower_lsp_server::ls_types::Uri>()
        .map_err(|err| format!("failed to parse test URI: {err}"))
}

async fn write_lsp_message<W>(writer: &mut W, message: serde_json::Value) -> Result<(), String>
where
    W: AsyncWrite + Unpin,
{
    let body = serde_json::to_vec(&message)
        .map_err(|err| format!("failed to encode LSP message: {err}"))?;
    let header = format!("Content-Length: {}\r\n\r\n", body.len());
    writer
        .write_all(header.as_bytes())
        .await
        .map_err(|err| format!("failed to write LSP header: {err}"))?;
    writer
        .write_all(&body)
        .await
        .map_err(|err| format!("failed to write LSP body: {err}"))?;
    writer
        .flush()
        .await
        .map_err(|err| format!("failed to flush LSP message: {err}"))
}

async fn read_lsp_response<R>(reader: &mut R, id: u64) -> Result<serde_json::Value, String>
where
    R: AsyncRead + Unpin,
{
    loop {
        let message = read_lsp_message(reader).await?;
        if message.get("id").and_then(serde_json::Value::as_u64) == Some(id) {
            return Ok(message);
        }
    }
}

async fn read_lsp_response_with_notifications<R>(
    reader: &mut R,
    id: u64,
) -> Result<(serde_json::Value, Vec<serde_json::Value>), String>
where
    R: AsyncRead + Unpin,
{
    let mut notifications = Vec::new();
    loop {
        let message = read_lsp_message(reader).await?;
        if message.get("id").and_then(serde_json::Value::as_u64) == Some(id) {
            return Ok((message, notifications));
        }
        notifications.push(message);
    }
}

fn log_notification_messages(messages: &[serde_json::Value]) -> Vec<String> {
    messages
        .iter()
        .filter(|message| {
            message.get("method").and_then(serde_json::Value::as_str) == Some("window/logMessage")
        })
        .filter_map(|message| {
            message
                .get("params")
                .and_then(|params| params.get("message"))
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
        })
        .collect()
}

async fn read_lsp_message<R>(reader: &mut R) -> Result<serde_json::Value, String>
where
    R: AsyncRead + Unpin,
{
    let mut header = Vec::new();
    loop {
        let mut byte = [0_u8; 1];
        reader
            .read_exact(&mut byte)
            .await
            .map_err(|err| format!("failed to read LSP header: {err}"))?;
        header.push(byte[0]);
        if header.ends_with(b"\r\n\r\n") {
            break;
        }
    }
    let header =
        std::str::from_utf8(&header).map_err(|err| format!("invalid LSP header UTF-8: {err}"))?;
    let content_length = header
        .lines()
        .find_map(|line| line.strip_prefix("Content-Length: "))
        .ok_or_else(|| "missing LSP Content-Length header".to_string())?
        .parse::<usize>()
        .map_err(|err| format!("invalid LSP Content-Length header: {err}"))?;
    let mut body = vec![0_u8; content_length];
    reader
        .read_exact(&mut body)
        .await
        .map_err(|err| format!("failed to read LSP body: {err}"))?;
    serde_json::from_slice(&body).map_err(|err| format!("failed to decode LSP message: {err}"))
}

fn gap_action_diagnostic() -> tower_lsp_server::ls_types::Diagnostic {
    tower_lsp_server::ls_types::Diagnostic {
        range: Range {
            start: Position {
                line: 11,
                character: 0,
            },
            end: Position {
                line: 11,
                character: 120,
            },
        },
        severity: Some(DiagnosticSeverity::WARNING),
        code: Some(NumberOrString::String(
            "ripr-gap-MissingBoundaryAssertion".to_string(),
        )),
        code_description: None,
        source: Some("ripr".to_string()),
        message: "ripr gap: MissingBoundaryAssertion; repair route: AddBoundaryAssertion"
            .to_string(),
        related_information: None,
        tags: None,
        data: Some(serde_json::json!({
            "schema_version": "0.1",
            "source": "gap_decision_ledger",
            "gap_ledger": "target/ripr/reports/gap-decision-ledger.json",
            "gap_id": "gap:py:pricing",
            "canonical_gap_id": "gap:py:pricing",
            "gap_kind": "MissingBoundaryAssertion",
            "language": "python",
            "language_status": "preview",
            "gap_state": "actionable",
            "policy_state": "advisory",
            "repairability": "repairable",
            "static_limit_kind": "missing_import_graph",
            "static_limit_detail": "Imported owner targets were not resolved in preview mode.",
            "repair_route": {
                "route_kind": "AddBoundaryAssertion",
                "target_file": "tests/test_pricing.py",
                "target_line": 2,
                "related_test": "tests/test_pricing.py::test_discount_boundary",
                "assertion_shape": "assert price(threshold) == expected",
                "changed_behavior": "amount >= threshold",
                "stop_conditions": ["Stop if the related test belongs to another package."]
            },
            "verification_commands": ["ripr agent verify --root . --json"],
            "receipt_command": "ripr agent receipt --root . --json",
            "authority_boundary": "advisory"
        })),
    }
}

fn validated_gap_artifact() -> ValidatedGapArtifact {
    ValidatedGapArtifact {
        kind: GapArtifactKind::GapDecisionLedger,
        root: Some(".".to_string()),
        identities: vec![GapArtifactIdentity {
            canonical_gap_id: Some("gap:py:pricing".to_string()),
            seam_id: None,
            finding_id: None,
        }],
        language: Some(LanguageId::Python),
        language_status: Some(LanguageStatus::Preview),
        gap_state: Some("actionable".to_string()),
        related_paths: vec!["tests/test_pricing.py".to_string()],
        verify_commands: vec!["ripr agent verify --root . --json".to_string()],
        receipt_commands: vec!["ripr agent receipt --root . --json".to_string()],
        static_limit_kinds: vec!["missing_import_graph".to_string()],
        has_text_static_limit: false,
    }
}

fn sample_analysis_snapshot(
    root: PathBuf,
    uri: tower_lsp_server::ls_types::Uri,
    diagnostics: Vec<tower_lsp_server::ls_types::Diagnostic>,
    findings: Vec<Finding>,
) -> AnalysisSnapshot {
    let mut diagnostics_by_uri = BTreeMap::new();
    diagnostics_by_uri.insert(uri, diagnostics);
    AnalysisSnapshot {
        root,
        base: Some("origin/main".to_string()),
        mode: Mode::Draft,
        refresh: RefreshMetadata::generated_now(),
        findings,
        classified_seams: Vec::new(),
        gap_artifacts: Vec::new(),
        gap_artifact_rejections: Vec::new(),
        diagnostics_by_uri,
    }
}

fn sample_workspace_diagnostics(
    root: PathBuf,
    uri: tower_lsp_server::ls_types::Uri,
    diagnostics: Vec<tower_lsp_server::ls_types::Diagnostic>,
    findings: Vec<Finding>,
) -> WorkspaceDiagnostics {
    let snapshot = sample_analysis_snapshot(root, uri.clone(), diagnostics.clone(), findings);
    WorkspaceDiagnostics {
        snapshot,
        batches: vec![DiagnosticBatch { uri, diagnostics }],
    }
}

fn code_action_params(
    diagnostics: Vec<tower_lsp_server::ls_types::Diagnostic>,
) -> Result<CodeActionParams, String> {
    Ok(CodeActionParams {
        text_document: TextDocumentIdentifier::new(test_uri("file:///workspace/src/pricing.rs")?),
        range: Range {
            start: Position {
                line: 87,
                character: 0,
            },
            end: Position {
                line: 87,
                character: 120,
            },
        },
        context: CodeActionContext {
            diagnostics,
            only: None,
            trigger_kind: None,
        },
        work_done_progress_params: Default::default(),
        partial_result_params: Default::default(),
    })
}

fn code_action_commands(
    actions: &[CodeActionOrCommand],
) -> Result<Vec<(String, String, Vec<serde_json::Value>)>, String> {
    let mut commands = Vec::new();
    for action in actions {
        let CodeActionOrCommand::CodeAction(action) = action else {
            return Err("expected code action".to_string());
        };
        let Some(command) = &action.command else {
            return Err(format!("expected command for action {}", action.title));
        };
        commands.push((
            action.title.clone(),
            command.command.clone(),
            command.arguments.clone().unwrap_or_default(),
        ));
    }
    Ok(commands)
}

fn boundary_gap_fixture_root() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join("fixtures/boundary_gap/input")
}

struct TempLspRoot {
    path: PathBuf,
}

impl TempLspRoot {
    fn path(&self) -> &Path {
        &self.path
    }
}

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

fn unique_lsp_test_root(name: &str) -> Result<TempLspRoot, String> {
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|duration| duration.as_nanos())
        .unwrap_or(0);
    let root = std::env::temp_dir().join(format!("ripr-lsp-{name}-{}-{stamp}", std::process::id()));
    std::fs::create_dir_all(&root).map_err(|err| format!("create temp root failed: {err}"))?;
    Ok(TempLspRoot { path: root })
}

fn boundary_gap_lsp_config(repo_config: crate::config::RiprConfig) -> LspAnalysisConfig {
    LspAnalysisConfig {
        base_ref: Some("HEAD".to_string()),
        mode: Mode::Instant,
        repo_config,
        ..LspAnalysisConfig::default()
    }
}

fn workspace_projection_contract(
    root: &Path,
    config: &LspAnalysisConfig,
) -> Result<serde_json::Value, String> {
    let diagnostics = workspace_diagnostics_with_config(root, config)?;
    let projected_diagnostics = diagnostics
        .batches
        .iter()
        .flat_map(|batch| {
            batch
                .diagnostics
                .iter()
                .map(|diagnostic| project_diagnostic(root, &batch.uri, diagnostic))
        })
        .collect::<Result<Vec<_>, _>>()?;
    let (uri, diagnostic) = first_seam_diagnostic(&diagnostics)?;
    let seam = diagnostics
        .snapshot
        .classified_seam_for_diagnostic(&diagnostic)
        .ok_or_else(|| "expected seam diagnostic to resolve to classified seam".to_string())?;
    let hover = hover_with_snapshot_status(
        classified_seam_hover_response(seam, &diagnostic, Some(&diagnostics.snapshot)),
        &diagnostics.snapshot,
    );
    let hover_markdown = match hover.contents {
        HoverContents::Markup(markup) => markup.value,
        _ => return Err("expected markup hover".to_string()),
    };
    let actions = code_action_response(
        &code_action_params_for(uri, diagnostic.range.start.line, vec![diagnostic.clone()])?,
        Some(&diagnostics.snapshot),
    );
    let summary = RefreshLogSummary::from_snapshot(1, &diagnostics.snapshot)
        .with_enabled_languages(config.repo_config().languages().enabled());
    let status = refresh_completed_log_message(&summary, diagnostics.batches.len(), 0);

    Ok(serde_json::json!({
        "diagnostics": projected_diagnostics,
        "hover": normalize_snapshot_age(&hover_markdown),
        "actions": project_code_actions(root, &actions)?,
        "status": status,
    }))
}

fn normalize_snapshot_age(markdown: &str) -> String {
    markdown
        .lines()
        .map(|line| {
            if line.starts_with("Analysis snapshot: generated ") {
                "Analysis snapshot: generated <elapsed> ago.".to_string()
            } else {
                line.to_string()
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn first_seam_diagnostic(
    diagnostics: &WorkspaceDiagnostics,
) -> Result<
    (
        tower_lsp_server::ls_types::Uri,
        tower_lsp_server::ls_types::Diagnostic,
    ),
    String,
> {
    diagnostics
        .batches
        .iter()
        .flat_map(|batch| {
            batch
                .diagnostics
                .iter()
                .map(move |diagnostic| (&batch.uri, diagnostic))
        })
        .find(|(_, diagnostic)| {
            diagnostic
                .code
                .as_ref()
                .map(diagnostic_code_value)
                .is_some_and(|code| code.starts_with("ripr-seam-"))
        })
        .map(|(uri, diagnostic)| (uri.clone(), diagnostic.clone()))
        .ok_or_else(|| "expected at least one seam diagnostic".to_string())
}

fn boundary_gap_lsp_fixture_outputs() -> Result<(serde_json::Value, serde_json::Value), String> {
    let fixture_root = boundary_gap_fixture_root();
    let mut seams = crate::analysis::inventory_classified_seams_at_with_config(
        &fixture_root,
        &crate::config::RiprConfig::default(),
    )?;
    seams.sort_by(|left, right| left.seam.id().as_str().cmp(right.seam.id().as_str()));
    if seams.len() != 1 {
        return Err(format!(
            "expected one boundary_gap classified seam, got {}",
            seams.len()
        ));
    }
    let seam = seams
        .into_iter()
        .next()
        .ok_or_else(|| "expected classified seam".to_string())?;
    let diagnostic = diagnostic_for_classified_seam(&fixture_root, &seam)
        .ok_or_else(|| "expected seam diagnostic".to_string())?;
    let uri = file_uri_for_path(&fixture_root.join(seam.seam.file()))?;
    let mut snapshot = sample_analysis_snapshot(
        fixture_root.clone(),
        uri.clone(),
        vec![diagnostic.clone()],
        Vec::new(),
    );
    snapshot.mode = Mode::Fast;
    snapshot.classified_seams = vec![seam.clone()];
    let actions = code_action_response(
        &code_action_params_for(
            uri.clone(),
            diagnostic.range.start.line,
            vec![diagnostic.clone()],
        )?,
        Some(&snapshot),
    );

    Ok((
        serde_json::json!({
            "fixture": "boundary_gap",
            "diagnostics": [project_diagnostic(&fixture_root, &uri, &diagnostic)?],
        }),
        serde_json::json!({
            "fixture": "boundary_gap",
            "actions": project_code_actions(&fixture_root, &actions)?,
        }),
    ))
}

fn assert_json_fixture(name: &str, actual: serde_json::Value) -> Result<(), String> {
    let path = Path::new("fixtures")
        .join("boundary_gap")
        .join("expected")
        .join(name);
    let path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join(path);
    let text = std::fs::read_to_string(&path).map_err(|err| {
        format!(
            "failed to read {}: {err}\nactual:\n{}",
            path.display(),
            pretty_json(&actual)
        )
    })?;
    let expected: serde_json::Value = serde_json::from_str(&text)
        .map_err(|err| format!("failed to parse {}: {err}", path.display()))?;
    if expected != actual {
        return Err(format!(
            "{} drifted\nexpected:\n{}\nactual:\n{}",
            path.display(),
            pretty_json(&expected),
            pretty_json(&actual)
        ));
    }
    Ok(())
}

fn project_diagnostic(
    root: &Path,
    uri: &tower_lsp_server::ls_types::Uri,
    diagnostic: &tower_lsp_server::ls_types::Diagnostic,
) -> Result<serde_json::Value, String> {
    Ok(serde_json::json!({
        "uri": relative_uri_path(root, uri)?,
        "range": {
            "start": {
                "line": diagnostic.range.start.line,
                "character": diagnostic.range.start.character,
            },
            "end": {
                "line": diagnostic.range.end.line,
                "character": diagnostic.range.end.character,
            },
        },
        "severity": diagnostic.severity.map(diagnostic_severity_label),
        "code": diagnostic.code.as_ref().map(diagnostic_code_value),
        "source": diagnostic.source.clone(),
        "message": diagnostic.message,
        "data": diagnostic.data.clone(),
    }))
}

fn project_code_actions(
    root: &Path,
    actions: &[CodeActionOrCommand],
) -> Result<Vec<serde_json::Value>, String> {
    let commands = code_action_commands(actions)?;
    commands
        .into_iter()
        .map(|(title, command, arguments)| {
            let arguments = arguments
                .iter()
                .map(|argument| normalize_lsp_action_argument(root, argument))
                .collect::<Result<Vec<_>, _>>()?;
            Ok(serde_json::json!({
                "title": title,
                "command": command,
                "arguments": arguments,
            }))
        })
        .collect()
}

fn normalize_lsp_action_argument(
    root: &Path,
    argument: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let Some(object) = argument.as_object() else {
        return Ok(argument.clone());
    };
    let mut normalized = serde_json::Map::new();
    for (key, value) in object {
        if key == "uri"
            && let Some(uri) = value.as_str()
            && uri.starts_with("file://")
        {
            let parsed = uri
                .parse()
                .map_err(|err| format!("failed to parse action uri {uri}: {err}"))?;
            normalized.insert(
                key.clone(),
                serde_json::json!(relative_uri_path(root, &parsed)?),
            );
        } else {
            normalized.insert(key.clone(), value.clone());
        }
    }
    Ok(serde_json::Value::Object(normalized))
}

fn code_action_params_for(
    uri: tower_lsp_server::ls_types::Uri,
    line: u32,
    diagnostics: Vec<tower_lsp_server::ls_types::Diagnostic>,
) -> Result<CodeActionParams, String> {
    Ok(CodeActionParams {
        text_document: TextDocumentIdentifier::new(uri),
        range: Range {
            start: Position { line, character: 0 },
            end: Position {
                line,
                character: 120,
            },
        },
        context: CodeActionContext {
            diagnostics,
            only: None,
            trigger_kind: None,
        },
        work_done_progress_params: Default::default(),
        partial_result_params: Default::default(),
    })
}

fn diagnostic_severity_label(severity: DiagnosticSeverity) -> &'static str {
    match severity {
        DiagnosticSeverity::ERROR => "error",
        DiagnosticSeverity::WARNING => "warning",
        DiagnosticSeverity::INFORMATION => "information",
        DiagnosticSeverity::HINT => "hint",
        _ => "unknown",
    }
}

fn diagnostic_code_value(code: &NumberOrString) -> String {
    match code {
        NumberOrString::Number(value) => value.to_string(),
        NumberOrString::String(value) => value.clone(),
    }
}

fn relative_uri_path(root: &Path, uri: &tower_lsp_server::ls_types::Uri) -> Result<String, String> {
    let path =
        path_from_file_uri(uri).ok_or_else(|| format!("expected file uri: {}", uri.as_str()))?;
    relative_path(root, &path)
}

fn relative_path(root: &Path, path: &Path) -> Result<String, String> {
    let root = normalize_fixture_path(root);
    let path = normalize_fixture_path(path);
    if path == root {
        return Ok(".".to_string());
    }
    let prefix = format!("{root}/");
    path.strip_prefix(&prefix)
        .map(str::to_string)
        .ok_or_else(|| format!("path {path} is not under fixture root {root}"))
}

fn normalize_fixture_path(path: &Path) -> String {
    path.to_string_lossy().replace('\\', "/")
}

fn pretty_json(value: &serde_json::Value) -> String {
    serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string())
}

fn hover_params(uri: tower_lsp_server::ls_types::Uri, line: u32, character: u32) -> HoverParams {
    HoverParams {
        text_document_position_params: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier::new(uri),
            position: Position { line, character },
        },
        work_done_progress_params: Default::default(),
    }
}

#[expect(
    deprecated,
    reason = "Test helper constructs InitializeParams including the deprecated root_path/root_uri fields to exercise fallback handling in capabilities.rs."
)]
fn initialize_params(
    workspace_folders: Option<Vec<WorkspaceFolder>>,
    root_uri: Option<tower_lsp_server::ls_types::Uri>,
) -> InitializeParams {
    InitializeParams {
        workspace_folders,
        root_uri,
        ..InitializeParams::default()
    }
}

fn sample_finding() -> Finding {
    Finding {
        id: "probe:pricing:88:predicate".to_string(),
        probe: Probe {
            id: ProbeId("probe:pricing:88:predicate".to_string()),
            location: SourceLocation {
                file: PathBuf::from("src/pricing.rs"),
                line: 88,
                column: 1,
            },
            owner: None,
            family: ProbeFamily::Predicate,
            delta: DeltaKind::Control,
            before: None,
            after: None,
            expression: "amount >= threshold".to_string(),
            expected_sinks: Vec::new(),
            required_oracles: Vec::new(),
        },
        class: ExposureClass::WeaklyExposed,
        ripr: RiprEvidence {
            reach: StageEvidence::new(StageState::Yes, Confidence::High, "related tests found"),
            infect: StageEvidence::new(
                StageState::Yes,
                Confidence::High,
                "predicate can alter branch behavior",
            ),
            propagate: StageEvidence::new(
                StageState::Yes,
                Confidence::Medium,
                "branch influences return value",
            ),
            reveal: RevealEvidence {
                observe: StageEvidence::new(
                    StageState::Weak,
                    Confidence::Medium,
                    "return value asserted",
                ),
                discriminate: StageEvidence::new(
                    StageState::Weak,
                    Confidence::Medium,
                    "boundary value missing",
                ),
            },
        },
        confidence: 0.75,
        evidence: Vec::new(),
        missing: Vec::new(),
        flow_sinks: Vec::new(),
        activation: crate::domain::ActivationEvidence::default(),
        stop_reasons: Vec::new(),
        related_tests: Vec::new(),
        recommended_next_step: Some("Add an exact boundary assertion.".to_string()),
        language: None,
        language_status: None,
        owner_kind: None,
        static_limit_kind: None,
    }
}

fn sample_classified_seam() -> crate::analysis::ClassifiedSeam {
    use crate::analysis::seams::{
        ExpectedSink, RepoSeam, RequiredDiscriminator, SeamGripClass, SeamKind,
    };
    use crate::analysis::test_grip_evidence::{
        RelatedTestGrip, RelationConfidence, RelationReason, TestGripEvidence,
    };
    use crate::domain::{MissingDiscriminatorFact, ValueContext, ValueFact};

    let seam = RepoSeam::new(
        "src/pricing.rs",
        "pricing::discounted_total",
        SeamKind::PredicateBoundary,
        42,
        88,
        "amount >= discount_threshold",
        RequiredDiscriminator::BoundaryValue {
            description: "amount >= discount_threshold".to_string(),
        },
        ExpectedSink::ReturnValue,
    );
    let seam_id = seam.id().clone();
    crate::analysis::ClassifiedSeam {
        seam,
        evidence: TestGripEvidence {
            seam_id,
            related_tests: vec![RelatedTestGrip {
                test_name: "below_threshold_has_no_discount".to_string(),
                file: PathBuf::from("tests/pricing.rs"),
                line: 12,
                oracle_kind: OracleKind::ExactValue,
                oracle_strength: OracleStrength::Strong,
                evidence_summary: "exact value assertion".to_string(),
                relation_reason: RelationReason::DirectOwnerCall,
                relation_confidence: RelationConfidence::High,
            }],
            reach: StageEvidence::new(
                StageState::Yes,
                Confidence::High,
                "related test calls owner",
            ),
            activate: StageEvidence::new(StageState::Yes, Confidence::High, "test reaches branch"),
            propagate: StageEvidence::new(StageState::Yes, Confidence::Medium, "return value sink"),
            observe: StageEvidence::new(StageState::Yes, Confidence::Medium, "exact assertion"),
            discriminate: StageEvidence::new(
                StageState::Weak,
                Confidence::Medium,
                "boundary value missing",
            ),
            observed_values: vec![ValueFact {
                line: 12,
                text: "discounted_total(50, 100)".to_string(),
                value: "50".to_string(),
                context: ValueContext::FunctionArgument,
            }],
            missing_discriminators: vec![MissingDiscriminatorFact {
                value: "discount_threshold (equality boundary)".to_string(),
                reason: "observed values skip equality boundary".to_string(),
                flow_sink: None,
            }],
        },
        class: SeamGripClass::WeaklyGripped,
    }
}

fn sample_side_effect_seam_without_related_tests() -> crate::analysis::ClassifiedSeam {
    use crate::analysis::seams::{
        ExpectedSink, RepoSeam, RequiredDiscriminator, SeamGripClass, SeamKind,
    };
    use crate::analysis::test_grip_evidence::TestGripEvidence;

    let seam = RepoSeam::new(
        "src/service.rs",
        "service::publish_event",
        SeamKind::SideEffect,
        7,
        14,
        "event_bus.publish(event)",
        RequiredDiscriminator::Effect {
            sink: "event bus publish".to_string(),
        },
        ExpectedSink::SideEffect,
    );
    let seam_id = seam.id().clone();
    crate::analysis::ClassifiedSeam {
        seam,
        evidence: TestGripEvidence {
            seam_id,
            related_tests: Vec::new(),
            reach: StageEvidence::new(StageState::No, Confidence::Low, "no related test"),
            activate: StageEvidence::new(StageState::No, Confidence::Low, "no activation value"),
            propagate: StageEvidence::new(StageState::Unknown, Confidence::Low, "unknown sink"),
            observe: StageEvidence::new(StageState::No, Confidence::Low, "no observer"),
            discriminate: StageEvidence::new(StageState::No, Confidence::Low, "no discriminator"),
            observed_values: Vec::new(),
            missing_discriminators: Vec::new(),
        },
        class: SeamGripClass::Ungripped,
    }
}

#[test]
fn finding_hover_response_includes_ripr_evidence_path() -> Result<(), String> {
    use super::hover::finding_hover_response;

    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    let hover = finding_hover_response(&finding, &diagnostic);

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("**ripr** `weakly_exposed`"));
            assert!(markup.value.contains("predicate"));
            assert!(markup.value.contains("reach yes:"));
            assert!(markup.value.contains("infection yes:"));
            assert!(markup.value.contains("propagation yes:"));
            assert!(markup.value.contains("observation weak:"));
            assert!(markup.value.contains("discriminator weak:"));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn finding_hover_response_includes_evidence_details() -> Result<(), String> {
    use super::hover::finding_hover_response;
    use crate::domain::{
        ActivationEvidence, FlowSinkFact, FlowSinkKind, MissingDiscriminatorFact, RelatedTest,
        ValueContext, ValueFact,
    };

    let mut finding = sample_finding();
    finding.flow_sinks = vec![FlowSinkFact {
        kind: FlowSinkKind::ReturnValue,
        text: "total".to_string(),
        line: 88,
        owner: None,
    }];
    finding.related_tests = vec![RelatedTest {
        name: "discount_boundary_is_exact".to_string(),
        file: PathBuf::from("tests/pricing.rs"),
        line: 12,
        oracle: Some("assert_eq!(total, expected)".to_string()),
        oracle_kind: OracleKind::ExactValue,
        oracle_strength: OracleStrength::Strong,
    }];
    finding.activation = ActivationEvidence {
        observed_values: vec![ValueFact {
            line: 12,
            text: "assert_eq!".to_string(),
            value: "amount == threshold".to_string(),
            context: ValueContext::FunctionArgument,
        }],
        missing_discriminators: vec![MissingDiscriminatorFact {
            value: "amount == threshold".to_string(),
            reason: "related tests do not cover the changed boundary value".to_string(),
            flow_sink: None,
        }],
    };

    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let hover = finding_hover_response(&finding, &diagnostic);

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("## RIPR Evidence"));
            assert!(markup.value.contains("* reach yes: related tests found"));
            assert!(
                markup
                    .value
                    .contains("* infection yes: predicate can alter branch behavior")
            );
            assert!(
                markup
                    .value
                    .contains("* propagation yes: branch influences return value")
            );
            assert!(
                markup
                    .value
                    .contains("* observation weak: return value asserted")
            );
            assert!(
                markup
                    .value
                    .contains("* discriminator weak: boundary value missing")
            );
            assert!(markup.value.contains("## Related Tests"));
            assert!(markup.value.contains("tests/pricing.rs:12"));
            assert!(markup.value.contains("discount_boundary_is_exact"));
            assert!(
                markup
                    .value
                    .contains("strong exact_value oracle: assert_eq!(total, expected)")
            );
            assert!(markup.value.contains("Add an exact boundary assertion."));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn preview_finding_diagnostic_preserves_language_metadata() -> Result<(), String> {
    let mut finding = sample_finding();
    finding.language = Some(LanguageId::Python);
    finding.language_status = Some(LanguageStatus::Preview);
    finding.owner_kind = Some(OwnerKind::Function);
    finding.static_limit_kind = Some(StaticLimitKind::MissingImportGraph);
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    assert!(
        diagnostic
            .message
            .contains("python preview evidence (syntax-first, advisory)")
    );
    assert!(
        diagnostic
            .message
            .contains("Static limit: missing_import_graph")
    );
    let data = diagnostic
        .data
        .and_then(|value| value.as_object().cloned())
        .ok_or_else(|| "expected diagnostic data".to_string())?;
    assert_eq!(
        data.get("language").and_then(|value| value.as_str()),
        Some("python")
    );
    assert_eq!(
        data.get("language_status").and_then(|value| value.as_str()),
        Some("preview")
    );
    assert_eq!(
        data.get("owner_kind").and_then(|value| value.as_str()),
        Some("function")
    );
    assert_eq!(
        data.get("static_limit_kind")
            .and_then(|value| value.as_str()),
        Some("missing_import_graph")
    );
    Ok(())
}

#[test]
fn preview_finding_hover_shows_boundary_before_evidence() -> Result<(), String> {
    use super::hover::finding_hover_response;

    let mut finding = sample_finding();
    finding.language = Some(LanguageId::Python);
    finding.language_status = Some(LanguageStatus::Preview);
    finding.static_limit_kind = Some(StaticLimitKind::MissingImportGraph);
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    let hover = finding_hover_response(&finding, &diagnostic);

    match hover.contents {
        HoverContents::Markup(markup) => {
            let preview_index = markup
                .value
                .find("## Preview Boundary")
                .ok_or_else(|| "expected preview boundary".to_string())?;
            let evidence_index = markup
                .value
                .find("## RIPR Evidence")
                .ok_or_else(|| "expected evidence section".to_string())?;
            let static_limit_index = markup
                .value
                .find("Static limit: missing_import_graph")
                .ok_or_else(|| "expected static limit".to_string())?;
            let action_index = markup
                .value
                .find("Add an exact boundary assertion.")
                .ok_or_else(|| "expected suggested action text".to_string())?;
            assert!(
                preview_index < evidence_index,
                "preview boundary must appear before evidence details"
            );
            assert!(
                static_limit_index < action_index,
                "static limits must appear before suggested action language"
            );
            assert!(markup.value.contains("Language: python"));
            assert!(markup.value.contains("Status: preview"));
            assert!(markup.value.contains("Evidence: syntax-first"));
            assert!(markup.value.contains("Action: advisory only"));
            assert!(markup.value.contains("Static limit: missing_import_graph"));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn preview_finding_code_actions_stay_bounded_to_context_and_refresh() -> Result<(), String> {
    let mut finding = sample_finding();
    finding.language = Some(LanguageId::Python);
    finding.language_status = Some(LanguageStatus::Preview);
    finding.owner_kind = Some(OwnerKind::Function);
    finding.static_limit_kind = Some(StaticLimitKind::MissingImportGraph);
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.py")?;
    let snapshot = sample_analysis_snapshot(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let actions = code_action_response(
        &code_action_params_for(uri, diagnostic.range.start.line, vec![diagnostic])?,
        Some(&snapshot),
    );

    let commands = code_action_commands(&actions)?;
    assert_eq!(
        commands
            .iter()
            .map(|(title, command, _)| (title.as_str(), command.as_str()))
            .collect::<Vec<_>>(),
        vec![
            ("Inspect finding: copy context packet", COPY_CONTEXT_COMMAND),
            ("Refresh Analysis - Saved Workspace Check", REFRESH_COMMAND),
        ],
        "preview findings must not expose seam repair, related-test, verify, or receipt actions without validated seam/gap evidence"
    );
    assert_eq!(commands[0].2[0]["finding_id"], "probe:pricing:88:predicate");
    assert_eq!(commands[0].2[0]["probe_id"], "probe:pricing:88:predicate");
    Ok(())
}

#[test]
fn hover_for_position_uses_snapshot_finding_hover() -> Result<(), String> {
    let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
    let backend = service.inner();
    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
    let uri = test_uri("file:///workspace/src/pricing.rs")?;
    let diagnostics = sample_workspace_diagnostics(
        PathBuf::from("/workspace"),
        uri.clone(),
        vec![diagnostic.clone()],
        vec![finding],
    );
    let Some(_) = backend.refresh_plan(diagnostics) else {
        return Err("expected refresh plan".to_string());
    };

    let Some(hover) = backend.hover_for_position(&hover_params(uri, 87, 1)) else {
        return Err("expected finding hover".to_string());
    };

    match hover.contents {
        HoverContents::Markup(markup) => {
            assert!(markup.value.contains("**ripr** `weakly_exposed`"));
            assert!(markup.value.contains("predicate"));
            assert!(markup.value.contains("## RIPR Evidence"));
            assert!(markup.value.contains("reach yes:"));
            assert!(markup.value.contains("Add an exact boundary assertion."));
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn finding_hover_avoids_mutation_runtime_language() -> Result<(), String> {
    use super::hover::finding_hover_response;

    let finding = sample_finding();
    let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);

    let hover = finding_hover_response(&finding, &diagnostic);

    match hover.contents {
        HoverContents::Markup(markup) => {
            let lower = markup.value.to_lowercase();
            let forbidden_terms = vec!["kil", "surv", "prov", "adeq", "untest"];
            for term in forbidden_terms {
                assert!(
                    !lower.contains(term),
                    "hover must use conservative static language"
                );
            }
            Ok(())
        }
        _ => Err("expected markup hover".to_string()),
    }
}

#[test]
fn execute_command_collect_context_returns_packet_for_known_finding() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        let finding = sample_finding();
        let expected_finding = finding.clone();
        let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
        let uri = test_uri("file:///workspace/src/pricing.rs")?;
        let diagnostics = sample_workspace_diagnostics(
            PathBuf::from("/workspace"),
            uri.clone(),
            vec![diagnostic.clone()],
            vec![finding],
        );
        let Some(_) = backend.refresh_plan(diagnostics) else {
            return Err("expected refresh plan".to_string());
        };

        let params = ExecuteCommandParams {
            command: COLLECT_CONTEXT_COMMAND.to_string(),
            arguments: vec![serde_json::json!({
                "finding_id": "probe:pricing:88:predicate",
                "probe_id": "probe:pricing:88:predicate",
                "uri": "file:///workspace/src/pricing.rs",
                "line": 88,
            })],
            work_done_progress_params: Default::default(),
        };
        let result = backend.execute_command(params).await;
        let packet = result.map_err(|err| format!("execute_command failed: {err}"))?;
        let Some(packet) = packet else {
            return Err("expected context packet".to_string());
        };
        let expected_stop_reasons = expected_finding
            .effective_stop_reasons()
            .iter()
            .map(|reason| reason.as_str().to_string())
            .collect();
        let expected_context_packet = crate::domain::context_packet::ContextPacket::from_finding(
            &expected_finding,
            crate::config::DEFAULT_CONTEXT_RELATED_TESTS,
            expected_stop_reasons,
        );
        let expected_json =
            crate::output::json::render_context_packet_dto(&expected_context_packet);
        let expected_packet: serde_json::Value = serde_json::from_str(&expected_json)
            .map_err(|err| format!("failed to parse expected packet: {err}"))?;
        assert_eq!(packet, expected_packet);
        let packet_str = serde_json::to_string(&packet)
            .map_err(|err| format!("failed to serialize packet: {err}"))?;
        assert!(packet_str.contains("\"version\""));
        assert!(packet_str.contains("\"tool\""));
        assert!(packet_str.contains("probe:pricing:88:predicate"));
        Ok(())
    })
}

#[test]
fn execute_command_collect_context_returns_agent_seam_packet_for_known_seam() -> Result<(), String>
{
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        let seam = sample_classified_seam();
        let seam_id = seam.seam.id().as_str().to_string();
        let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
            .ok_or_else(|| "expected seam diagnostic".to_string())?;
        let uri = test_uri("file:///workspace/src/pricing.rs")?;
        let mut diagnostics = sample_workspace_diagnostics(
            PathBuf::from("/workspace"),
            uri,
            vec![diagnostic],
            Vec::new(),
        );
        diagnostics.snapshot.classified_seams = vec![seam];
        let Some(_) = backend.refresh_plan(diagnostics) else {
            return Err("expected refresh plan".to_string());
        };

        let params = ExecuteCommandParams {
            command: COLLECT_CONTEXT_COMMAND.to_string(),
            arguments: vec![serde_json::json!({
                "seam_id": seam_id,
                "uri": "file:///workspace/src/pricing.rs",
                "line": 88,
            })],
            work_done_progress_params: Default::default(),
        };
        let result = backend.execute_command(params).await;
        let packet = result.map_err(|err| format!("execute_command failed: {err}"))?;
        let Some(packet) = packet else {
            return Err("expected seam packet".to_string());
        };
        assert_eq!(packet["schema_version"], "0.3");
        assert_eq!(packet["packets_total"], 1);
        assert_eq!(packet["packets"][0]["seam_id"], seam_id);
        assert_eq!(
            packet["packets"][0]["assertion_shape"]["kind"],
            "exact_return_value"
        );
        Ok(())
    })
}

#[test]
fn execute_command_collect_evidence_context_returns_editor_packet_for_known_seam()
-> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        let seam = sample_classified_seam();
        let seam_id = seam.seam.id().as_str().to_string();
        let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
            .ok_or_else(|| "expected seam diagnostic".to_string())?;
        let uri = test_uri("file:///workspace/src/pricing.rs")?;
        let mut diagnostics = sample_workspace_diagnostics(
            PathBuf::from("/workspace"),
            uri,
            vec![diagnostic],
            Vec::new(),
        );
        diagnostics.snapshot.classified_seams = vec![seam];
        let Some(_) = backend.refresh_plan(diagnostics) else {
            return Err("expected refresh plan".to_string());
        };

        let params = ExecuteCommandParams {
            command: COLLECT_EVIDENCE_CONTEXT_COMMAND.to_string(),
            arguments: vec![serde_json::json!({
                "seam_id": seam_id,
                "uri": "file:///workspace/src/pricing.rs",
                "line": 88,
            })],
            work_done_progress_params: Default::default(),
        };
        let result = backend.execute_command(params).await;
        let packet = result.map_err(|err| format!("execute_command failed: {err}"))?;
        let Some(packet) = packet else {
            return Err("expected evidence context packet".to_string());
        };

        assert_eq!(packet["schema_version"], "0.1");
        assert_eq!(packet["tool"], "ripr");
        assert_eq!(packet["base"], "origin/main");
        assert_eq!(packet["mode"], "draft");
        assert_eq!(packet["seam_id"], seam_id);
        assert_eq!(packet["file"], "src/pricing.rs");
        assert_eq!(packet["range"]["start"], 88);
        assert_eq!(packet["range"]["end"], 88);
        assert_eq!(packet["class"], "weakly_gripped");
        assert_eq!(packet["seam_kind"], "predicate_boundary");
        assert_eq!(packet["owner"], "pricing::discounted_total");
        assert_eq!(packet["evidence_path"]["reach"], "present");
        assert_eq!(packet["evidence_path"]["activate"], "present");
        assert_eq!(packet["evidence_path"]["propagate"], "present");
        assert_eq!(packet["evidence_path"]["observe"], "present");
        assert_eq!(packet["evidence_path"]["discriminate"], "weak");
        assert_eq!(
            packet["missing_discriminator"],
            "discount_threshold (equality boundary)"
        );
        assert_eq!(
            packet["related_test"],
            "tests/pricing.rs::below_threshold_has_no_discount"
        );
        assert_eq!(
            packet["related_test_location"]["oracle_strength"],
            "strong"
        );
        assert_eq!(packet["suggested_test"]["file"], "tests/pricing.rs");
        assert!(
            packet["suggested_assertion"]
                .as_str()
                .is_some_and(|value| value.contains("assert"))
        );
        assert!(
            packet["agent_brief_command"]
                .as_str()
                .is_some_and(|value| value.starts_with("ripr agent brief --root . --seam-id "))
        );
        assert_eq!(
            packet["after_snapshot_command"],
            "ripr check --root . --base origin/main --mode draft --format repo-exposure-json > target/ripr/pilot/after.repo-exposure.json"
        );
        assert_eq!(
            packet["verify_command"],
            "ripr agent verify --root . --before target/ripr/pilot/repo-exposure.json --after target/ripr/pilot/after.repo-exposure.json --json > target/ripr/agent/agent-verify.json"
        );
        assert!(
            packet["receipt_command"]
                .as_str()
                .is_some_and(|value| {
                    value.contains("ripr agent receipt --root . --verify-json target/ripr/agent/agent-verify.json")
                        && value.contains("--out target/ripr/agent/agent-receipt.json")
                })
        );
        assert_eq!(
            packet["limits_note"],
            "Static evidence only; no runtime mutation execution."
        );
        Ok(())
    })
}

#[test]
fn execute_command_collect_evidence_context_returns_none_for_unknown_seam() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        let seam = sample_classified_seam();
        let diagnostic = diagnostic_for_classified_seam(Path::new("/workspace"), &seam)
            .ok_or_else(|| "expected seam diagnostic".to_string())?;
        let uri = test_uri("file:///workspace/src/pricing.rs")?;
        let mut diagnostics = sample_workspace_diagnostics(
            PathBuf::from("/workspace"),
            uri,
            vec![diagnostic],
            Vec::new(),
        );
        diagnostics.snapshot.classified_seams = vec![seam];
        let Some(_) = backend.refresh_plan(diagnostics) else {
            return Err("expected refresh plan".to_string());
        };

        let params = ExecuteCommandParams {
            command: COLLECT_EVIDENCE_CONTEXT_COMMAND.to_string(),
            arguments: vec![serde_json::json!({
                "seam_id": "unknown-seam",
            })],
            work_done_progress_params: Default::default(),
        };
        let result = backend.execute_command(params).await;
        let packet = result.map_err(|err| format!("execute_command failed: {err}"))?;
        assert!(packet.is_none(), "expected None for unknown seam");
        Ok(())
    })
}

#[test]
fn execute_command_collect_context_returns_none_for_unknown_finding() -> Result<(), String> {
    let runtime = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .map_err(|err| format!("failed to start test runtime: {err}"))?;
    runtime.block_on(async {
        let (service, _socket) = LspService::new(|client| Backend::new(client, PathBuf::from(".")));
        let backend = service.inner();
        let finding = sample_finding();
        let diagnostic = diagnostic_for_finding(Path::new("/workspace"), &finding);
        let uri = test_uri("file:///workspace/src/pricing.rs")?;
        let diagnostics = sample_workspace_diagnostics(
            PathBuf::from("/workspace"),
            uri.clone(),
            vec![diagnostic.clone()],
            vec![finding],
        );
        let Some(_) = backend.refresh_plan(diagnostics) else {
            return Err("expected refresh plan".to_string());
        };

        let params = ExecuteCommandParams {
            command: COLLECT_CONTEXT_COMMAND.to_string(),
            arguments: vec![serde_json::json!({
                "finding_id": "probe:unknown:1:predicate",
            })],
            work_done_progress_params: Default::default(),
        };
        let result = backend.execute_command(params).await;
        let packet = result.map_err(|err| format!("execute_command failed: {err}"))?;
        assert!(packet.is_none(), "expected None for unknown finding");
        Ok(())
    })
}

#[test]
fn execute_command_refresh_remains_unchanged() -> Result<(), String> {
    let Some(provider) = initialize_result().capabilities.execute_command_provider else {
        return Err("expected execute command provider".to_string());
    };

    assert!(
        provider
            .commands
            .iter()
            .any(|command| command == REFRESH_COMMAND)
    );
    Ok(())
}