lanekeep-engine 0.5.0

Rule execution engine for lanekeep.
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
//! Rule execution engine for lanekeep.
//!
//! Discovery, gates, parsing, query matching and handler invocation, run over a corpus.
//!
//! # Why this is not in `lanekeep-core`
//!
//! Architecture §3 places the walker in `lanekeep-core`. That does not work: running rules
//! requires the sandbox, and the sandbox is built *on* core — putting the walker there
//! would make `lanekeep-core` and `lanekeep-js` mutually dependent.
//!
//! It cannot live in `lanekeep-cli` either, because `lanekeep-testkit` has to run rules
//! too, and a test harness that reached into the binary crate would be a worse coupling
//! than this one. So the walker sits above the sandbox and below both consumers.
//!
//! Core keeps what it always had: the types, discovery, gates, and the ordering contract.
//!
//! # The shape of a run
//!
//! ```text
//! discover paths (sorted)
//!   └─> for each file, in parallel:
//!         path gates ──reject──> skip without reading
//!         read bytes
//!         content gates ──reject──> skip without parsing
//!         parse once, shared by every rule targeting the file
//!         for each admitted rule: match its query, invoke the handler per match
//!   └─> sort violations
//! ```
//!
//! One parse per file, not per rule. Parsing is the dominant cost, and a file with twenty
//! applicable rules must not pay it twenty times.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;

use lanekeep_cache::{CacheKey, Entry as CacheEntry, GrammarKey, RunKey, Store};
use lanekeep_config::{Config, ConfigError, RuleSpec};
use lanekeep_core::suppression::{self, Date, Suppressions};
use lanekeep_core::{
    CompiledGates, Discovery, DiscoveryError, Fact, FilePath, Location, Position, RuleId, Severity,
    TrackedRead, Violation,
};
use lanekeep_js::{
    FileAccess, HOST_API_VERSION, HostContext, Limits, ReduceContext, ReduceFact, RuleRoot,
    RunClock, Sandbox, SandboxError,
};
use lanekeep_lang::{Language, LanguageRegistry};
use lanekeep_query::{CompileError, CompiledQuery};
use rayon::prelude::*;
use thiserror::Error;

/// Why a run could not complete.
///
/// Every variant aborts the run. A checker that could not finish must not be mistaken for
/// one that found nothing — see architecture §6.8.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum RunError {
    /// Discovery could not run.
    #[error(transparent)]
    Discovery(#[from] DiscoveryError),

    /// A rule's query does not compile.
    #[error("rule `{rule}` has an invalid query\n{detail}")]
    Query {
        /// Which rule.
        rule: String,
        /// The rendered compile error.
        detail: String,
    },

    /// A rule names a language nothing provides.
    #[error("rule `{rule}` targets unknown language `{language}`\n  known languages: {known}")]
    UnknownLanguage {
        /// Which rule.
        rule: String,
        /// The language as written.
        language: String,
        /// What is available.
        known: String,
    },

    /// A rule's gates are malformed.
    #[error("rule `{rule}` has invalid gates: {detail}")]
    Gates {
        /// Which rule.
        rule: String,
        /// What is wrong.
        detail: String,
    },

    /// The sandbox failed, including on a breached budget.
    #[error("rule `{rule}` failed on `{file}`\n{detail}")]
    Rule {
        /// Which rule.
        rule: String,
        /// Which file it was running against.
        file: String,
        /// The sandbox's account of it.
        detail: String,
    },

    /// A worker could not be set up.
    #[error("could not start a worker: {detail}")]
    Worker {
        /// What went wrong.
        detail: String,
    },
}

/// A rule prepared for execution: metadata plus everything compiled.
///
/// The query is compiled once per language the rule targets, because a query is compiled
/// against a grammar and the grammars differ. Which one a given file uses is decided by the
/// file, not by the rule — see [`Prepared::for_language`].
struct Prepared {
    spec: RuleSpec,
    gates: CompiledGates,
    /// Compiled query per language, in the order the rule declared them.
    compiled: Vec<(Arc<dyn Language>, CompiledQuery)>,
}

impl Prepared {
    /// The grammar and query to use for a file of the given language, or `None` when this
    /// rule does not target it — in which case the rule does not run on that file at all.
    ///
    /// Running it anyway is what the old behavior did, and it does not fail loudly: the file
    /// parses into a tree of `ERROR` nodes and every query quietly matches nothing.
    fn for_language(&self, id: &str) -> Option<&(Arc<dyn Language>, CompiledQuery)> {
        self.compiled
            .iter()
            .find(|(language, _)| language.id().as_str() == id)
    }
}

/// Everything a run needs, built once and shared across workers.
#[expect(
    clippy::struct_excessive_bools,
    reason = "four independent run modes — caching, reducing, unused reporting, profiling — \
              every combination of which is meaningful and reachable from the CLI. The lint \
              is aimed at a type where a pile of bools stands in for a missing enum; these \
              are orthogonal switches, and an enum over their sixteen combinations would be \
              strictly worse to read and to set."
)]
pub struct Engine {
    rules: Vec<Prepared>,
    discovery: Discovery,
    /// The project root, canonicalized once. Every tracked read is checked against it, and
    /// canonicalizing per file would put a syscall on the hot path for a constant.
    root: PathBuf,
    /// Everything constant about this run that a cache key depends on.
    run_key: RunKey,
    /// Whether results may be read from and written to the cache.
    caching: bool,
    /// Whether reduce phases run.
    reducing: bool,
    /// Whether directives that silenced nothing are reported.
    reporting_unused: bool,
    /// Whether per-rule timings are collected.
    profiling: bool,
    /// The date `expires:` is compared against.
    ///
    /// Fixed once for the run, so two files checked a millisecond apart cannot disagree
    /// about what day it is. Supplied by the host because the sandbox has no clock.
    today: Date,
    limits: Limits,
    rules_root: RuleRoot,
    config_path: PathBuf,
    typescript: Arc<dyn Language>,
    javascript: Arc<dyn Language>,
    /// Extension to language id, so a file can be matched to a grammar without the registry.
    ///
    /// Lowercased keys, because the registry lowercases too — whether `Button.TSX` gets
    /// checked should not depend on how someone typed it.
    languages_by_extension: BTreeMap<String, String>,
}

impl std::fmt::Debug for Engine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Engine")
            .field("rules", &self.rules.len())
            .field("root", &self.discovery.root())
            .finish_non_exhaustive()
    }
}

/// Where a run spent its time, per rule.
///
/// The split is the point. A rule that is slow in `query` has a query matching more than it
/// needs and wants narrowing; a rule that is slow in `handler` has code to look at. Reporting
/// one total would leave an author guessing which, and the two have nothing in common as
/// fixes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RuleTiming {
    /// Time matching this rule's query, in Rust.
    pub query: Duration,
    /// Time inside its handler, in the sandbox.
    pub handler: Duration,
    /// How many matches crossed the boundary.
    ///
    /// The number the query gate exists to keep small — §7.2 — so it belongs beside the
    /// times rather than being inferred from them.
    pub matches: u64,
}

impl RuleTiming {
    /// Everything this rule cost.
    #[must_use]
    pub const fn total(&self) -> Duration {
        self.query.saturating_add(self.handler)
    }
}

/// What a run produced.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Outcome {
    /// Violations, in canonical order.
    pub violations: Vec<Violation>,
    /// How many files discovery selected.
    pub files_discovered: usize,
    /// How many were actually parsed, after gates.
    pub files_parsed: usize,

    /// Where the run spent its time, per rule, when `--profile` asked.
    ///
    /// Absent otherwise: timing every match costs a clock read per invocation, which is
    /// exactly the kind of thing that should not be on the path a warm run takes.
    pub timings: Option<BTreeMap<RuleId, RuleTiming>>,

    /// What each checked file's rules read beyond that file, in path order.
    ///
    /// Exactly the shape a cache entry needs: dependencies belong to the file whose result
    /// they affect, not to the run. A file with no tracked reads has no entry here rather
    /// than an empty one, so the common case costs nothing.
    pub dependencies: BTreeMap<FilePath, Vec<TrackedRead>>,
}

impl Engine {
    /// Prepare a run.
    ///
    /// Everything that can fail on a rule's own contents fails here, before any file is
    /// read — a run that dies halfway through because rule seventeen has a typo has
    /// already wasted the work.
    ///
    /// # Errors
    ///
    /// Returns [`RunError`] for an invalid query, gate, or language reference.
    pub fn prepare(
        config: &Config,
        project_root: &Path,
        rules_root: RuleRoot,
        config_path: &Path,
        registry: &LanguageRegistry,
        typescript: Arc<dyn Language>,
        javascript: Arc<dyn Language>,
    ) -> Result<Self, RunError> {
        let discovery = Discovery::new(project_root, &config.include, &config.exclude)?;

        let known = registry
            .languages()
            .map(|l| l.id().as_str())
            .collect::<Vec<_>>()
            .join(", ");

        let mut languages_by_extension = BTreeMap::new();
        for language in registry.languages() {
            for extension in language.extensions() {
                languages_by_extension
                    .insert(extension.to_ascii_lowercase(), language.id().to_string());
            }
        }

        let mut rules = Vec::with_capacity(config.rules.len());
        for spec in &config.rules {
            if !spec.severity.is_enabled() {
                continue;
            }

            let mut compiled = Vec::with_capacity(spec.languages.len());
            for id in &spec.languages {
                let language =
                    registry
                        .by_id(id)
                        .cloned()
                        .ok_or_else(|| RunError::UnknownLanguage {
                            rule: spec.id.to_string(),
                            language: id.clone(),
                            known: known.clone(),
                        })?;

                // Compiled against this grammar specifically. A query that is valid for one
                // dialect and not another is a rule bug, and this is where it surfaces —
                // at config load, naming the rule, rather than as silence at run time.
                let query = CompiledQuery::compile(language.as_ref(), &spec.query).map_err(
                    |e: CompileError| RunError::Query {
                        rule: spec.id.to_string(),
                        detail: e.to_string(),
                    },
                )?;

                compiled.push((language, query));
            }

            let gates = CompiledGates::compile(&spec.gates).map_err(|e| RunError::Gates {
                rule: spec.id.to_string(),
                detail: e.to_string(),
            })?;

            rules.push(Prepared {
                spec: spec.clone(),
                gates,
                compiled,
            });
        }

        // Every registered grammar, so a tree-sitter bump invalidates rather than silently
        // reusing results computed against different node shapes.
        let mut grammars: Vec<GrammarKey> = registry
            .languages()
            .map(|language| GrammarKey {
                id: language.id().to_string(),
                abi: u32::try_from(language.grammar_abi()).unwrap_or(u32::MAX),
            })
            .collect();
        grammars.sort_by(|a, b| a.id.cmp(&b.id));

        let run_key = RunKey::new(
            // Major.minor only: a patch release changes nothing a rule can observe, and
            // invalidating every cache on one would make patch upgrades expensive for
            // nothing.
            engine_version(),
            HOST_API_VERSION,
            &config.ruleset_hash,
            &config.config_hash,
            &grammars,
        );

        Ok(Self {
            rules,
            run_key,
            caching: true,
            reducing: true,
            reporting_unused: false,
            profiling: false,
            today: suppression::today(),
            // Canonicalized here so every tracked read compares against the same absolute
            // root. Falling back to the path as given keeps a non-existent root a discovery
            // problem rather than turning it into a confusing read failure later.
            root: project_root
                .canonicalize()
                .unwrap_or_else(|_| project_root.to_path_buf()),
            discovery,
            limits: config.limits,
            rules_root,
            config_path: config_path.to_path_buf(),
            typescript,
            javascript,
            languages_by_extension,
        })
    }

    /// Which language parses this file, or `None` when nothing registered claims it.
    fn language_of(&self, path: &FilePath) -> Option<&str> {
        let extension = Path::new(path.as_str())
            .extension()?
            .to_str()?
            .to_ascii_lowercase();
        self.languages_by_extension
            .get(extension.as_str())
            .map(String::as_str)
    }

    /// Turn the cache off, for `--no-cache` and for tests that need a cold run.
    #[must_use]
    pub const fn without_cache(mut self) -> Self {
        self.caching = false;
        self
    }

    /// Collect per-rule timings.
    ///
    /// Off by default because measuring costs a clock read per handler invocation, and the
    /// path a warm run takes is the one place that matters most.
    #[must_use]
    pub const fn profiling(mut self) -> Self {
        self.profiling = true;
        self
    }

    /// Report suppressions that silenced nothing.
    ///
    /// Off by default because it is hygiene rather than correctness: a suppression whose
    /// violation no longer exists is debt, and debt is worth surfacing on request rather
    /// than in everyone's inner loop.
    #[must_use]
    pub const fn reporting_unused_suppressions(mut self) -> Self {
        self.reporting_unused = true;
        self
    }

    /// Fix the date `expires:` is compared against.
    ///
    /// For tests, which otherwise could not assert anything about expiry without waiting.
    #[must_use]
    pub const fn with_today(mut self, today: Date) -> Self {
        self.today = today;
        self
    }

    /// Skip every reduce phase.
    ///
    /// For a run over a deliberately partial corpus. A cross-file rule consumes facts from
    /// every file, so running one over a subset does not give a smaller answer — it gives a
    /// wrong one. `no-unused-exports` over three changed files would report every export in
    /// them as unused, because the importers were never looked at.
    ///
    /// Skipping is therefore the only sound option, and the caller that narrowed the corpus
    /// is the one that has to say so to the user.
    #[must_use]
    pub const fn without_reduce(mut self) -> Self {
        self.reducing = false;
        self
    }

    /// The files discovery selects, before any gate.
    ///
    /// For a caller narrowing the corpus: intersecting with this is what keeps `include` and
    /// `exclude` in force, so `--staged` cannot check a file the config excluded.
    #[must_use]
    pub fn discover(&self) -> Vec<FilePath> {
        self.discovery.walk()
    }

    /// How many rules will actually run. Rules set to `off` are dropped at preparation.
    #[must_use]
    pub fn rule_count(&self) -> usize {
        self.rules.len()
    }

    /// The rules that will run, in the order the config declared them.
    ///
    /// The specs rather than a rendered listing: what a listing should look like is the
    /// reporter's problem, and an engine that decided it would have to be changed for every
    /// new output format.
    pub fn rules(&self) -> impl Iterator<Item = &RuleSpec> {
        self.rules.iter().map(|prepared| &prepared.spec)
    }

    /// Run over the whole corpus.
    ///
    /// # Errors
    ///
    /// Returns the first [`RunError`] any worker produced. Rayon's reduction is not
    /// order-dependent, so which of several simultaneous failures surfaces is arbitrary —
    /// but every one of them aborts the run, so the choice does not change the outcome.
    pub fn run(&self) -> Result<Outcome, RunError> {
        let files = self.discovery.walk();
        self.run_files(&files, Coverage::Whole)
    }

    /// Run over an explicit file list, for `--since` and `--staged`.
    ///
    /// # Errors
    ///
    /// As [`Engine::run`].
    pub fn run_over(&self, files: &[FilePath]) -> Result<Outcome, RunError> {
        self.run_files(files, Coverage::Partial)
    }

    /// The shared body of [`Engine::run`] and [`Engine::run_over`].
    fn run_files(&self, files: &[FilePath], coverage: Coverage) -> Result<Outcome, RunError> {
        let clock = RunClock::start(self.limits.global_timeout);

        // Loaded once, before any worker starts. Shared read-only across the pool: a cache
        // that workers wrote to concurrently would need a lock on the hot path, and the
        // whole point is to be faster than recomputing.
        let cache = if self.caching {
            Store::load(&self.root)
        } else {
            Store::empty()
        };

        let results: Vec<Result<FileOutcome, RunError>> = files
            .par_iter()
            .map_init(
                // One sandbox per worker, created on first use and reused for that
                // worker's whole share. Building one per file would pay engine startup
                // thousands of times; sharing one across workers is impossible, since the
                // runtime is single-threaded by construction.
                // The sandbox is per worker and built on first use — one engine startup
                // per thread that needs one, rather than per file, and none at all for a
                // worker whose files all hit the cache. That last part is what makes a warm
                // run cheap: starting QuickJS and evaluating every rule module, per worker,
                // to then execute no JavaScript, was most of a warm run's cost.
                || Worker::new(self, &clock),
                |worker, path| self.check_file(worker, &cache, path),
            )
            .collect();

        let mut violations = Vec::new();
        let mut facts = Vec::new();
        let mut files_parsed = 0;
        let mut dependencies = BTreeMap::new();
        let mut fresh = Store::empty();
        let mut directives: BTreeMap<FilePath, FileDirectives> = BTreeMap::new();
        let mut timings: BTreeMap<RuleId, RuleTiming> = BTreeMap::new();
        for result in results {
            let outcome = result?;
            violations.extend(outcome.violations);
            facts.extend(outcome.facts);
            files_parsed += usize::from(outcome.parsed);
            if let Some(entry) = outcome.entry {
                fresh.insert(entry.0, entry.1);
            }
            for (rule, timing) in outcome.timings {
                let entry = timings.entry(rule).or_default();
                entry.query = entry.query.saturating_add(timing.query);
                entry.handler = entry.handler.saturating_add(timing.handler);
                entry.matches += timing.matches;
            }
            if !outcome.suppressions.is_empty() {
                directives.insert(
                    outcome.path.clone(),
                    FileDirectives {
                        suppressions: outcome.suppressions,
                        used: outcome.used_suppressions,
                    },
                );
            }
            if !outcome.reads.is_empty() {
                dependencies.insert(outcome.path, outcome.reads);
            }
        }

        if self.caching {
            match coverage {
                // The run saw everything, so what it did not produce an entry for no longer
                // exists. Saving only fresh entries is what ages deleted files out.
                Coverage::Whole => fresh.save(&self.root),
                // The run saw a subset. Saving only what it produced would discard the
                // entries for every file it never looked at — so `--staged` would leave the
                // next full run cold, which is the opposite of what an incremental entry
                // point is for.
                Coverage::Partial => {
                    let mut merged = cache;
                    for key in fresh.keys().copied().collect::<Vec<_>>() {
                        if let Some(entry) = fresh.get(&key) {
                            merged.insert(key, entry.clone());
                        }
                    }
                    merged.save(&self.root);
                }
            }
        }

        // Into the one order every run will see, before any rule looks at them.
        //
        // Rayon's `collect` into a `Vec` already preserves input order, so on today's code
        // path this sort changes nothing — which is exactly why it is easy to delete and
        // must not be. The ordering guarantee belongs to the engine, not to a property of
        // whichever collection strategy it happens to use: switching to `for_each` with a
        // shared sink, or grouping by rule before reducing, would silently lose it. The
        // cost is one sort of a small vector, once per run.
        lanekeep_core::fact::sort(&mut facts);

        // A cross-file rule reports at a site in some other file, which may well have been a
        // cache hit this run — so its directives come from the outcome, whether they were
        // parsed now or restored from the entry.
        let reduced = self.reduce(&clock, files, &facts)?;
        for violation in reduced {
            // A cross-file violation can be the only thing a directive ever silences, so
            // usage is recorded here too — otherwise it would be reported as unused.
            match covering_elsewhere(&directives, &violation) {
                Some((file, index)) => {
                    if let Some(found) = directives.get_mut(&file)
                        && !found.used.contains(&index)
                    {
                        found.used.push(index);
                    }
                }
                None => violations.push(violation),
            }
        }

        if self.reporting_unused {
            violations.extend(unused_violations(&directives));
        }

        lanekeep_core::sort(&mut violations);
        Ok(Outcome {
            violations,
            files_discovered: files.len(),
            files_parsed,
            timings: self.profiling.then_some(timings),
            dependencies,
        })
    }

    /// Run the reduce phase for every rule that has one.
    ///
    /// Single-threaded, and deliberately so: there is one pass per rule, each already sees
    /// the whole corpus, and a rule's `reduce` is the one place a rule is allowed to be
    /// expensive. Parallelizing across rules would buy little and would need one sandbox per
    /// worker with the whole fact set copied into each.
    fn reduce(
        &self,
        clock: &Arc<RunClock>,
        files: &[FilePath],
        facts: &[Fact],
    ) -> Result<Vec<Violation>, RunError> {
        if !self.reducing {
            return Ok(Vec::new());
        }

        let reducing: Vec<&Prepared> = self
            .rules
            .iter()
            .filter(|rule| rule.spec.has_reduce)
            .collect();
        if reducing.is_empty() {
            // The common case. Building a sandbox to do nothing would put engine startup on
            // the critical path of every run that has no cross-file rule at all.
            return Ok(Vec::new());
        }

        let sandbox = self.build_sandbox(clock)?;
        let paths: Vec<String> = files.iter().map(|f| f.as_str().to_owned()).collect();
        let mut violations = Vec::new();

        for rule in reducing {
            // A rule sees only its own facts. Letting one read another's would make an
            // internal payload shape into a contract between rules, and would make the
            // result depend on the order rules happened to be declared in.
            let own: Vec<ReduceFact> = facts
                .iter()
                .filter(|fact| fact.rule_id == rule.spec.id)
                .map(|fact| ReduceFact {
                    kind: fact.kind.clone(),
                    json: lanekeep_js::merge_file(&fact.data, fact.file.as_str()),
                })
                .collect();

            let host = ReduceContext::new(paths.clone(), own);
            let timeout = rule.spec.timeout.unwrap_or(self.limits.rule_timeout);
            let call = format!(
                "globalThis.__lanekeepConfig.rules[{}].reduce(ctx)",
                rule_index(&rule.spec)
            );

            sandbox
                .eval_with_reduce_host::<()>(&host, &call, timeout)
                .map_err(|e: SandboxError| RunError::Rule {
                    rule: rule.spec.id.to_string(),
                    // No single file is at fault in a reduce phase, and naming one would be
                    // a lie the reader would then go and look at.
                    file: "<reduce>".to_owned(),
                    detail: e.to_string(),
                })?;

            for report in host.take_reports() {
                // The path is the rule's, normalized but not checked against the corpus. A
                // cross-file rule may legitimately report at a file the walker excluded —
                // a config, a generated file. Autofix will need to disagree: it must never
                // write to a path a rule invented. That check belongs with the writing.
                violations.push(Violation {
                    rule_id: rule.spec.id.clone(),
                    location: Location::new(
                        FilePath::new(&report.file),
                        Position::new(report.line, report.column),
                    ),
                    message: report
                        .message
                        .unwrap_or_else(|| rule.spec.card.message.clone()),
                    remediation: rule.spec.card.remediation.clone(),
                    severity: rule.spec.severity,
                    // A reduce phase has no parse tree, so there is no node to replace and
                    // nothing to compute a byte range from. A cross-file finding is fixed by
                    // hand.
                    fix: None,
                });
            }
        }

        Ok(violations)
    }

    /// Build the sandbox a worker uses, evaluating the ruleset into it.
    fn build_sandbox(&self, clock: &Arc<RunClock>) -> Result<Sandbox, RunError> {
        let sandbox = Sandbox::with_modules(
            self.limits,
            Arc::clone(clock),
            self.rules_root.clone(),
            Arc::clone(&self.typescript),
            Arc::clone(&self.javascript),
        )
        .map_err(|e| RunError::Worker {
            detail: e.to_string(),
        })?;

        // Every worker evaluates the ruleset into its own engine. A rule's `check` is a
        // function, and a function cannot cross between runtimes — so the modules are
        // loaded per worker rather than the handlers being extracted and shared.
        lanekeep_config::evaluate_into(&sandbox, &self.rules_root, &self.config_path).map_err(
            |e: ConfigError| RunError::Worker {
                detail: e.to_string(),
            },
        )?;

        Ok(sandbox)
    }

    /// Check one file. Returns its violations, facts and tracked reads.
    fn check_file(
        &self,
        worker: &mut Worker<'_>,
        cache: &Store,
        path: &FilePath,
    ) -> Result<FileOutcome, RunError> {
        // A fresh set of tracked reads for this file, sharing the root already canonicalized
        // at preparation.
        let files = Rc::new(FileAccess::rooted(self.root.clone()));

        // Path gates first: rejecting here costs no read at all.
        let admitted: Vec<&Prepared> = self
            .rules
            .iter()
            .filter(|rule| rule.gates.admits_path(path))
            .collect();
        if admitted.is_empty() {
            return Ok(FileOutcome::skipped(path.clone()));
        }

        let absolute = self.discovery.root().join(path.as_str());
        let Ok(bytes) = std::fs::read(&absolute) else {
            // A file that vanished between discovery and reading is not a failure. The
            // tree is allowed to change under a run; what must not happen is a partial
            // result being reported as complete, and a missing file contributes nothing
            // either way.
            return Ok(FileOutcome::skipped(path.clone()));
        };

        // The cache is consulted after the path gates and the read, because the key needs
        // the file's bytes — but before the content gates and the parse, which is where the
        // saving is. A hit costs one hash and one dependency check.
        // A file's result can depend on what day it is, two ways: an expiring suppression in
        // its bytes, or a rule that read `ctx.today` while checking it. Such a file gets a
        // key with the date folded in, so its entry lives for one day; every other file gets
        // a dateless key and its entry survives indefinitely.
        //
        // Folding the date into every key instead would invalidate the whole corpus daily
        // for the sake of a handful of files. Leaving it out entirely would serve yesterday's
        // answer — an expiry that never expires, a date comparison frozen at whenever the
        // cache was written.
        //
        // The expiry is visible in the bytes, so it is known now. Whether a rule reads the
        // date is not knowable until the rules have run, which is why both keys exist and
        // the lookup tries the dated one first: a file that was date-dependent last run has
        // its entry there, and if the date has moved that key simply misses.
        let keys = self.caching.then(|| {
            let content = lanekeep_cache::hash_bytes(&bytes);
            (
                self.run_key.for_file(path.as_str(), &content),
                self.run_key
                    .for_dated_file(path.as_str(), &content, &self.today.to_string()),
            )
        });
        let has_expiry = memchr::memmem::find(&bytes, b"expires:").is_some();

        if let Some((plain, dated)) = keys {
            // Dated first. A file with an expiring suppression is *only* ever stored dated,
            // so trying the plain key for it would be a lookup that can never hit.
            let candidates: &[CacheKey] = if has_expiry {
                &[dated]
            } else {
                &[dated, plain]
            };
            for key in candidates {
                if let Some(entry) = cache.get(key)
                    && lanekeep_cache::validate(entry, &self.root)
                {
                    return Ok(FileOutcome::cached(path.clone(), *key, entry.clone()));
                }
            }
        }

        // Content gates: one read, a substring scan, and a parse saved.
        let admitted: Vec<&Prepared> = admitted
            .into_iter()
            .filter(|rule| rule.gates.admits_content(&bytes))
            .collect();
        if admitted.is_empty() {
            // Still worth an entry: "nothing applies to this file" is a result, and
            // recomputing the gates every run for a file that never matches is the cost the
            // cache exists to remove. No rule ran, so nothing read the date — unless the
            // file carries an expiry, which is a property of its bytes.
            return Ok(FileOutcome::empty_entry(
                path.clone(),
                keys.map(|(plain, dated)| if has_expiry { dated } else { plain }),
            ));
        }

        let Ok(source) = String::from_utf8(bytes) else {
            // Not valid UTF-8, so not source this tool can reason about.
            return Ok(FileOutcome::skipped(path.clone()));
        };

        // Parsed once per file, whatever rules ran: a directive is a property of the file,
        // not of any rule.
        let directives = suppression::parse(&source);

        let mut outcome = FileOutcome::parsed(path.clone());
        for rule in admitted {
            let (violations, facts, read_the_date, timing) =
                self.run_rule(worker, &files, rule, path, &source)?;
            outcome.violations.extend(violations);
            outcome.facts.extend(facts);
            outcome.read_the_date |= read_the_date;
            if self.profiling {
                outcome.timings.push((rule.spec.id.clone(), timing));
            }
        }

        // Applied after every rule has run, so a directive covers whatever any of them
        // reported at that line. Which directive fired is recorded rather than discarded:
        // it is the only moment the information exists, since a warm run sees the survivors
        // and not what was hidden.
        let mut used = Vec::new();
        outcome.violations.retain(|violation| {
            match directives.covering(&violation.rule_id, violation.location.position.line) {
                Some(index) => {
                    let index = u32::try_from(index).unwrap_or(u32::MAX);
                    if !used.contains(&index) {
                        used.push(index);
                    }
                    false
                }
                None => true,
            }
        });
        used.sort_unstable();
        outcome.used_suppressions = used;
        outcome
            .violations
            .extend(self.directive_violations(&directives, path));

        outcome.suppressions = directives.valid;
        outcome.reads = files.dependencies();
        // Dated if anything about this file's result depended on the date: an expiring
        // directive, or a rule that read `ctx.today`.
        let date_dependent = has_expiry || outcome.read_the_date;
        outcome.entry = keys.map(|(plain, dated)| {
            (
                if date_dependent { dated } else { plain },
                CacheEntry {
                    violations: outcome.violations.clone(),
                    facts: outcome.facts.clone(),
                    dependencies: outcome.reads.clone(),
                    suppressions: outcome.suppressions.clone(),
                    used_suppressions: outcome.used_suppressions.clone(),
                },
            )
        });

        Ok(outcome)
    }

    /// Violations about the directives themselves.
    ///
    /// A suppression that does not work has to say so. A malformed directive silences
    /// nothing while looking like it does, and an expired one is a deadline the author set
    /// and then passed — reporting both is the whole reason the fields are checked rather
    /// than best-effort parsed.
    fn directive_violations(&self, directives: &Suppressions, path: &FilePath) -> Vec<Violation> {
        let mut violations = Vec::new();

        // Parsed once here rather than per violation. `SUPPRESSION_RULE` is a literal this
        // crate controls, so a failure would be a build-time mistake — falling back to the
        // rules' own namespace keeps that from being a panic in a checker.
        let Ok(rule_id) = SUPPRESSION_RULE.parse::<RuleId>() else {
            return violations;
        };

        for bad in &directives.malformed {
            violations.push(Violation {
                rule_id: rule_id.clone(),
                location: Location::new(path.clone(), Position::new(bad.line, bad.column)),
                message: bad.problem.clone(),
                remediation: String::from(
                    "fix the directive, or remove it and fix what it was hiding",
                ),
                severity: Severity::Error,
                fix: None,
            });
        }

        for suppression in &directives.valid {
            let Some(expires) = suppression.expires else {
                continue;
            };
            if expires >= self.today {
                continue;
            }

            violations.push(Violation {
                rule_id: rule_id.clone(),
                location: Location::new(
                    path.clone(),
                    Position::new(suppression.line, suppression.column),
                ),
                message: format!(
                    "suppression expired on {expires}\"{}\"",
                    suppression.reason
                ),
                remediation: String::from(
                    "fix what it was suppressing, or decide it is permanent and drop the \
                     expiry",
                ),
                severity: Severity::Error,
                fix: None,
            });
        }

        violations
    }

    fn run_rule(
        &self,
        worker: &mut Worker<'_>,
        files: &Rc<FileAccess>,
        rule: &Prepared,
        path: &FilePath,
        source: &str,
    ) -> Result<(Vec<Violation>, Vec<Fact>, bool, RuleTiming), RunError> {
        // The grammar is chosen by the file, not by the rule. A rule that does not target
        // this file's language does not run on it at all — previously it ran anyway, against
        // a grammar that could not parse the file, and matched nothing without saying so.
        let Some(language_id) = self.language_of(path) else {
            return Ok((Vec::new(), Vec::new(), false, RuleTiming::default()));
        };
        let Some((language, compiled_query)) = rule.for_language(language_id) else {
            return Ok((Vec::new(), Vec::new(), false, RuleTiming::default()));
        };

        let mut parser = tree_sitter::Parser::new();
        if parser.set_language(&language.grammar()).is_err() {
            return Ok((Vec::new(), Vec::new(), false, RuleTiming::default()));
        }
        let Some(tree) = parser.parse(source, None) else {
            return Ok((Vec::new(), Vec::new(), false, RuleTiming::default()));
        };

        // Only when asked. A clock read per invocation is cheap and not free, and this is
        // the hot path.
        let mut timing = RuleTiming::default();
        let clock = |on: bool| on.then(std::time::Instant::now);

        // Collect capture paths while the tree is borrowed, then intern once the borrow
        // has ended — the two-phase shape the arena's ownership of the tree forces.
        let mut matches: Vec<Vec<(String, Vec<u32>)>> = Vec::new();
        let host = HostContext::new(tree, source.to_owned(), path.as_str())
            .with_resolver_from(language.as_ref())
            .with_language(Arc::clone(language))
            .with_today(&self.today.to_string())
            .with_file_access(Rc::clone(files));

        let query_started = clock(self.profiling);
        {
            let arena = host.arena().borrow();
            compiled_query.for_each_match(arena.tree(), source.as_bytes(), |m| {
                let captures = m
                    .captures
                    .iter()
                    .filter_map(|(name, node)| {
                        arena.path_of(*node).map(|path| ((*name).to_owned(), path))
                    })
                    .collect();
                matches.push(captures);
            });
        }

        if let Some(started) = query_started {
            timing.query = started.elapsed();
            timing.matches = matches.len() as u64;
        }

        if matches.is_empty() {
            return Ok((Vec::new(), Vec::new(), false, timing));
        }

        // Only now, with matches in hand, is a sandbox needed. Everything above — parsing,
        // query matching — is Rust, and a file that matches nothing never starts one.
        let sandbox = worker.sandbox()?;

        let timeout = rule.spec.timeout.unwrap_or(self.limits.rule_timeout);
        let mut violations = Vec::new();

        for captures in matches {
            let handles: Vec<(String, u32)> = {
                let mut arena = host.arena().borrow_mut();
                captures
                    .into_iter()
                    .filter_map(|(name, path)| arena.intern_path(path).map(|h| (name, h)))
                    .collect()
            };

            let literal = handles
                .iter()
                .map(|(name, handle)| format!("{}: {handle}", json_key(name)))
                .collect::<Vec<_>>()
                .join(", ");

            // The handler is invoked through the module the config already loaded, so the
            // rule object here is the same one the config validated.
            let call = format!(
                "globalThis.__lanekeepConfig.rules[{}].check(ctx, {{{literal}}})",
                rule_index(&rule.spec)
            );

            let handler_started = clock(self.profiling);
            let outcome = sandbox.eval_with_host_timeout::<()>(&host, &call, timeout);
            if let Some(started) = handler_started {
                timing.handler = timing.handler.saturating_add(started.elapsed());
            }

            outcome.map_err(|e: SandboxError| RunError::Rule {
                rule: rule.spec.id.to_string(),
                file: path.as_str().to_owned(),
                detail: e.to_string(),
            })?;
        }

        let facts = host
            .take_facts()
            .into_iter()
            .enumerate()
            .map(|(sequence, emitted)| Fact {
                rule_id: rule.spec.id.clone(),
                file: path.clone(),
                kind: emitted.kind,
                data: emitted.data,
                // Emission order within the file. The engine assigns it rather than
                // trusting the rule, so a rule cannot reorder its own facts relative to
                // another file's and change what `reduce` sees.
                sequence: u32::try_from(sequence).unwrap_or(u32::MAX),
            })
            .collect();

        for report in host.take_reports() {
            violations.push(Violation {
                rule_id: rule.spec.id.clone(),
                location: Location::new(path.clone(), Position::new(report.line, report.column)),
                message: report
                    .message
                    .unwrap_or_else(|| rule.spec.card.message.clone()),
                remediation: rule.spec.card.remediation.clone(),
                severity: rule.spec.severity,
                fix: report.fix,
            });
        }

        Ok((violations, facts, host.date_was_read(), timing))
    }
}

/// Whether a run looked at the whole corpus or a chosen subset.
///
/// The distinction only matters when saving: a run that saw everything may prune, and a run
/// that saw a subset must not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Coverage {
    /// Everything discovery selected.
    Whole,
    /// An explicit subset, from `--since` or `--staged`.
    Partial,
}

/// One rayon worker's reusable state.
///
/// The sandbox is built on first use rather than up front. Starting QuickJS and evaluating
/// every rule module into it costs real time, and a worker whose files all hit the cache —
/// or whose queries match nothing — never executes a line of JavaScript and does not need
/// one.
struct Worker<'a> {
    engine: &'a Engine,
    clock: Arc<RunClock>,
    sandbox: Option<Sandbox>,
    /// A failure to build, remembered so it is reported once per worker rather than
    /// retried for every remaining file.
    failed: Option<RunError>,
}

impl<'a> Worker<'a> {
    fn new(engine: &'a Engine, clock: &Arc<RunClock>) -> Self {
        Self {
            engine,
            clock: Arc::clone(clock),
            sandbox: None,
            failed: None,
        }
    }

    /// This worker's sandbox, building it if this is the first rule that needs one.
    fn sandbox(&mut self) -> Result<&Sandbox, RunError> {
        if let Some(error) = &self.failed {
            return Err(error.clone());
        }

        if self.sandbox.is_none() {
            match self.engine.build_sandbox(&self.clock) {
                Ok(sandbox) => self.sandbox = Some(sandbox),
                Err(error) => {
                    self.failed = Some(error.clone());
                    return Err(error);
                }
            }
        }

        self.sandbox.as_ref().ok_or_else(|| RunError::Worker {
            detail: "sandbox was not built".to_owned(),
        })
    }
}

/// What checking one file produced.
struct FileOutcome {
    /// The file this is about, so the run can key dependencies by it.
    path: FilePath,
    violations: Vec<Violation>,
    facts: Vec<Fact>,
    /// What this file's rules read beyond it.
    reads: Vec<TrackedRead>,
    /// The file's suppression directives, for filtering reduce-phase violations.
    suppressions: Vec<suppression::Suppression>,
    /// Indices of the directives that silenced something.
    used_suppressions: Vec<u32>,
    /// Whether any rule read `ctx.today` while checking this file.
    read_the_date: bool,
    /// Per-rule timings, when profiling.
    timings: Vec<(RuleId, RuleTiming)>,
    /// What to store for this file, when caching is on.
    entry: Option<(CacheKey, CacheEntry)>,
    /// Whether the file was parsed at all, for the "n files checked" count.
    parsed: bool,
}

impl FileOutcome {
    /// A file that never reached a parser — gated out, unreadable, or not UTF-8.
    const fn skipped(path: FilePath) -> Self {
        Self {
            path,
            violations: Vec::new(),
            facts: Vec::new(),
            reads: Vec::new(),
            suppressions: Vec::new(),
            used_suppressions: Vec::new(),
            read_the_date: false,
            timings: Vec::new(),
            entry: None,
            parsed: false,
        }
    }

    const fn parsed(path: FilePath) -> Self {
        Self {
            path,
            violations: Vec::new(),
            facts: Vec::new(),
            reads: Vec::new(),
            suppressions: Vec::new(),
            used_suppressions: Vec::new(),
            read_the_date: false,
            timings: Vec::new(),
            entry: None,
            parsed: true,
        }
    }

    /// A file whose result came back from the cache.
    ///
    /// Counted as parsed, because from outside the run it was checked — reporting a warm
    /// run as having checked nothing would make the number useless.
    fn cached(path: FilePath, key: CacheKey, entry: CacheEntry) -> Self {
        Self {
            path,
            violations: entry.violations.clone(),
            facts: entry.facts.clone(),
            reads: entry.dependencies.clone(),
            suppressions: entry.suppressions.clone(),
            used_suppressions: entry.used_suppressions.clone(),
            // A cache hit ran no rules, so nothing read the date this time. Whether the
            // entry was dated is already settled by the key it was found under.
            read_the_date: false,
            timings: Vec::new(),
            entry: Some((key, entry)),
            parsed: true,
        }
    }

    /// A file that no rule's content gates admitted.
    fn empty_entry(path: FilePath, key: Option<CacheKey>) -> Self {
        Self {
            path,
            violations: Vec::new(),
            facts: Vec::new(),
            reads: Vec::new(),
            suppressions: Vec::new(),
            used_suppressions: Vec::new(),
            read_the_date: false,
            timings: Vec::new(),
            entry: key.map(|key| (key, CacheEntry::default())),
            parsed: false,
        }
    }
}

/// One file's directives, and which of them silenced something.
struct FileDirectives {
    suppressions: Vec<suppression::Suppression>,
    /// Indices into `suppressions`. Carried from the cache entry on a warm run.
    used: Vec<u32>,
}

/// Which directive silences a violation reported into some other file.
///
/// A cross-file rule reports at the site a fact came from, so the directives that matter are
/// that file's, not the one the rule happened to be reducing over.
fn covering_elsewhere(
    directives: &BTreeMap<FilePath, FileDirectives>,
    violation: &Violation,
) -> Option<(FilePath, u32)> {
    let found = directives.get(&violation.location.file)?;
    let index = found.suppressions.iter().position(|suppression| {
        suppression.covers(&violation.rule_id, violation.location.position.line)
    })?;

    Some((
        violation.location.file.clone(),
        u32::try_from(index).unwrap_or(u32::MAX),
    ))
}

/// Violations for directives that silenced nothing.
///
/// A suppression whose violation no longer exists is debt: it documents a decision about
/// code that has changed, and the next person to read it has no way to tell it is stale.
///
/// Reported as warnings rather than errors. Turning on a hygiene report should not fail a
/// build that was passing — the point is to show the debt, not to refuse to proceed until it
/// is paid.
fn unused_violations(directives: &BTreeMap<FilePath, FileDirectives>) -> Vec<Violation> {
    let Ok(rule_id) = SUPPRESSION_RULE.parse::<RuleId>() else {
        return Vec::new();
    };

    let mut violations = Vec::new();
    for (file, found) in directives {
        for (index, suppression) in found.suppressions.iter().enumerate() {
            let index = u32::try_from(index).unwrap_or(u32::MAX);
            if found.used.contains(&index) {
                continue;
            }

            violations.push(Violation {
                rule_id: rule_id.clone(),
                location: Location::new(
                    file.clone(),
                    Position::new(suppression.line, suppression.column),
                ),
                message: format!("suppression silenced nothing — \"{}\"", suppression.reason),
                remediation: String::from(
                    "remove it: whatever it was accepting is no longer reported",
                ),
                severity: Severity::Warn,
                fix: None,
            });
        }
    }
    violations
}

/// The engine version a cache key uses: major.minor only.
fn engine_version() -> &'static str {
    // Trimmed at the second dot. A patch release changes nothing a rule can observe, so
    // invalidating every cache in the world on one would cost users time for nothing.
    const FULL: &str = env!("CARGO_PKG_VERSION");
    match FULL.match_indices('.').nth(1) {
        Some((at, _)) => FULL.split_at(at).0,
        None => FULL,
    }
}

/// The id violations about suppressions are reported under.
///
/// A real namespaced id, so it sorts, suppresses and serializes like any other — and so a
/// consumer parsing output does not meet a special case.
const SUPPRESSION_RULE: &str = "lanekeep/suppression";

/// Position of a rule in the config's `rules` array, which is how the handler is reached.
fn rule_index(spec: &RuleSpec) -> usize {
    spec.index
}

/// Quote a capture name for use as an object key.
fn json_key(name: &str) -> String {
    format!("{name:?}")
}

/// Convenience for callers that only need a default severity check.
#[must_use]
pub fn any_failing(violations: &[Violation]) -> bool {
    violations.iter().any(|v| v.severity == Severity::Error)
}

/// Where the rules root sits, given a project root.
#[must_use]
pub fn rules_root_for(project_root: &Path) -> PathBuf {
    project_root.to_path_buf()
}

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

    use lanekeep_lang_js::{JavaScript, TypeScript};

    use super::*;

    struct Project {
        dir: PathBuf,
    }

    impl Project {
        fn new(name: &str, files: &[(&str, &str)]) -> Self {
            let dir = std::env::temp_dir().join(format!("lanekeep-engine-{name}"));
            let _ = fs::remove_dir_all(&dir);
            fs::create_dir_all(&dir).expect("creates dir");
            let project = Self { dir };
            for (path, contents) in files {
                project.write(path, contents);
            }
            project
        }

        fn write(&self, path: &str, contents: &str) {
            let full = self.dir.join(path);
            if let Some(parent) = full.parent() {
                fs::create_dir_all(parent).expect("creates parent");
            }
            fs::write(full, contents).expect("writes");
        }

        fn run(&self) -> Result<Outcome, RunError> {
            let root = RuleRoot::new(&self.dir).expect("canonicalizes");
            let config_path = self.dir.join("lanekeep.config.ts");

            let sandbox =
                lanekeep_config::sandbox_for(&root, Arc::new(TypeScript), Arc::new(JavaScript))
                    .expect("sandbox");
            let config = lanekeep_config::load(&sandbox, &root, &config_path)
                .unwrap_or_else(|e| panic!("config failed to load: {e}"));

            let engine = Engine::prepare(
                &config,
                &self.dir,
                root,
                &config_path,
                &lanekeep_lang_js::registry(),
                Arc::new(TypeScript),
                Arc::new(JavaScript),
            )?;
            engine.run()
        }
    }

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

    /// A rule reporting every `debugger` statement — small, unambiguous, and easy to seed.
    const DEBUGGER_RULE: &str = "import { defineRule } from 'lanekeep';\n\
        export default defineRule({\n\
          id: 'local/no-debugger',\n\
          query: '(debugger_statement) @stmt',\n\
          card: {\n\
            message: 'debugger statement',\n\
            remediation: 'remove it before committing',\n\
            examples: { bad: 'debugger;', good: 'console.log(x);' },\n\
          },\n\
          check(ctx, m) { ctx.report(m.stmt); },\n\
        });\n";

    /// A rule matching `x.y`, which is the shape that vanishes when JSX fails to parse.
    fn member_rule_for(language: &str) -> String {
        let declaration = if language.is_empty() {
            String::new()
        } else {
            format!("  language: {language},\n")
        };
        format!(
            "import {{ defineRule }} from 'lanekeep';\n\
             export default defineRule({{\n\
               id: 'local/member',\n\
             {declaration}\
               query: '(member_expression) @m',\n\
               card: {{\n\
                 message: 'member expression',\n\
                 remediation: 'n/a',\n\
                 examples: {{ bad: 'a.b', good: 'b' }},\n\
               }},\n\
               check(ctx, m) {{ ctx.report(m.m); }},\n\
             }});\n"
        )
    }

    fn config_for(include: &str) -> String {
        format!(
            "import {{ defineConfig }} from 'lanekeep';\n\
             import rule from './rule';\n\
             export default defineConfig({{ include: ['{include}'], rules: [rule] }});\n"
        )
    }

    fn config(extra: &str) -> String {
        format!(
            "import {{ defineConfig }} from 'lanekeep';\n\
             import rule from './rule';\n\
             export default defineConfig({{ include: ['src/**/*.ts'], rules: [rule]{extra} }});\n"
        )
    }

    /// A rule with no `language` of its own has to see inside JSX.
    ///
    /// The default used to be `typescript` alone, and the engine parsed every file with the
    /// rule's grammar whatever the file was. So a `.tsx` file went through the TypeScript
    /// grammar, every JSX element became an `ERROR` node, and a query simply matched nothing
    /// inside it — with no error, no warning, and no way to tell from the output. On a React
    /// codebase that is most of the code.
    #[test]
    fn a_default_rule_sees_inside_jsx() {
        let project = Project::new(
            "jsx-default",
            &[
                ("rule.ts", &member_rule_for("")),
                ("lanekeep.config.ts", &config_for("src/**/*.tsx")),
                (
                    "src/Component.tsx",
                    "export const C = () => <View style={styles.used} />;\n",
                ),
            ],
        );

        let outcome = project.run().expect("runs");

        assert_eq!(
            outcome.violations.len(),
            1,
            "a member expression inside JSX was not seen: {:?}",
            outcome.violations
        );
    }

    /// And the same rule still works on plain TypeScript, each file through its own grammar.
    #[test]
    fn a_default_rule_still_sees_plain_typescript() {
        let project = Project::new(
            "ts-default",
            &[
                ("rule.ts", &member_rule_for("")),
                ("lanekeep.config.ts", &config_for("src/**/*.ts")),
                ("src/plain.ts", "const x = styles.used;\n"),
            ],
        );

        let outcome = project.run().expect("runs");

        assert_eq!(outcome.violations.len(), 1, "{:?}", outcome.violations);
    }

    /// A rule that names one language is not run on files belonging to another.
    ///
    /// Previously it was run on everything and the mismatch showed up as an unparsable tree
    /// rather than as a skip, which is the failure this whole change is about.
    #[test]
    fn a_rule_does_not_run_on_a_language_it_does_not_name() {
        let project = Project::new(
            "single-language",
            &[
                ("rule.ts", &member_rule_for("'typescript'")),
                ("lanekeep.config.ts", &config_for("src/**/*.tsx")),
                (
                    "src/Component.tsx",
                    "export const C = () => <View style={styles.used} />;\n",
                ),
            ],
        );

        let outcome = project.run().expect("runs");

        assert!(
            outcome.violations.is_empty(),
            "a typescript-only rule ran on a tsx file: {:?}",
            outcome.violations
        );
    }

    /// Naming several languages runs the rule against each, compiled per grammar.
    #[test]
    fn a_rule_may_name_several_languages() {
        let project = Project::new(
            "many-languages",
            &[
                ("rule.ts", &member_rule_for("['typescript', 'tsx']")),
                ("lanekeep.config.ts", &config_for("src/**/*.{ts,tsx}")),
                ("src/plain.ts", "const x = styles.used;\n"),
                (
                    "src/Component.tsx",
                    "export const C = () => <View style={styles.used} />;\n",
                ),
            ],
        );

        let outcome = project.run().expect("runs");

        assert_eq!(outcome.violations.len(), 2, "{:?}", outcome.violations);
    }

    /// An unknown language is still an error, however it is spelled.
    #[test]
    fn an_unknown_language_in_a_list_is_reported() {
        let project = Project::new(
            "unknown-in-list",
            &[
                ("rule.ts", &member_rule_for("['typescript', 'klingon']")),
                ("lanekeep.config.ts", &config_for("src/**/*.ts")),
                ("src/plain.ts", "const x = styles.used;\n"),
            ],
        );

        let error = project
            .run()
            .expect_err("should refuse an unknown language");
        assert!(
            error.to_string().contains("klingon"),
            "the error should name it: {error}"
        );
    }

    #[test]
    fn runs_a_rule_over_a_corpus_end_to_end() {
        let project = Project::new(
            "end-to-end",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/clean.ts", "const a = 1;\n"),
                ("src/dirty.ts", "const b = 2;\ndebugger;\n"),
                ("src/also.ts", "function f() {\n  debugger;\n}\n"),
            ],
        );

        let outcome = project.run().expect("runs");

        assert_eq!(outcome.violations.len(), 2, "{:?}", outcome.violations);
        let rendered: Vec<String> = outcome
            .violations
            .iter()
            .map(|v| format!("{} {}", v.rule_id, v.location))
            .collect();
        assert_eq!(
            rendered,
            [
                "local/no-debugger src/also.ts:2:3",
                "local/no-debugger src/dirty.ts:2:1",
            ]
        );
        assert_eq!(outcome.violations[0].message, "debugger statement");
        assert_eq!(
            outcome.violations[0].remediation,
            "remove it before committing"
        );
    }

    #[test]
    fn output_is_identical_across_repeated_runs() {
        // The guarantee the whole design rests on. Files are checked in parallel, so
        // violations arrive in an order that varies run to run; only the sort makes the
        // output stable, and it has to hold across many files rather than two.
        let mut files = vec![
            ("rule.ts".to_owned(), DEBUGGER_RULE.to_owned()),
            ("lanekeep.config.ts".to_owned(), config("")),
        ];
        for i in 0..40 {
            files.push((
                format!("src/f{i}.ts"),
                format!("const x{i} = 1;\ndebugger;\n"),
            ));
        }
        let borrowed: Vec<(&str, &str)> = files
            .iter()
            .map(|(a, b)| (a.as_str(), b.as_str()))
            .collect();
        let project = Project::new("determinism", &borrowed);

        let first = project.run().expect("runs").violations;
        assert_eq!(first.len(), 40);

        for _ in 0..4 {
            assert_eq!(project.run().expect("runs").violations, first);
        }
    }

    #[test]
    fn exclude_keeps_files_out_of_the_run() {
        let project = Project::new(
            "exclude",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config(", exclude: ['**/*.test.ts']")),
                ("src/a.ts", "debugger;\n"),
                ("src/a.test.ts", "debugger;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        assert_eq!(outcome.violations[0].location.file.as_str(), "src/a.ts");
    }

    #[test]
    fn a_content_gate_skips_the_parse() {
        // The gate's whole purpose. `files_parsed` is what proves it skipped rather than
        // parsed and found nothing — the violation count would look identical either way.
        let gated = "import { defineRule } from 'lanekeep';\n\
            export default defineRule({\n\
              id: 'local/no-debugger',\n\
              query: '(debugger_statement) @stmt',\n\
              gates: { fileContains: ['debugger'] },\n\
              card: { message: 'm', remediation: 'r', examples: { bad: 'a', good: 'b' } },\n\
              check(ctx, m) { ctx.report(m.stmt); },\n\
            });\n";

        let project = Project::new(
            "gate",
            &[
                ("rule.ts", gated),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
                ("src/b.ts", "const b = 1;\n"),
                ("src/c.ts", "const c = 2;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.files_discovered, 3);
        assert_eq!(
            outcome.files_parsed, 1,
            "only the file containing the needle should parse"
        );
        assert_eq!(outcome.violations.len(), 1);
    }

    #[test]
    fn a_rule_set_to_off_does_not_run() {
        let project = Project::new(
            "off",
            &[
                ("rule.ts", DEBUGGER_RULE),
                (
                    "lanekeep.config.ts",
                    &config(", severity: { 'local/no-debugger': 'off' }"),
                ),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());
    }

    #[test]
    fn severity_reaches_the_violation() {
        let project = Project::new(
            "severity",
            &[
                ("rule.ts", DEBUGGER_RULE),
                (
                    "lanekeep.config.ts",
                    &config(", severity: { 'local/no-debugger': 'warn' }"),
                ),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations[0].severity, Severity::Warn);
        assert!(!any_failing(&outcome.violations));
    }

    #[test]
    fn a_rule_that_throws_aborts_the_run_naming_itself_and_the_file() {
        // §6.8: a breach cancels rather than degrading to a partial result, and the
        // diagnostic has to identify the culprit or it is not actionable.
        let throwing = "import { defineRule } from 'lanekeep';\n\
            export default defineRule({\n\
              id: 'local/throws',\n\
              query: '(debugger_statement) @stmt',\n\
              card: { message: 'm', remediation: 'r', examples: { bad: 'a', good: 'b' } },\n\
              check() { throw new Error('rule bug'); },\n\
            });\n";

        let project = Project::new(
            "throws",
            &[
                ("rule.ts", throwing),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );

        let err = project.run().expect_err("must abort");
        let rendered = err.to_string();
        assert!(rendered.contains("local/throws"), "{rendered}");
        assert!(rendered.contains("src/a.ts"), "{rendered}");
        assert!(rendered.contains("rule bug"), "{rendered}");
    }

    #[test]
    fn an_invalid_query_fails_before_any_file_is_read() {
        let bad = "import { defineRule } from 'lanekeep';\n\
            export default defineRule({\n\
              id: 'local/bad-query',\n\
              query: '(no_such_node) @x',\n\
              card: { message: 'm', remediation: 'r', examples: { bad: 'a', good: 'b' } },\n\
              check() {},\n\
            });\n";

        let project = Project::new(
            "bad-query",
            &[
                ("rule.ts", bad),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );

        let err = project.run().expect_err("must fail at preparation");
        assert!(matches!(err, RunError::Query { .. }), "{err:?}");
        assert!(err.to_string().contains("no_such_node"), "{err}");
    }

    #[test]
    fn a_rule_can_use_the_host_api_it_was_given() {
        // Proves the ctx surface is actually reachable from a real rule, not just from
        // the sandbox's own tests.
        let rule = "import { defineRule } from 'lanekeep';\n\
            export default defineRule({\n\
              id: 'local/long-names',\n\
              query: '(variable_declarator name: (identifier) @name)',\n\
              card: { message: 'name too long', remediation: 'shorten it', examples: { bad: 'a', good: 'b' } },\n\
              check(ctx, m) {\n\
                if (ctx.text(m.name).length > 5) ctx.report(m.name, `\\\"${ctx.text(m.name)}\\\" is too long`);\n\
              },\n\
            });\n";

        let project = Project::new(
            "host-api",
            &[
                ("rule.ts", rule),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const ok = 1;\nconst wayTooLong = 2;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        assert!(
            outcome.violations[0].message.contains("wayTooLong"),
            "{:?}",
            outcome.violations[0]
        );
    }

    #[test]
    fn a_corpus_with_no_matches_produces_nothing() {
        let project = Project::new(
            "clean",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const a = 1;\n"),
            ],
        );
        let outcome = project.run().expect("runs");
        assert!(outcome.violations.is_empty());
        assert_eq!(outcome.files_parsed, 1, "no gates means it is still parsed");
    }

    // --- the reduce phase ----------------------------------------------------------------

    /// A cross-file rule: every exported symbol nobody imports.
    ///
    /// The smallest rule that genuinely cannot work per-file — whether an export is unused
    /// is not a property of the file that declares it.
    const UNUSED_EXPORTS_RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/no-unused-exports',
  query: `
    (export_statement declaration: (function_declaration name: (identifier) @name)) @stmt
    (import_statement (import_clause (named_imports (import_specifier name: (identifier) @imported))))
  `,
  card: {
    message: 'unused export',
    remediation: 'delete it, or import it somewhere',
    examples: { bad: 'export function unused() {}', good: 'function used() {}' },
  },
  check(ctx, m) {
    if (m.imported) {
      ctx.emitFact({ kind: 'import', symbol: ctx.text(m.imported) });
      return;
    }
    ctx.emitFact({
      kind: 'export',
      symbol: ctx.text(m.name),
      line: ctx.line(m.stmt),
      column: ctx.column(m.stmt),
    });
  },
  reduce(ctx) {
    const imported = new Set(ctx.facts('import').map((f) => f.symbol));
    for (const e of ctx.facts('export')) {
      if (!imported.has(e.symbol)) {
        ctx.report({ file: e.file, line: e.line, column: e.column }, `'${e.symbol}' is exported but never imported`);
      }
    }
  },
});
";

    #[test]
    fn a_reduce_phase_sees_facts_from_every_file() {
        let project = Project::new(
            "reduce-cross-file",
            &[
                ("rule.ts", UNUSED_EXPORTS_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "export function used() {}\nexport function spare() {}\n",
                ),
                ("src/b.ts", "import { used } from './a';\nused();\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        let found: Vec<(&str, u32, &str)> = outcome
            .violations
            .iter()
            .map(|v| {
                (
                    v.location.file.as_str(),
                    v.location.position.line,
                    v.message.as_str(),
                )
            })
            .collect();

        assert_eq!(
            found,
            vec![("src/a.ts", 2, "'spare' is exported but never imported")],
            "only the export nobody imports should be reported"
        );
    }

    #[test]
    fn a_rule_with_no_reduce_still_runs() {
        // The common path must not regress: no reduce phase, no sandbox built for one.
        let project = Project::new(
            "reduce-absent",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
    }

    #[test]
    fn a_reduce_phase_with_no_facts_reports_nothing() {
        let project = Project::new(
            "reduce-empty",
            &[
                ("rule.ts", UNUSED_EXPORTS_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const a = 1;\n"),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());
    }

    #[test]
    fn the_file_list_reaches_the_reduce_phase() {
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/counts-files',
  query: '(debugger_statement) @stmt',
  card: {
    message: 'file count',
    remediation: 'nothing to do',
    examples: { bad: 'a', good: 'b' },
  },
  check() {},
  reduce(ctx) {
    ctx.report({ file: ctx.files[0], line: ctx.files.length, column: 1 });
  },
});
";
        let project = Project::new(
            "reduce-files",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const a = 1;\n"),
                ("src/b.ts", "const b = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        // Discovery sorts, so `files[0]` is `src/a.ts` on every run and every platform.
        assert_eq!(outcome.violations[0].location.file.as_str(), "src/a.ts");
        assert_eq!(outcome.violations[0].location.position.line, 2);
    }

    #[test]
    fn a_rule_does_not_see_another_rules_facts() {
        // Otherwise a payload shape becomes a contract between rules, and the result starts
        // depending on the order rules were declared in.
        const EMITTER: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/emitter',
  query: '(export_statement) @stmt',
  card: { message: 'emitter', remediation: 'x', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) { ctx.emitFact({ kind: 'thing', from: 'emitter' }); },
});
";
        const READER: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/reader',
  query: '(export_statement) @stmt',
  card: { message: 'reader', remediation: 'x', examples: { bad: 'a', good: 'b' } },
  check() {},
  reduce(ctx) {
    ctx.report({ file: 'seen.ts', line: ctx.facts().length + 1, column: 1 });
  },
});
";
        let project = Project::new(
            "reduce-isolation",
            &[
                ("emitter.ts", EMITTER),
                ("reader.ts", READER),
                (
                    "lanekeep.config.ts",
                    "import { defineConfig } from 'lanekeep';\n\
                     import emitter from './emitter';\n\
                     import reader from './reader';\n\
                     export default defineConfig({ include: ['src/**/*.ts'], rules: [emitter, reader] });\n",
                ),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        assert_eq!(
            outcome.violations[0].location.position.line, 1,
            "the reader saw the emitter's facts"
        );
    }

    #[test]
    fn a_reduce_phase_that_throws_aborts_the_run() {
        // Same posture as a `check` that throws: a partial result reported as a complete
        // one is worse than no result.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/throws-in-reduce',
  query: '(debugger_statement) @stmt',
  card: { message: 'x', remediation: 'y', examples: { bad: 'a', good: 'b' } },
  check() {},
  reduce() { throw new Error('reduce exploded'); },
});
";
        let project = Project::new(
            "reduce-throws",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const a = 1;\n"),
            ],
        );

        let error = project.run().expect_err("aborts");
        let rendered = error.to_string();
        assert!(rendered.contains("reduce exploded"), "{rendered}");
        assert!(
            rendered.contains("local/throws-in-reduce"),
            "the error should name the rule: {rendered}"
        );
    }

    #[test]
    fn facts_reach_reduce_in_the_same_order_on_every_run() {
        // The determinism invariant at the level a rule can observe: `ctx.facts()` is in
        // (file, sequence) order, so a rule that takes the first match — or builds a
        // "first seen wins" map — gives the same answer every run.
        //
        // This asserts the property, not the mechanism. Two things currently produce it,
        // rayon's order-preserving `collect` and the explicit sort, so removing either one
        // alone leaves this passing. The sort's own coverage is in `lanekeep_core::fact`,
        // where shuffled input makes its absence visible.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/first-fact-wins',
  query: '(export_statement declaration: (lexical_declaration (variable_declarator name: (identifier) @name)))',
  card: { message: 'first', remediation: 'x', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) { ctx.emitFact({ kind: 'sym', symbol: ctx.text(m.name) }); },
  reduce(ctx) {
    const all = ctx.facts('sym');
    ctx.report({ file: 'order.ts', line: 1, column: 1 }, all.map((f) => `${f.file}:${f.symbol}`).join(','));
  },
});
";
        let files: Vec<(String, String)> = (0..12)
            .map(|i| {
                (
                    format!("src/f{i:02}.ts"),
                    format!("export const s{i:02} = {i};\n"),
                )
            })
            .collect();

        let mut layout: Vec<(&str, &str)> = vec![("rule.ts", RULE)];
        let config_source = config("");
        layout.push(("lanekeep.config.ts", &config_source));
        for (path, contents) in &files {
            layout.push((path, contents));
        }

        let project = Project::new("reduce-determinism", &layout);

        let first = project.run().expect("runs").violations[0].message.clone();
        for attempt in 0..4 {
            let again = project.run().expect("runs").violations[0].message.clone();
            assert_eq!(again, first, "fact order changed on attempt {attempt}");
        }

        // And it is the canonical order, not merely a repeatable one.
        assert!(
            first.starts_with("src/f00.ts:s00,src/f01.ts:s01,"),
            "facts are not in (file, sequence) order: {first}"
        );
    }

    #[test]
    fn a_rule_cannot_misattribute_a_fact_to_another_file() {
        // The host sets `file`, last, so a rule's own `file` key loses to it.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/lying-fact',
  query: '(export_statement) @stmt',
  card: { message: 'x', remediation: 'y', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) { ctx.emitFact({ kind: 'e', file: 'somewhere-else.ts' }); },
  reduce(ctx) {
    for (const f of ctx.facts('e')) ctx.report({ file: f.file, line: 1, column: 1 });
  },
});
";
        let project = Project::new(
            "reduce-misattribution",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        assert_eq!(outcome.violations[0].location.file.as_str(), "src/a.ts");
    }

    // --- tracked reads -------------------------------------------------------------------

    /// A rule that reads a sibling file and reports when it says so.
    const READING_RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/reads-config',
  query: '(export_statement) @stmt',
  card: {
    message: 'config says no',
    remediation: 'change the config, or the code',
    examples: { bad: 'export const a = 1;', good: 'const a = 1;' },
  },
  check(ctx, m) {
    const raw = ctx.readFile('policy.json');
    if (raw && JSON.parse(raw).forbidExports) ctx.report(m.stmt);
  },
});
";

    #[test]
    fn a_rule_can_read_another_file() {
        let project = Project::new(
            "reads-allowed",
            &[
                ("rule.ts", READING_RULE),
                ("lanekeep.config.ts", &config("")),
                ("policy.json", r#"{"forbidExports":true}"#),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );
        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", outcome.violations);
    }

    #[test]
    fn what_the_file_says_changes_the_result() {
        // Otherwise the test above would pass on a `readFile` that returned nothing.
        let project = Project::new(
            "reads-content",
            &[
                ("rule.ts", READING_RULE),
                ("lanekeep.config.ts", &config("")),
                ("policy.json", r#"{"forbidExports":false}"#),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());
    }

    #[test]
    fn a_read_is_recorded_against_the_file_that_made_it() {
        // The shape a cache entry needs. A dependency recorded against the run, or leaked
        // from the previous file on the same worker, would invalidate the wrong entries.
        //
        // Enough files that workers necessarily handle several each: with only two, rayon
        // puts them on separate workers with separate `FileAccess`, and a missing reset
        // between files cannot show. `FileAccess::clear` is covered deterministically by
        // its own unit test; this covers the engine actually calling it.
        let mut layout: Vec<(String, String)> = vec![
            ("rule.ts".to_owned(), READING_RULE.to_owned()),
            ("lanekeep.config.ts".to_owned(), config("")),
            (
                "policy.json".to_owned(),
                r#"{"forbidExports":false}"#.to_owned(),
            ),
        ];
        // Odd files export and therefore read; even files do neither.
        for i in 0..24 {
            let body = if i % 2 == 0 {
                format!("const v{i} = {i};\n")
            } else {
                format!("export const v{i} = {i};\n")
            };
            layout.push((format!("src/f{i:02}.ts"), body));
        }
        let borrowed: Vec<(&str, &str)> = layout
            .iter()
            .map(|(p, c)| (p.as_str(), c.as_str()))
            .collect();

        let project = Project::new("reads-attributed", &borrowed);
        let outcome = project.run().expect("runs");

        for i in 0..24 {
            let file = FilePath::new(format!("src/f{i:02}.ts"));
            let deps = outcome.dependencies.get(&file);
            if i % 2 == 0 {
                assert!(
                    deps.is_none(),
                    "src/f{i:02}.ts read nothing but has {deps:?}"
                );
            } else {
                let deps = deps.unwrap_or_else(|| panic!("src/f{i:02}.ts should have read"));
                assert_eq!(deps.len(), 1);
                assert_eq!(deps[0].path.as_str(), "policy.json");
                assert!(deps[0].hash.is_some());
            }
        }
    }

    #[test]
    fn a_missing_file_is_recorded_as_a_dependency_too() {
        // The case that makes a cache wrong rather than cold: the answer "not there" has to
        // be invalidated when the file appears.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/wants-config',
  query: '(export_statement) @stmt',
  card: { message: 'no config', remediation: 'add one', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) {
    if (!ctx.fileExists('tsconfig.json')) ctx.report(m.stmt);
  },
});
";
        let project = Project::new(
            "reads-absent",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);

        let deps = outcome
            .dependencies
            .get(&FilePath::new("src/a.ts"))
            .expect("the miss is a dependency");
        assert_eq!(deps.len(), 1);
        assert_eq!(deps[0].path.as_str(), "tsconfig.json");
        assert_eq!(deps[0].hash, None, "absence is recorded as absence");
    }

    #[test]
    fn reading_outside_the_project_aborts_the_run() {
        // Not a rule that reports nothing: a rule reaching outside the project is a rule
        // doing something it must never do, and a run that continued would be reporting a
        // result produced by code that tried.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/escapes',
  query: '(export_statement) @stmt',
  card: { message: 'x', remediation: 'y', examples: { bad: 'a', good: 'b' } },
  check(ctx) { ctx.readFile('../../../etc/passwd'); },
});
";
        let project = Project::new(
            "reads-escape",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        let error = project.run().expect_err("aborts");
        let rendered = error.to_string();
        assert!(rendered.contains("outside the project root"), "{rendered}");
        assert!(rendered.contains("local/escapes"), "{rendered}");
    }

    #[test]
    fn reading_the_same_file_from_two_files_records_it_under_both() {
        let project = Project::new(
            "reads-shared",
            &[
                ("rule.ts", READING_RULE),
                ("lanekeep.config.ts", &config("")),
                ("policy.json", r#"{"forbidExports":false}"#),
                ("src/a.ts", "export const a = 1;\n"),
                ("src/b.ts", "export const b = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        for file in ["src/a.ts", "src/b.ts"] {
            let deps = outcome
                .dependencies
                .get(&FilePath::new(file))
                .unwrap_or_else(|| panic!("{file} should depend on the policy"));
            assert_eq!(deps[0].path.as_str(), "policy.json");
        }

        // The same bytes, so the same hash — a cache must not see two different
        // dependencies on one file.
        let a = &outcome.dependencies[&FilePath::new("src/a.ts")][0];
        let b = &outcome.dependencies[&FilePath::new("src/b.ts")][0];
        assert_eq!(a.hash, b.hash);
    }

    #[test]
    fn dependencies_are_the_same_on_every_run() {
        let project = Project::new(
            "reads-deterministic",
            &[
                ("rule.ts", READING_RULE),
                ("lanekeep.config.ts", &config("")),
                ("policy.json", r#"{"forbidExports":false}"#),
                ("src/a.ts", "export const a = 1;\n"),
                ("src/b.ts", "export const b = 1;\n"),
                ("src/c.ts", "export const c = 1;\n"),
            ],
        );
        let first = project.run().expect("runs").dependencies;
        assert!(!first.is_empty());
        for attempt in 0..4 {
            assert_eq!(
                project.run().expect("runs").dependencies,
                first,
                "dependencies changed on attempt {attempt}"
            );
        }
    }

    #[test]
    fn the_read_surface_is_absent_from_the_reduce_phase() {
        // Reduce reads would be run-level dependencies, not per-file ones, and storing them
        // in a per-file entry would attribute them to whichever file came last. Until the
        // cache can express that, the functions are not there to be misused.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/reduce-reads',
  query: '(export_statement) @stmt',
  card: { message: 'x', remediation: 'y', examples: { bad: 'a', good: 'b' } },
  check() {},
  reduce(ctx) {
    const absent = ctx.readFile === undefined && ctx.fileExists === undefined;
    ctx.report({ file: 'probe.ts', line: absent ? 1 : 2, column: 1 });
  },
});
";
        let project = Project::new(
            "reads-reduce",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        assert_eq!(
            outcome.violations[0].location.position.line, 1,
            "reads must not be reachable from a reduce phase"
        );
    }

    // --- the cache -----------------------------------------------------------------------

    impl Project {
        /// Run with the cache disabled, for comparing against a warm run.
        fn run_cold(&self) -> Result<Outcome, RunError> {
            self.build().map(Engine::without_cache)?.run()
        }

        /// The engine, without running it.
        fn build(&self) -> Result<Engine, RunError> {
            let root = RuleRoot::new(&self.dir).expect("canonicalizes");
            let config_path = self.dir.join("lanekeep.config.ts");
            let sandbox =
                lanekeep_config::sandbox_for(&root, Arc::new(TypeScript), Arc::new(JavaScript))
                    .expect("sandbox");
            let config = lanekeep_config::load(&sandbox, &root, &config_path)
                .unwrap_or_else(|e| panic!("config failed to load: {e}"));
            Engine::prepare(
                &config,
                &self.dir,
                root,
                &config_path,
                &lanekeep_lang_js::registry(),
                Arc::new(TypeScript),
                Arc::new(JavaScript),
            )
        }

        fn cache(&self) -> Store {
            Store::load(&self.dir)
        }
    }

    fn rendered(outcome: &Outcome) -> Vec<String> {
        outcome
            .violations
            .iter()
            .map(|v| {
                format!(
                    "{}:{}:{} {} {}",
                    v.location.file.as_str(),
                    v.location.position.line,
                    v.location.position.column,
                    v.rule_id,
                    v.message
                )
            })
            .collect()
    }

    #[test]
    fn a_warm_run_agrees_with_a_cold_one() {
        let project = Project::new(
            "cache-agrees",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\nconst a = 1;\n"),
                ("src/b.ts", "const b = 1;\ndebugger;\n"),
                ("src/c.ts", "const c = 1;\n"),
            ],
        );

        let cold = rendered(&project.run().expect("runs"));
        let warm = rendered(&project.run().expect("runs"));
        assert_eq!(warm, cold, "the cache changed the answer");
        assert!(!cold.is_empty(), "the fixture should report something");
    }

    #[test]
    fn a_run_writes_a_cache() {
        let project = Project::new(
            "cache-written",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        assert!(project.cache().is_empty(), "nothing before the first run");
        project.run().expect("runs");
        assert!(!project.cache().is_empty(), "the run stored nothing");
    }

    #[test]
    fn a_cached_result_is_actually_used() {
        // Agreeing with a cold run proves nothing on its own — a cache that was never read
        // would agree too. So doctor the stored entry and show the doctored value comes
        // back: that can only happen through the cache.
        let project = Project::new(
            "cache-used",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const a = 1;\n"),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());

        let store = project.cache();
        let key = *store
            .keys()
            .next()
            .expect("the run stored an entry for the file");

        let mut doctored = Store::empty();
        doctored.insert(
            key,
            lanekeep_cache::Entry {
                violations: vec![Violation {
                    rule_id: "local/no-debugger".parse().expect("valid id"),
                    location: Location::new(FilePath::new("src/a.ts"), Position::new(7, 3)),
                    message: "from the cache".to_owned(),
                    remediation: "nothing".to_owned(),
                    severity: Severity::Error,
                    fix: None,
                }],
                facts: Vec::new(),
                dependencies: Vec::new(),
                suppressions: Vec::new(),
                used_suppressions: Vec::new(),
            },
        );
        doctored.save(&project.dir);

        let outcome = project.run().expect("runs");
        assert_eq!(
            rendered(&outcome),
            vec!["src/a.ts:7:3 local/no-debugger from the cache"],
            "the cached entry was not used"
        );
    }

    #[test]
    fn editing_a_file_invalidates_it() {
        let project = Project::new(
            "cache-edited",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const a = 1;\n"),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());

        project.write("src/a.ts", "debugger;\n");
        assert_eq!(
            project.run().expect("runs").violations.len(),
            1,
            "an edited file kept its stale result"
        );
    }

    #[test]
    fn moving_a_file_invalidates_it() {
        // Path gates make results path-sensitive, so identical bytes at a new path are not
        // a hit. This fixture's rule has no path gate, but the key must not depend on that.
        let project = Project::new(
            "cache-moved",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        project.run().expect("runs");

        fs::remove_file(project.dir.join("src/a.ts")).expect("removes");
        project.write("src/moved.ts", "debugger;\n");

        let outcome = project.run().expect("runs");
        assert_eq!(
            outcome.violations[0].location.file.as_str(),
            "src/moved.ts",
            "the violation followed the old path"
        );
    }

    #[test]
    fn editing_a_tracked_dependency_invalidates_the_files_that_read_it() {
        // The reason tracked effects exist. Nothing about `src/a.ts` changed, and its result
        // still has to be recomputed.
        let project = Project::new(
            "cache-dependency",
            &[
                ("rule.ts", READING_RULE),
                ("lanekeep.config.ts", &config("")),
                ("policy.json", r#"{"forbidExports":false}"#),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());

        project.write("policy.json", r#"{"forbidExports":true}"#);
        assert_eq!(
            project.run().expect("runs").violations.len(),
            1,
            "a changed dependency did not invalidate"
        );
    }

    #[test]
    fn a_dependency_that_appears_invalidates() {
        // The case a cache is wrong rather than merely cold without: a rule was told a file
        // was absent, and creating it has to reopen the question.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/wants-config',
  query: '(export_statement) @stmt',
  card: { message: 'no config', remediation: 'add one', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) {
    if (!ctx.fileExists('tsconfig.json')) ctx.report(m.stmt);
  },
});
";
        let project = Project::new(
            "cache-appeared",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );
        assert_eq!(project.run().expect("runs").violations.len(), 1);

        project.write("tsconfig.json", "{}");
        assert!(
            project.run().expect("runs").violations.is_empty(),
            "a dependency that appeared did not invalidate"
        );
    }

    #[test]
    fn changing_the_ruleset_invalidates_everything() {
        let project = Project::new(
            "cache-ruleset",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        assert_eq!(project.run().expect("runs").violations.len(), 1);

        // Same file, different rule: it now reports nothing.
        project.write(
            "rule.ts",
            &DEBUGGER_RULE.replace("ctx.report(m.stmt);", "/* nothing */"),
        );
        assert!(
            project.run().expect("runs").violations.is_empty(),
            "an edited rule kept its stale results"
        );
    }

    #[test]
    fn changing_the_config_invalidates_everything() {
        let project = Project::new(
            "cache-config",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        assert_eq!(project.run().expect("runs").violations.len(), 1);

        project.write(
            "lanekeep.config.ts",
            &config(", severity: { 'local/no-debugger': 'off' }"),
        );
        assert!(
            project.run().expect("runs").violations.is_empty(),
            "a config change did not invalidate"
        );
    }

    #[test]
    fn a_corrupt_cache_still_produces_the_right_answer() {
        // Disposability, end to end: garbage on disk costs a recompute and nothing else.
        let project = Project::new(
            "cache-corrupt",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        let expected = rendered(&project.run().expect("runs"));

        let path = Store::path_for(&project.dir);
        fs::write(&path, b"\x00\x01\x02 not a cache").expect("writes");

        assert_eq!(rendered(&project.run().expect("runs")), expected);
    }

    #[test]
    fn caching_can_be_turned_off() {
        let project = Project::new(
            "cache-off",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );
        let outcome = project.run_cold().expect("runs");
        assert_eq!(outcome.violations.len(), 1);
        assert!(
            project.cache().is_empty(),
            "a run with caching off wrote a cache"
        );
    }

    #[test]
    fn facts_survive_a_warm_run() {
        // The reduce phase runs every time, over facts that may all have come from the
        // cache. A cache that dropped them would make cross-file rules go quiet on the
        // second run — reporting on a cold run and nothing on a warm one is the worst
        // possible failure, because it looks like the problem was fixed.
        let project = Project::new(
            "cache-facts",
            &[
                ("rule.ts", UNUSED_EXPORTS_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "export function used() {}\nexport function spare() {}\n",
                ),
                ("src/b.ts", "import { used } from './a';\nused();\n"),
            ],
        );

        let cold = rendered(&project.run().expect("runs"));
        assert_eq!(cold.len(), 1, "{cold:?}");
        assert_eq!(rendered(&project.run().expect("runs")), cold);
        assert_eq!(rendered(&project.run().expect("runs")), cold);
    }

    #[test]
    fn a_cache_file_does_not_churn() {
        // Byte-identical across runs over unchanged input. A file that rewrote itself every
        // run would be a spurious diff for anyone who commits it.
        let project = Project::new(
            "cache-stable",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
                ("src/b.ts", "const b = 1;\n"),
            ],
        );
        project.run().expect("runs");
        let first = fs::read(Store::path_for(&project.dir)).expect("reads");
        project.run().expect("runs");
        let second = fs::read(Store::path_for(&project.dir)).expect("reads");
        assert_eq!(first, second, "the cache file churned");
    }

    #[test]
    fn entries_for_deleted_files_do_not_accumulate() {
        let project = Project::new(
            "cache-prune",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
                ("src/b.ts", "debugger;\n"),
            ],
        );
        project.run().expect("runs");
        assert_eq!(project.cache().len(), 2);

        fs::remove_file(project.dir.join("src/b.ts")).expect("removes");
        project.run().expect("runs");
        assert_eq!(
            project.cache().len(),
            1,
            "an entry outlived the file it was for"
        );
    }

    #[test]
    fn a_partial_run_does_not_discard_other_files_entries() {
        // `--staged` saving only what it processed would wipe the cache for every file it
        // never looked at, leaving the next full run cold — the opposite of what an
        // incremental entry point is for.
        let project = Project::new(
            "cache-partial",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
                ("src/b.ts", "const b = 1;\n"),
                ("src/c.ts", "const c = 1;\n"),
            ],
        );
        project.run().expect("runs");
        assert_eq!(project.cache().len(), 3);

        let engine = project.build().expect("prepares");
        engine
            .run_over(&[FilePath::new("src/a.ts")])
            .expect("runs over one file");

        assert_eq!(
            project.cache().len(),
            3,
            "a partial run discarded entries for files it did not look at"
        );
    }

    #[test]
    fn a_full_run_still_prunes() {
        // The other half: pruning has to keep working, or entries for deleted files
        // accumulate forever.
        let project = Project::new(
            "cache-prune-still",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
                ("src/b.ts", "const b = 1;\n"),
            ],
        );
        project.run().expect("runs");
        assert_eq!(project.cache().len(), 2);

        fs::remove_file(project.dir.join("src/b.ts")).expect("removes");
        project.run().expect("runs");
        assert_eq!(project.cache().len(), 1);
    }

    // --- suppressions ----------------------------------------------------------------------

    impl Project {
        /// Run with a fixed date, so an expiry can be asserted without waiting for one.
        fn run_on(&self, today: &str) -> Result<Outcome, RunError> {
            let date = Date::parse(today).expect("valid date");
            self.build().map(|engine| engine.with_today(date))?.run()
        }
    }

    fn messages(outcome: &Outcome) -> Vec<&str> {
        outcome
            .violations
            .iter()
            .map(|v| v.message.as_str())
            .collect()
    }

    #[test]
    fn a_next_line_directive_silences_the_line_below_it() {
        let project = Project::new(
            "suppress-next-line",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: legacy entry point\n\
                     debugger;\n",
                ),
            ],
        );
        assert!(
            project.run().expect("runs").violations.is_empty(),
            "the directive did not silence the violation"
        );
    }

    #[test]
    fn a_directive_silences_only_the_line_it_names() {
        let project = Project::new(
            "suppress-scope",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: legacy\n\
                     debugger;\n\
                     debugger;\n",
                ),
            ],
        );
        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", messages(&outcome));
        assert_eq!(outcome.violations[0].location.position.line, 3);
    }

    #[test]
    fn a_file_directive_silences_every_line() {
        let project = Project::new(
            "suppress-file",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-file local/no-debugger reason: generated fixture\n\
                     debugger;\n\
                     debugger;\n",
                ),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());
    }

    #[test]
    fn a_directive_naming_another_rule_silences_nothing() {
        let project = Project::new(
            "suppress-other-rule",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/something-else reason: unrelated\n\
                     debugger;\n",
                ),
            ],
        );
        assert_eq!(project.run().expect("runs").violations.len(), 1);
    }

    #[test]
    fn a_malformed_directive_is_reported() {
        // The failure this exists to prevent: a directive that looks like it works, does
        // not, and says nothing. Both the missing reason and the violation it failed to
        // suppress have to surface.
        let project = Project::new(
            "suppress-malformed",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger\ndebugger;\n",
                ),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 2, "{:?}", messages(&outcome));
        assert!(
            messages(&outcome)
                .iter()
                .any(|m| m.contains("no `reason:`")),
            "{:?}",
            messages(&outcome)
        );
        assert!(
            outcome
                .violations
                .iter()
                .any(|v| v.rule_id.to_string() == "lanekeep/suppression"),
            "reported under the wrong id"
        );
    }

    #[test]
    fn an_expired_directive_is_reported_and_still_silences() {
        // It expired, which is worth saying — but suddenly reporting everything it covered
        // would turn a deadline into an avalanche on the day it passed.
        let project = Project::new(
            "suppress-expired",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: pending rewrite expires: 2026-01-01\n\
                     debugger;\n",
                ),
            ],
        );

        let outcome = project.run_on("2026-08-01").expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", messages(&outcome));
        assert!(
            outcome.violations[0]
                .message
                .contains("expired on 2026-01-01"),
            "{:?}",
            messages(&outcome)
        );
        assert!(
            outcome.violations[0].message.contains("pending rewrite"),
            "the reason should be quoted back: {:?}",
            messages(&outcome)
        );
    }

    #[test]
    fn a_directive_that_has_not_expired_is_quiet() {
        let project = Project::new(
            "suppress-unexpired",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: pending expires: 2026-12-31\n\
                     debugger;\n",
                ),
            ],
        );
        assert!(
            project
                .run_on("2026-08-01")
                .expect("runs")
                .violations
                .is_empty()
        );
    }

    #[test]
    fn a_directive_expires_the_day_after_its_date() {
        // On the date itself it still holds: an expiry is a deadline, and a deadline of the
        // 31st is not missed on the 31st.
        let project = Project::new(
            "suppress-boundary",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-file local/no-debugger reason: x expires: 2026-08-01\n\
                     debugger;\n",
                ),
            ],
        );
        assert!(
            project
                .run_on("2026-08-01")
                .expect("runs")
                .violations
                .is_empty()
        );
        assert_eq!(
            project.run_on("2026-08-02").expect("runs").violations.len(),
            1
        );
    }

    #[test]
    fn an_expiring_directive_is_not_served_stale_from_the_cache() {
        // The cache-soundness case. A file cached the day before expiry must not keep its
        // suppressed result the day after — an expiry that a warm run ignored would never
        // expire at all, which is the one thing an expiry exists to prevent.
        let project = Project::new(
            "suppress-cache-date",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-file local/no-debugger reason: x expires: 2026-08-01\n\
                     debugger;\n",
                ),
            ],
        );

        assert!(
            project
                .run_on("2026-08-01")
                .expect("runs")
                .violations
                .is_empty()
        );
        let after = project.run_on("2026-08-02").expect("runs");
        assert_eq!(
            after.violations.len(),
            1,
            "a warm run served an expired suppression: {:?}",
            messages(&after)
        );
    }

    #[test]
    fn suppressions_survive_a_warm_run() {
        let project = Project::new(
            "suppress-warm",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-file local/no-debugger reason: generated\ndebugger;\n",
                ),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());
        assert!(
            project.run().expect("runs").violations.is_empty(),
            "the warm run reported what the cold one suppressed"
        );
    }

    #[test]
    fn a_cross_file_violation_is_silenced_by_the_directive_where_it_lands() {
        // A reduce-phase violation is reported at the site a fact came from, in a file the
        // rule was never "checking" — and possibly one that was a cache hit. The directives
        // that matter are that file's.
        let project = Project::new(
            "suppress-cross-file",
            &[
                ("rule.ts", UNUSED_EXPORTS_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "export function used() {}\n\
                     // lanekeep-ignore-next-line local/no-unused-exports reason: public API\n\
                     export function spare() {}\n",
                ),
                ("src/b.ts", "import { used } from './a';\nused();\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert!(
            outcome.violations.is_empty(),
            "a cross-file violation ignored the directive at its site: {:?}",
            messages(&outcome)
        );
    }

    #[test]
    fn a_cross_file_violation_survives_a_directive_for_another_rule() {
        let project = Project::new(
            "suppress-cross-file-other",
            &[
                ("rule.ts", UNUSED_EXPORTS_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "export function used() {}\n\
                     // lanekeep-ignore-next-line local/unrelated reason: x\n\
                     export function spare() {}\n",
                ),
                ("src/b.ts", "import { used } from './a';\nused();\n"),
            ],
        );
        assert_eq!(project.run().expect("runs").violations.len(), 1);
    }

    // --- unused suppressions ---------------------------------------------------------------

    impl Project {
        fn run_reporting_unused(&self) -> Result<Outcome, RunError> {
            self.build()
                .map(Engine::reporting_unused_suppressions)?
                .run()
        }
    }

    #[test]
    fn a_suppression_that_silenced_nothing_is_reported() {
        let project = Project::new(
            "unused-reported",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: was needed once\n\
                     const a = 1;\n",
                ),
            ],
        );

        let outcome = project.run_reporting_unused().expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", messages(&outcome));
        assert!(
            outcome.violations[0].message.contains("silenced nothing"),
            "{:?}",
            messages(&outcome)
        );
        assert!(
            outcome.violations[0].message.contains("was needed once"),
            "the reason should be quoted back: {:?}",
            messages(&outcome)
        );
    }

    #[test]
    fn a_suppression_that_did_its_job_is_not_reported() {
        let project = Project::new(
            "unused-used",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: legacy\ndebugger;\n",
                ),
            ],
        );
        assert!(
            project
                .run_reporting_unused()
                .expect("runs")
                .violations
                .is_empty()
        );
    }

    #[test]
    fn unused_suppressions_are_quiet_without_the_flag() {
        // Hygiene, on request. It must not appear in everyone's inner loop.
        let project = Project::new(
            "unused-off",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: stale\nconst a = 1;\n",
                ),
            ],
        );
        assert!(project.run().expect("runs").violations.is_empty());
    }

    #[test]
    fn an_unused_suppression_is_a_warning_not_an_error() {
        // Turning on a hygiene report must not fail a build that was passing.
        let project = Project::new(
            "unused-severity",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: stale\nconst a = 1;\n",
                ),
            ],
        );
        let outcome = project.run_reporting_unused().expect("runs");
        assert_eq!(outcome.violations[0].severity, Severity::Warn);
        assert!(!lanekeep_core::any_failing(&outcome.violations));
    }

    #[test]
    fn usage_survives_a_warm_run() {
        // The case this needed a cache field for: a warm run sees the survivors and not what
        // was hidden, so without the recorded usage every suppression in a cached file would
        // suddenly look unused.
        let project = Project::new(
            "unused-warm",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger reason: legacy\ndebugger;\n",
                ),
            ],
        );

        assert!(
            project
                .run_reporting_unused()
                .expect("runs")
                .violations
                .is_empty()
        );
        let warm = project.run_reporting_unused().expect("runs");
        assert!(
            warm.violations.is_empty(),
            "a warm run called a used suppression unused: {:?}",
            messages(&warm)
        );
    }

    #[test]
    fn a_suppression_used_only_by_a_cross_file_rule_is_not_unused() {
        // A directive can be the only thing standing between a reduce-phase violation and
        // the report. Counting usage only during the per-file pass would call it unused.
        let project = Project::new(
            "unused-cross-file",
            &[
                ("rule.ts", UNUSED_EXPORTS_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "export function used() {}\n\
                     // lanekeep-ignore-next-line local/no-unused-exports reason: public API\n\
                     export function spare() {}\n",
                ),
                ("src/b.ts", "import { used } from './a';\nused();\n"),
            ],
        );

        let outcome = project.run_reporting_unused().expect("runs");
        assert!(
            outcome.violations.is_empty(),
            "a directive used by a cross-file rule was called unused: {:?}",
            messages(&outcome)
        );
    }

    #[test]
    fn a_malformed_directive_is_not_also_reported_as_unused() {
        // It already has a violation saying what is wrong with it. A second one saying it
        // silenced nothing would be true, unhelpful, and confusing.
        let project = Project::new(
            "unused-malformed",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                (
                    "src/a.ts",
                    "// lanekeep-ignore-next-line local/no-debugger\nconst a = 1;\n",
                ),
            ],
        );

        let outcome = project.run_reporting_unused().expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", messages(&outcome));
        assert!(
            outcome.violations[0].message.contains("no `reason:`"),
            "{:?}",
            messages(&outcome)
        );
    }

    // --- ctx.today and the cache -----------------------------------------------------------

    /// A rule that reports only when the date it is given starts with a given year.
    const DATE_RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/dated',
  query: '(export_statement) @stmt',
  card: { message: 'dated', remediation: 'x', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) {
    if (ctx.today.startsWith('2027')) ctx.report(m.stmt, `it is ${ctx.today}`);
  },
});
";

    #[test]
    fn a_rule_can_read_the_date() {
        let project = Project::new(
            "today-read",
            &[
                ("rule.ts", DATE_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );
        let outcome = project.run_on("2027-03-04").expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", messages(&outcome));
        assert!(outcome.violations[0].message.contains("2027-03-04"));
    }

    #[test]
    fn a_result_that_read_the_date_is_not_served_across_days() {
        // The cache-soundness case for `ctx.today`. Without tracking the read, the answer
        // computed in 2026 would be served in 2027 forever — a date comparison frozen at
        // whenever the cache happened to be written.
        let project = Project::new(
            "today-cache",
            &[
                ("rule.ts", DATE_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        assert!(
            project
                .run_on("2026-12-31")
                .expect("runs")
                .violations
                .is_empty()
        );
        let later = project.run_on("2027-01-01").expect("runs");
        assert_eq!(
            later.violations.len(),
            1,
            "a warm run served a date-dependent result from another day: {:?}",
            messages(&later)
        );
    }

    #[test]
    fn a_result_that_ignored_the_date_survives_across_days() {
        // The other half, and the reason the read is tracked rather than assumed: dating
        // every entry would re-key the whole corpus daily.
        //
        // Asserted on the stored *bytes*, not the entry count. A re-keyed entry replaces the
        // one it supersedes, so the count is identical either way — it was the count I
        // reached for first, and it proved nothing.
        let project = Project::new(
            "today-undated",
            &[
                ("rule.ts", DEBUGGER_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "debugger;\n"),
            ],
        );

        project.run_on("2026-12-31").expect("runs");
        let before = fs::read(Store::path_for(&project.dir)).expect("reads");

        let outcome = project.run_on("2027-01-01").expect("runs");
        assert_eq!(outcome.violations.len(), 1);

        let after = fs::read(Store::path_for(&project.dir)).expect("reads");
        assert_eq!(
            before, after,
            "a result that never read the date was re-keyed across days"
        );
    }

    #[test]
    fn a_result_that_read_the_date_is_re_keyed_across_days() {
        // The converse, on the same evidence. Together these pin both directions: dateless
        // entries keep their key, dated ones do not.
        let project = Project::new(
            "today-dated-key",
            &[
                ("rule.ts", DATE_RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "export const a = 1;\n"),
            ],
        );

        project.run_on("2026-12-31").expect("runs");
        let before = fs::read(Store::path_for(&project.dir)).expect("reads");

        project.run_on("2027-01-01").expect("runs");
        let after = fs::read(Store::path_for(&project.dir)).expect("reads");
        assert_ne!(
            before, after,
            "a result that read the date kept its key across days"
        );
    }

    #[test]
    fn loc_reaches_a_reduce_phase_through_a_fact() {
        // The shape `ctx.loc` exists for: emit it on a fact, report at it later, no glue.
        const RULE: &str = r"import { defineRule } from 'lanekeep';
export default defineRule({
  id: 'local/loc-through-facts',
  query: '(export_statement) @stmt',
  card: { message: 'via loc', remediation: 'x', examples: { bad: 'a', good: 'b' } },
  check(ctx, m) { ctx.emitFact({ kind: 'site', at: ctx.loc(m.stmt) }); },
  reduce(ctx) {
    for (const f of ctx.facts('site')) ctx.report(f.at, 'reported at a remembered place');
  },
});
";
        let project = Project::new(
            "loc-facts",
            &[
                ("rule.ts", RULE),
                ("lanekeep.config.ts", &config("")),
                ("src/a.ts", "const x = 1;\nexport const a = 1;\n"),
            ],
        );

        let outcome = project.run().expect("runs");
        assert_eq!(outcome.violations.len(), 1, "{:?}", messages(&outcome));
        assert_eq!(outcome.violations[0].location.file.as_str(), "src/a.ts");
        assert_eq!(outcome.violations[0].location.position.line, 2);
    }
}