nyx-scanner 0.6.1

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

pub mod index {
    #![allow(clippy::too_many_arguments, clippy::type_complexity)]

    use crate::commands::scan::Diag;
    use crate::errors::{NyxError, NyxResult};
    use crate::patterns::Severity;
    use r2d2::{Pool, PooledConnection};
    use r2d2_sqlite::SqliteConnectionManager;
    use rusqlite::{Connection, OpenFlags, OptionalExtension, params};
    use std::fs;
    use std::ops::Deref;
    use std::path::{Path, PathBuf};
    use std::str::FromStr;
    use std::sync::Arc;
    use std::time::{SystemTime, UNIX_EPOCH};

    /// DB schema (foreign‑keys enabled).
    const SCHEMA: &str = r#"
        PRAGMA foreign_keys = ON;

        CREATE TABLE IF NOT EXISTS files (id INTEGER PRIMARY KEY AUTOINCREMENT,
            project TEXT NOT NULL,
            path TEXT NOT NULL,
            hash BLOB NOT NULL,
            mtime INTEGER NOT NULL,
            scanned_at INTEGER NOT NULL,
            UNIQUE(project, path)
        );

        CREATE TABLE IF NOT EXISTS issues (file_id INTEGER NOT NULL
                              REFERENCES files(id)
                              ON DELETE CASCADE,
            rule_id TEXT NOT NULL,
            severity TEXT NOT NULL,
            line INTEGER NOT NULL,
            col INTEGER NOT NULL,
            PRIMARY KEY (file_id, rule_id, line, col));

        CREATE TABLE IF NOT EXISTS function_summaries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project TEXT NOT NULL,
            file_path TEXT NOT NULL,
            file_hash BLOB NOT NULL,
            name TEXT NOT NULL,
            arity INTEGER NOT NULL DEFAULT -1,
            lang TEXT NOT NULL,
            container TEXT NOT NULL DEFAULT '',
            disambig INTEGER,
            kind TEXT NOT NULL DEFAULT 'fn',
            summary TEXT NOT NULL,
            updated_at INTEGER NOT NULL,
            UNIQUE(project, file_path, name, container, arity, disambig, kind)
        );

        CREATE TABLE IF NOT EXISTS ssa_function_summaries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project TEXT NOT NULL,
            file_path TEXT NOT NULL,
            file_hash BLOB NOT NULL,
            name TEXT NOT NULL,
            arity INTEGER NOT NULL DEFAULT -1,
            lang TEXT NOT NULL,
            namespace TEXT NOT NULL DEFAULT '',
            container TEXT NOT NULL DEFAULT '',
            disambig INTEGER,
            kind TEXT NOT NULL DEFAULT 'fn',
            summary TEXT NOT NULL,
            updated_at INTEGER NOT NULL,
            UNIQUE(project, file_path, name, container, arity, disambig, kind)
        );

        CREATE TABLE IF NOT EXISTS auth_check_summaries (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project TEXT NOT NULL,
            file_path TEXT NOT NULL,
            file_hash BLOB NOT NULL,
            name TEXT NOT NULL,
            arity INTEGER NOT NULL DEFAULT -1,
            lang TEXT NOT NULL,
            namespace TEXT NOT NULL DEFAULT '',
            container TEXT NOT NULL DEFAULT '',
            disambig INTEGER,
            kind TEXT NOT NULL DEFAULT 'fn',
            summary TEXT NOT NULL,
            updated_at INTEGER NOT NULL,
            UNIQUE(project, file_path, name, container, arity, disambig, kind)
        );

        CREATE TABLE IF NOT EXISTS ssa_function_bodies (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            project TEXT NOT NULL,
            file_path TEXT NOT NULL,
            file_hash BLOB NOT NULL,
            name TEXT NOT NULL,
            arity INTEGER NOT NULL DEFAULT -1,
            lang TEXT NOT NULL,
            namespace TEXT NOT NULL DEFAULT '',
            container TEXT NOT NULL DEFAULT '',
            disambig INTEGER,
            kind TEXT NOT NULL DEFAULT 'fn',
            body BLOB NOT NULL,
            updated_at INTEGER NOT NULL,
            UNIQUE(project, file_path, name, container, arity, disambig, kind)
        );

        CREATE TABLE IF NOT EXISTS scans (
            id TEXT PRIMARY KEY,
            status TEXT NOT NULL,
            scan_root TEXT NOT NULL,
            started_at TEXT,
            finished_at TEXT,
            duration_secs REAL,
            engine_version TEXT,
            languages TEXT,
            files_scanned INTEGER,
            files_skipped INTEGER,
            finding_count INTEGER,
            findings_json TEXT,
            timing_json TEXT,
            error TEXT
        );

        CREATE TABLE IF NOT EXISTS scan_metrics (
            scan_id TEXT PRIMARY KEY REFERENCES scans(id) ON DELETE CASCADE,
            cfg_nodes INTEGER,
            call_edges INTEGER,
            functions_analyzed INTEGER,
            summaries_reused INTEGER,
            unresolved_calls INTEGER
        );

        CREATE TABLE IF NOT EXISTS scan_logs (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            scan_id TEXT NOT NULL REFERENCES scans(id) ON DELETE CASCADE,
            timestamp TEXT NOT NULL,
            level TEXT NOT NULL,
            message TEXT NOT NULL,
            file_path TEXT,
            detail TEXT
        );
        CREATE INDEX IF NOT EXISTS idx_scan_logs_scan ON scan_logs(scan_id);

        CREATE TABLE IF NOT EXISTS triage_states (
            fingerprint TEXT PRIMARY KEY,
            state TEXT NOT NULL DEFAULT 'open',
            note TEXT NOT NULL DEFAULT '',
            updated_at TEXT NOT NULL
        );

        CREATE TABLE IF NOT EXISTS triage_audit_log (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            fingerprint TEXT NOT NULL,
            action TEXT NOT NULL,
            previous_state TEXT NOT NULL,
            new_state TEXT NOT NULL,
            note TEXT NOT NULL DEFAULT '',
            timestamp TEXT NOT NULL
        );
        CREATE INDEX IF NOT EXISTS idx_triage_audit_fp ON triage_audit_log(fingerprint);
        CREATE INDEX IF NOT EXISTS idx_triage_audit_ts ON triage_audit_log(timestamp);

        CREATE TABLE IF NOT EXISTS nyx_metadata (
            key TEXT PRIMARY KEY,
            value TEXT NOT NULL
        );

        CREATE TABLE IF NOT EXISTS triage_suppression_rules (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            suppress_by TEXT NOT NULL,
            match_value TEXT NOT NULL,
            state TEXT NOT NULL DEFAULT 'suppressed',
            note TEXT NOT NULL DEFAULT '',
            created_at TEXT NOT NULL,
            UNIQUE(suppress_by, match_value)
        );

        -- First time we observed each finding fingerprint. Lazy-populated by the
        -- overview endpoint when computing backlog age — INSERT OR IGNORE means
        -- only the earliest scan that mentioned a fingerprint sticks.
        CREATE TABLE IF NOT EXISTS finding_first_seen (
            fingerprint TEXT PRIMARY KEY,
            first_seen_at TEXT NOT NULL
        );

        -- Indexes on (project, file_path) for the per-file replace_* paths.
        -- Without these, every DELETE WHERE project=? AND file_path=? does a
        -- full table scan, which dominates indexing time as the cache grows.
        CREATE INDEX IF NOT EXISTS idx_function_summaries_project_file
            ON function_summaries(project, file_path);
        CREATE INDEX IF NOT EXISTS idx_ssa_function_summaries_project_file
            ON ssa_function_summaries(project, file_path);
        CREATE INDEX IF NOT EXISTS idx_ssa_function_bodies_project_file
            ON ssa_function_bodies(project, file_path);
        CREATE INDEX IF NOT EXISTS idx_auth_check_summaries_project_file
            ON auth_check_summaries(project, file_path);
    "#;

    /// Engine version used to detect stale caches across upgrades.
    pub const ENGINE_VERSION: &str = env!("CARGO_PKG_VERSION");

    /// On-disk schema version for cached analysis data.
    ///
    /// Bumped independently of `ENGINE_VERSION` whenever the serialized
    /// layout or identity of a cached artefact changes in an incompatible
    /// way, e.g. a `FuncKey` field semantic change that would cause old
    /// summaries to misbehave when rehydrated.
    ///
    /// History:
    /// * `"1"`, initial.
    /// * `"2"`, 0.5.0: `FuncKey.disambig` changed from the function-node
    ///   byte offset to a depth-first structural index.  Pre-0.5.0 caches
    ///   store byte-offset disambigs and would fail to match bodies built
    ///   by the new engine, so they are silently rebuilt on open.
    /// * `"3"`, `ssa_function_bodies.body` changed from JSON TEXT to
    ///   bincode BLOB.  Old JSON payloads cannot be deserialised by the
    ///   new engine, so they are silently rebuilt on open.
    pub const SCHEMA_VERSION: &str = "3";

    // TODO: ADD CLEANS FOR EACH TABLE BASED ON PROJECT WHICH RUNS ON CLEAN
    // TODO: ADD DROP AND GIVE A CLI PARAMETER FOR DROP

    /// A single issue row, ready for insertion.
    #[derive(Debug, Clone)]
    pub struct IssueRow<'a> {
        pub rule_id: &'a str,
        pub severity: &'a str,
        pub line: i64,
        pub col: i64,
    }

    /// A scan record for DB persistence.
    #[derive(Debug, Clone)]
    pub struct ScanRecord {
        pub id: String,
        pub status: String,
        pub scan_root: String,
        pub started_at: Option<String>,
        pub finished_at: Option<String>,
        pub duration_secs: Option<f64>,
        pub engine_version: Option<String>,
        pub languages: Option<String>,
        pub files_scanned: Option<i64>,
        pub files_skipped: Option<i64>,
        pub finding_count: Option<i64>,
        pub findings_json: Option<String>,
        pub timing_json: Option<String>,
        pub error: Option<String>,
    }

    /// A triage audit log entry.
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct AuditEntry {
        pub id: i64,
        pub fingerprint: String,
        pub action: String,
        pub previous_state: String,
        pub new_state: String,
        pub note: String,
        pub timestamp: String,
    }

    /// A pattern-based suppression rule.
    #[derive(Debug, Clone, serde::Serialize)]
    pub struct SuppressionRule {
        pub id: i64,
        pub suppress_by: String,
        pub match_value: String,
        pub state: String,
        pub note: String,
        pub created_at: String,
    }

    pub struct Indexer {
        conn: PooledConnection<SqliteConnectionManager>,
        project: String,
    }

    impl Indexer {
        pub fn init(database_path: &Path) -> NyxResult<Arc<Pool<SqliteConnectionManager>>> {
            let _span = tracing::info_span!("db_init", path = %database_path.display()).entered();
            // NO_MUTEX is safe because r2d2 ensures each pooled connection
            // is only ever used by one thread at a time.  Combined with WAL
            // mode this allows concurrent readers + a single writer without
            // the global serialization that FULL_MUTEX causes.
            let flags = OpenFlags::SQLITE_OPEN_READ_WRITE
                | OpenFlags::SQLITE_OPEN_CREATE
                | OpenFlags::SQLITE_OPEN_NO_MUTEX;
            let manager = SqliteConnectionManager::file(database_path).with_flags(flags);
            // r2d2's default `max_size` is 10, which can stall rayon
            // workers on machines with more cores than that during the
            // parallel indexing pass.  Size the pool to comfortably hold
            // a connection per rayon thread plus a small slack.
            let max_conns = (num_cpus::get() as u32 + 4).max(16);
            let pool = Arc::new(Pool::builder().max_size(max_conns).build(manager)?);

            {
                let conn = pool.get()?;
                conn.pragma_update(None, "journal_mode", "WAL")?;
                conn.pragma_update(None, "synchronous", "NORMAL")?;
                conn.pragma_update(None, "cache_size", "-8000")?; // 8 MB
                conn.pragma_update(None, "temp_store", "MEMORY")?;
                conn.pragma_update(None, "mmap_size", "268435456")?; // 256 MB
                conn.execute_batch(SCHEMA)?;

                // Migrate: if the function_summaries table is missing any required
                // column (arity for older schemas; container/disambig/kind for the
                // richer FuncKey identity), drop and recreate it so the data layout
                // matches the current model.
                let fn_cols: std::collections::HashSet<String> = conn
                    .prepare("PRAGMA table_info(function_summaries)")
                    .and_then(|mut s| {
                        let cols: Vec<String> = s
                            .query_map([], |r| r.get::<_, String>(1))?
                            .filter_map(Result::ok)
                            .collect();
                        Ok(cols.into_iter().collect())
                    })
                    .unwrap_or_default();

                let fn_ok = fn_cols.contains("arity")
                    && fn_cols.contains("container")
                    && fn_cols.contains("disambig")
                    && fn_cols.contains("kind");

                if !fn_ok {
                    tracing::info!(
                        "migrating function_summaries: recreating table with identity columns"
                    );
                    conn.execute_batch("DROP TABLE IF EXISTS function_summaries;")?;
                    conn.execute_batch(SCHEMA)?;
                }

                // Migrate: verify SSA tables carry namespace + container/disambig/kind.
                let ssa_cols: std::collections::HashSet<String> = conn
                    .prepare("PRAGMA table_info(ssa_function_summaries)")
                    .and_then(|mut s| {
                        let cols: Vec<String> = s
                            .query_map([], |r| r.get::<_, String>(1))?
                            .filter_map(Result::ok)
                            .collect();
                        Ok(cols.into_iter().collect())
                    })
                    .unwrap_or_default();

                let ssa_ok = ssa_cols.contains("namespace")
                    && ssa_cols.contains("container")
                    && ssa_cols.contains("disambig")
                    && ssa_cols.contains("kind");

                if !ssa_ok {
                    tracing::info!("migrating ssa_function_summaries: recreating tables");
                    conn.execute_batch("DROP TABLE IF EXISTS ssa_function_summaries;")?;
                    conn.execute_batch("DROP TABLE IF EXISTS ssa_function_bodies;")?;
                    conn.execute_batch(SCHEMA)?;
                }

                // ssa_function_bodies may have been created with the old column set
                // even when ssa_function_summaries is current (e.g. partial
                // migrations).  Check and recreate independently.
                let body_cols: std::collections::HashSet<String> = conn
                    .prepare("PRAGMA table_info(ssa_function_bodies)")
                    .and_then(|mut s| {
                        let cols: Vec<String> = s
                            .query_map([], |r| r.get::<_, String>(1))?
                            .filter_map(Result::ok)
                            .collect();
                        Ok(cols.into_iter().collect())
                    })
                    .unwrap_or_default();

                let body_ok = body_cols.contains("namespace")
                    && body_cols.contains("container")
                    && body_cols.contains("disambig")
                    && body_cols.contains("kind");

                if !body_ok {
                    tracing::info!("migrating ssa_function_bodies: recreating table");
                    conn.execute_batch("DROP TABLE IF EXISTS ssa_function_bodies;")?;
                    conn.execute_batch(SCHEMA)?;
                }

                // Ensure the auth_check_summaries table exists for DBs
                // created before this column set was introduced.  The
                // `CREATE TABLE IF NOT EXISTS` in SCHEMA handles new DBs;
                // this branch only fires when the table is missing
                // entirely from a pre-existing DB.
                let auth_exists: bool = conn
                    .query_row(
                        "SELECT 1 FROM sqlite_master
                         WHERE type = 'table' AND name = 'auth_check_summaries'",
                        [],
                        |_| Ok(true),
                    )
                    .optional()?
                    .unwrap_or(false);
                if !auth_exists {
                    tracing::info!("creating auth_check_summaries table");
                    conn.execute_batch(SCHEMA)?;
                }

                // Schema version check: invalidate cached summary tables
                // when the on-disk artefact layout has changed in an
                // incompatible way, independently of the engine version.
                // Runs before `check_engine_version` so the engine-version
                // branch below does not race with a stale schema.
                Self::check_schema_version(&conn)?;

                // Engine version check: invalidate all caches when the scanner
                // version changes so stale serialized data cannot be loaded.
                Self::check_engine_version(&conn)?;
            }
            Ok(pool)
        }

        /// Check stored schema version against the compiled-in value.
        ///
        /// On mismatch (including first-time open), wipe the cached
        /// summary tables so pre-schema-bump artefacts cannot be
        /// rehydrated against the current engine.  Intentionally does
        /// not drop `files`, `scans`, or triage data: those are not
        /// layout-sensitive across this bump.
        fn check_schema_version(conn: &Connection) -> NyxResult<()> {
            let stored: Option<String> = conn
                .query_row(
                    "SELECT value FROM nyx_metadata WHERE key = 'schema_version'",
                    [],
                    |r| r.get(0),
                )
                .optional()?;

            let current = SCHEMA_VERSION;

            match stored {
                Some(ref v) if v == current => {
                    // Schema version matches, nothing to do.
                }
                _ => {
                    let old = stored.as_deref().unwrap_or("<none>");
                    tracing::info!(
                        "db schema version changed ({old} → {current}), clearing summary caches"
                    );
                    // Drop ssa_function_bodies entirely: column type changed
                    // to BLOB in v3 and `CREATE TABLE IF NOT EXISTS` will
                    // not migrate the column on an existing table.
                    conn.execute_batch(
                        "DROP TABLE IF EXISTS ssa_function_bodies;
                         DELETE FROM function_summaries;
                         DELETE FROM ssa_function_summaries;
                         DELETE FROM auth_check_summaries;
                         DELETE FROM files;",
                    )?;
                    conn.execute_batch(SCHEMA)?;
                    conn.execute(
                        "INSERT OR REPLACE INTO nyx_metadata (key, value) VALUES ('schema_version', ?1)",
                        params![current],
                    )?;
                }
            }
            Ok(())
        }

        /// Check stored engine version against the running binary.
        /// On mismatch (or missing row), wipe all cached analysis data so
        /// every file is rescanned with the new engine.
        fn check_engine_version(conn: &Connection) -> NyxResult<()> {
            let stored: Option<String> = conn
                .query_row(
                    "SELECT value FROM nyx_metadata WHERE key = 'engine_version'",
                    [],
                    |r| r.get(0),
                )
                .optional()?;

            let current = ENGINE_VERSION;

            match stored {
                Some(ref v) if v == current => {
                    // Version matches, nothing to do.
                }
                _ => {
                    let old = stored.as_deref().unwrap_or("<none>");
                    tracing::info!("engine version changed ({old} → {current}), rebuilding index");

                    // Wipe all cached summaries and file hashes so everything
                    // gets rescanned.
                    conn.execute_batch(
                        "DELETE FROM function_summaries;
                         DELETE FROM ssa_function_summaries;
                         DELETE FROM ssa_function_bodies;
                         DELETE FROM auth_check_summaries;
                         DELETE FROM files;",
                    )?;

                    conn.execute(
                        "INSERT OR REPLACE INTO nyx_metadata (key, value) VALUES ('engine_version', ?1)",
                        params![current],
                    )?;
                }
            }
            Ok(())
        }

        /// Persist the current engine version into metadata.
        ///
        /// Called after a successful scan to ensure the metadata row exists
        /// even for a freshly created database.
        pub fn write_engine_version(pool: &Pool<SqliteConnectionManager>) -> NyxResult<()> {
            let conn = pool.get()?;
            conn.execute(
                "INSERT OR REPLACE INTO nyx_metadata (key, value) VALUES ('engine_version', ?1)",
                params![ENGINE_VERSION],
            )?;
            Ok(())
        }

        /// Force a specific engine version into the metadata table.
        /// Used by tests to simulate version mismatch scenarios.
        #[cfg(test)]
        pub fn set_engine_version(
            pool: &Pool<SqliteConnectionManager>,
            version: &str,
        ) -> NyxResult<()> {
            let conn = pool.get()?;
            conn.execute(
                "INSERT OR REPLACE INTO nyx_metadata (key, value) VALUES ('engine_version', ?1)",
                params![version],
            )?;
            Ok(())
        }

        /// Read the stored engine version from metadata. Returns None if not set.
        #[cfg(test)]
        pub fn get_stored_engine_version(
            pool: &Pool<SqliteConnectionManager>,
        ) -> NyxResult<Option<String>> {
            let conn = pool.get()?;
            let v: Option<String> = conn
                .query_row(
                    "SELECT value FROM nyx_metadata WHERE key = 'engine_version'",
                    [],
                    |r| r.get(0),
                )
                .optional()?;
            Ok(v)
        }

        /// Count rows in a table for a given project. Test helper.
        #[cfg(test)]
        pub fn count_rows(
            pool: &Pool<SqliteConnectionManager>,
            table: &str,
            project: &str,
        ) -> NyxResult<i64> {
            let conn = pool.get()?;
            // table name can't be parameterized; this is test-only code with trusted inputs.
            let sql = format!("SELECT COUNT(*) FROM {table} WHERE project = ?1");
            let count: i64 = conn.query_row(&sql, params![project], |r| r.get(0))?;
            Ok(count)
        }

        /// Create a pool with init (schema + migrations + version check) for testing.
        /// This is `init()` but exposed under a clearer name for tests.
        #[cfg(test)]
        pub fn init_for_test(
            database_path: &Path,
        ) -> NyxResult<Arc<Pool<SqliteConnectionManager>>> {
            Self::init(database_path)
        }

        pub fn from_pool(project: &str, pool: &Pool<SqliteConnectionManager>) -> NyxResult<Self> {
            let conn = pool.get()?;
            Ok(Self {
                conn,
                project: project.to_owned(),
            })
        }

        // helper so code below can treat PooledConnection like &Connection
        fn c(&self) -> &Connection {
            self.conn.deref()
        }

        /// Return true when the file *content* or *mtime* changed since the last scan.
        ///
        /// Short-circuits on mtime: if the stored mtime matches the
        /// filesystem mtime, the file is assumed unchanged (skip hash).
        #[allow(dead_code)] // used in tests and by should_scan_with_hash callers may fall back
        pub fn should_scan(&self, path: &Path) -> NyxResult<bool> {
            let meta = fs::metadata(path)?;
            let mtime = meta.modified()?.duration_since(UNIX_EPOCH)?.as_secs() as i64;

            let row: Option<(Vec<u8>, i64)> = self
                .conn
                .query_row(
                    "SELECT hash, mtime FROM files WHERE project = ?1 AND path = ?2",
                    params![self.project, path.to_string_lossy()],
                    |r| Ok((r.get(0)?, r.get(1)?)),
                )
                .optional()?;

            Ok(match row {
                Some((stored_hash, stored_mtime)) => {
                    if stored_mtime != mtime {
                        // mtime changed, must re-scan
                        true
                    } else {
                        // mtime matches, compare hash only if cheap
                        // (the caller already read the file and can use
                        // should_scan_with_hash instead for full accuracy)
                        let digest = Self::digest_file(path)?;
                        stored_hash != digest
                    }
                }
                None => true,
            })
        }

        /// Like `should_scan` but accepts a pre-computed hash to avoid
        /// redundant file reads.
        pub fn should_scan_with_hash(&self, path: &Path, hash: &[u8]) -> NyxResult<bool> {
            let row: Option<Vec<u8>> = self
                .conn
                .query_row(
                    "SELECT hash FROM files WHERE project = ?1 AND path = ?2",
                    params![self.project, path.to_string_lossy()],
                    |r| r.get(0),
                )
                .optional()?;

            Ok(match row {
                Some(stored_hash) => stored_hash != hash,
                None => true,
            })
        }

        /// Insert or update the `files` row and return its id.
        pub fn upsert_file(&self, path: &Path) -> NyxResult<i64> {
            let bytes = fs::read(path)?;
            let hash = Self::digest_bytes(&bytes);
            self.upsert_file_with_hash(path, &hash)
        }

        /// Insert or update the `files` row using a pre-computed hash.
        /// Avoids redundant file reads when the caller already has the hash.
        pub fn upsert_file_with_hash(&self, path: &Path, hash: &[u8]) -> NyxResult<i64> {
            let meta = fs::metadata(path)?;
            let mtime = meta.modified()?.duration_since(UNIX_EPOCH)?.as_secs() as i64;
            let scanned_at = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;
            let path_str = path.to_string_lossy();

            // Use a single statement: upsert then query the id.
            self.c().execute(
                "INSERT INTO files (project, path, hash, mtime, scanned_at)
                 VALUES (?1, ?2, ?3, ?4, ?5)
                 ON CONFLICT(project,path) DO UPDATE
                 SET hash = excluded.hash,
                     mtime = excluded.mtime,
                     scanned_at = excluded.scanned_at",
                params![self.project, path_str, hash, mtime, scanned_at],
            )?;

            let id: i64 = self.c().query_row(
                "SELECT id FROM files WHERE project = ?1 AND path = ?2",
                params![self.project, path_str],
                |r| r.get(0),
            )?;
            Ok(id)
        }

        /// Replace all issues for `file_id` with the supplied set.
        ///
        /// Dedups rows by the same PRIMARY KEY the `issues` table enforces
        /// (`file_id, rule_id, line, col`) to defend against upstream bugs
        /// that produce same-keyed diagnostics with differing severity or
        /// cosmetic fields. The first-seen row wins; upstream
        /// `ParsedSource::finalize_diags` sorts so that high
        /// severity comes first, and this fallback preserves that ordering.
        pub fn replace_issues<'a>(
            &mut self,
            file_id: i64,
            issues: impl IntoIterator<Item = IssueRow<'a>>,
        ) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            tx.execute("DELETE FROM issues WHERE file_id = ?", params![file_id])?;

            {
                let mut stmt = tx.prepare(
                    "INSERT INTO issues (file_id, rule_id, severity, line, col)
                     VALUES (?1, ?2, ?3, ?4, ?5)",
                )?;
                let mut seen: std::collections::HashSet<(String, i64, i64)> =
                    std::collections::HashSet::new();
                for iss in issues {
                    if !seen.insert((iss.rule_id.to_string(), iss.line, iss.col)) {
                        continue;
                    }
                    stmt.execute(params![
                        file_id,
                        iss.rule_id,
                        iss.severity,
                        iss.line,
                        iss.col
                    ])?;
                }
            }
            tx.commit()?;
            Ok(())
        }

        /// Gets the issues for a specific file so we don't have to rescan
        pub fn get_issues_from_file(&self, path: &Path) -> NyxResult<Vec<Diag>> {
            let file_id: i64 = self.c().query_row(
                "SELECT id FROM files WHERE project = ?1 AND path = ?2",
                params![self.project, path.to_string_lossy()],
                |r| r.get(0),
            )?;

            let mut stmt = self.c().prepare(
                "SELECT rule_id, severity, line, col
         FROM issues
         WHERE file_id = ?1",
            )?;

            let issue_iter = stmt.query_map([file_id], |row| {
                let sev_str: String = row.get(1)?;
                let severity = Severity::from_str(&sev_str).unwrap_or_else(|_| {
                    tracing::warn!(
                        severity = %sev_str,
                        "unknown severity in DB row; defaulting to Medium"
                    );
                    Severity::Medium
                });
                Ok(Diag {
                    path: path.to_string_lossy().to_string(),
                    id: row.get::<_, String>(0)?, // rule_id
                    line: row.get::<_, i64>(2)? as usize,
                    col: row.get::<_, i64>(3)? as usize,
                    severity,
                    category: crate::patterns::FindingCategory::Security,
                    path_validated: false,
                    guard_kind: None,
                    message: None,
                    labels: vec![],
                    confidence: None,
                    evidence: None,
                    rank_score: None,
                    rank_reason: None,
                    suppressed: false,
                    suppression: None,
                    rollup: None,
                    finding_id: String::new(),
                    alternative_finding_ids: Vec::new(),
                })
            })?;

            Ok(issue_iter.filter_map(Result::ok).collect())
        }

        /// Atomically replace all function summaries for a single file.
        ///
        /// Deletes every existing summary row for `(project, file_path)` then
        /// inserts the new set.  This keeps the table in sync when a file is
        /// re‑parsed and its functions change.
        pub fn replace_summaries_for_file(
            &mut self,
            file_path: &Path,
            file_hash: &[u8],
            summaries: &[crate::summary::FuncSummary],
        ) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            let path_str = file_path.to_string_lossy();
            let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;

            tx.execute(
                "DELETE FROM function_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str],
            )?;

            {
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO function_summaries
                        (project, file_path, file_hash, name, arity, lang,
                         container, disambig, kind, summary, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                )?;

                for s in summaries {
                    let json = serde_json::to_string(s)
                        .map_err(|e| NyxError::Msg(format!("summary serialise: {e}")))?;
                    let disambig_sql = s.disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        s.name,
                        s.param_count as i64,
                        s.lang,
                        s.container,
                        disambig_sql,
                        s.kind.as_str(),
                        json,
                        now
                    ])?;
                }
            }

            tx.commit()?;
            Ok(())
        }

        /// Atomically replace all SSA function summaries for a single file.
        ///
        /// The input tuple is
        /// `(name, arity, lang, namespace, container, disambig, kind, summary)` ,
        /// matching the fields required to reconstruct a full [`crate::symbol::FuncKey`]
        /// on load.
        pub fn replace_ssa_summaries_for_file(
            &mut self,
            file_path: &Path,
            file_hash: &[u8],
            summaries: &[(
                String,
                usize,
                String,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::summary::ssa_summary::SsaFuncSummary,
            )],
        ) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            let path_str = file_path.to_string_lossy();
            let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;

            tx.execute(
                "DELETE FROM ssa_function_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str],
            )?;

            {
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO ssa_function_summaries
                        (project, file_path, file_hash, name, arity, lang, namespace,
                         container, disambig, kind, summary, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                )?;

                for (name, arity, lang, namespace, container, disambig, kind, summary) in summaries
                {
                    let json = serde_json::to_string(summary)
                        .map_err(|e| NyxError::Msg(format!("SSA summary serialise: {e}")))?;
                    let disambig_sql = disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        name,
                        *arity as i64,
                        lang,
                        namespace,
                        container,
                        disambig_sql,
                        kind.as_str(),
                        json,
                        now
                    ])?;
                }
            }

            tx.commit()?;
            Ok(())
        }

        /// Load every function summary for this project.
        ///
        /// Reads all JSON strings from SQLite in one pass, then
        /// deserializes them in parallel with rayon for large result sets.
        pub fn load_all_summaries(&self) -> NyxResult<Vec<crate::summary::FuncSummary>> {
            let mut stmt = self
                .c()
                .prepare("SELECT summary FROM function_summaries WHERE project = ?1")?;

            let jsons: Vec<String> = stmt
                .query_map([&self.project], |row| row.get::<_, String>(0))?
                .filter_map(|r| match r {
                    Ok(v) => Some(v),
                    Err(e) => {
                        tracing::warn!("failed to read summary row: {e}");
                        None
                    }
                })
                .collect();

            // Parallel JSON deserialization for large sets
            if jsons.len() > 256 {
                use rayon::prelude::*;
                let results: Vec<_> = jsons
                    .par_iter()
                    .filter_map(|json| {
                        serde_json::from_str::<crate::summary::FuncSummary>(json)
                            .map_err(|e| {
                                tracing::warn!("failed to deserialize summary JSON: {e}");
                                e
                            })
                            .ok()
                    })
                    .collect();
                Ok(results)
            } else {
                let mut out = Vec::with_capacity(jsons.len());
                for json in &jsons {
                    match serde_json::from_str::<crate::summary::FuncSummary>(json) {
                        Ok(s) => out.push(s),
                        Err(e) => {
                            tracing::warn!("failed to deserialize summary JSON: {e}");
                        }
                    }
                }
                Ok(out)
            }
        }

        /// Load every SSA function summary for this project.
        ///
        /// Returns rows with full metadata for `FuncKey` reconstruction:
        /// `(file_path, name, lang, arity, namespace, container, disambig, kind, SsaFuncSummary)`.
        pub fn load_all_ssa_summaries(
            &self,
        ) -> NyxResult<
            Vec<(
                String,
                String,
                String,
                i64,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::summary::ssa_summary::SsaFuncSummary,
            )>,
        > {
            let mut stmt = self.c().prepare(
                "SELECT file_path, name, lang, arity, namespace,
                        container, disambig, kind, summary
                 FROM ssa_function_summaries WHERE project = ?1",
            )?;

            let rows: Vec<(
                String,
                String,
                String,
                i64,
                String,
                String,
                Option<i64>,
                String,
                String,
            )> = stmt
                .query_map([&self.project], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, i64>(3)?,
                        row.get::<_, String>(4)?,
                        row.get::<_, String>(5)?,
                        row.get::<_, Option<i64>>(6)?,
                        row.get::<_, String>(7)?,
                        row.get::<_, String>(8)?,
                    ))
                })?
                .filter_map(|r| match r {
                    Ok(v) => Some(v),
                    Err(e) => {
                        tracing::warn!("failed to read SSA summary row: {e}");
                        None
                    }
                })
                .collect();

            if rows.len() > 256 {
                use rayon::prelude::*;
                let results: Vec<_> = rows
                    .par_iter()
                    .filter_map(
                        |(fp, name, lang, arity, ns, container, disambig, kind, json)| {
                            serde_json::from_str::<crate::summary::ssa_summary::SsaFuncSummary>(
                                json,
                            )
                            .map_err(|e| {
                                tracing::warn!("failed to deserialize SSA summary JSON: {e}");
                                e
                            })
                            .ok()
                            .map(|s| {
                                (
                                    fp.clone(),
                                    name.clone(),
                                    lang.clone(),
                                    *arity,
                                    ns.clone(),
                                    container.clone(),
                                    disambig.map(|d| d as u32),
                                    crate::symbol::FuncKind::from_slug(kind),
                                    s,
                                )
                            })
                        },
                    )
                    .collect();
                Ok(results)
            } else {
                let mut out = Vec::with_capacity(rows.len());
                for (fp, name, lang, arity, ns, container, disambig, kind, json) in &rows {
                    match serde_json::from_str::<crate::summary::ssa_summary::SsaFuncSummary>(json)
                    {
                        Ok(s) => {
                            out.push((
                                fp.clone(),
                                name.clone(),
                                lang.clone(),
                                *arity,
                                ns.clone(),
                                container.clone(),
                                disambig.map(|d| d as u32),
                                crate::symbol::FuncKind::from_slug(kind),
                                s,
                            ));
                        }
                        Err(e) => {
                            tracing::warn!("failed to deserialize SSA summary JSON: {e}");
                        }
                    }
                }
                Ok(out)
            }
        }

        /// Load symbol metadata (name, arity, lang, namespace, container, kind)
        /// for a single file.
        ///
        /// Lighter than `load_all_ssa_summaries`, skips JSON deserialization of
        /// the full summary body and filters by file_path in the query.  `kind`
        /// is the [`crate::symbol::FuncKind`] slug (`"fn"`, `"method"`,
        /// `"closure"`, ...) so consumers can distinguish anonymous functions
        /// from named ones.
        pub fn load_ssa_summaries_for_file(
            &self,
            file_path: &str,
        ) -> NyxResult<Vec<(String, i64, String, String, String, String)>> {
            let mut stmt = self.c().prepare(
                "SELECT name, arity, lang, namespace, container, kind
                 FROM ssa_function_summaries
                 WHERE project = ?1 AND file_path = ?2",
            )?;
            let rows: Vec<(String, i64, String, String, String, String)> = stmt
                .query_map(rusqlite::params![self.project, file_path], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, i64>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, String>(3)?,
                        row.get::<_, String>(4)?,
                        row.get::<_, String>(5)?,
                    ))
                })?
                .filter_map(Result::ok)
                .collect();
            Ok(rows)
        }

        /// Atomically replace all SSA callee bodies for a single file.
        ///
        /// Persists cross-file callee bodies for interprocedural symex.
        /// Bodies are serialized as MessagePack (rmp-serde, named-field
        /// encoding) BLOBs, JSON proved too costly at indexing time on
        /// large SSA structures, and bincode's positional format trips
        /// over the `#[serde(skip_serializing_if = ...)]` attributes
        /// scattered through `OptimizeResult` and friends.
        /// Input tuple: `(name, arity, lang, namespace, container, disambig, kind, body)`.
        pub fn replace_ssa_bodies_for_file(
            &mut self,
            file_path: &Path,
            file_hash: &[u8],
            bodies: &[(
                String,
                usize,
                String,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::taint::ssa_transfer::CalleeSsaBody,
            )],
        ) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            let path_str = file_path.to_string_lossy();
            let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;

            tx.execute(
                "DELETE FROM ssa_function_bodies WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str],
            )?;

            {
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO ssa_function_bodies
                        (project, file_path, file_hash, name, arity, lang, namespace,
                         container, disambig, kind, body, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                )?;

                for (name, arity, lang, namespace, container, disambig, kind, body) in bodies {
                    let blob = rmp_serde::to_vec_named(body)
                        .map_err(|e| NyxError::Msg(format!("SSA body serialise: {e}")))?;
                    let disambig_sql = disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        name,
                        *arity as i64,
                        lang,
                        namespace,
                        container,
                        disambig_sql,
                        kind.as_str(),
                        blob,
                        now
                    ])?;
                }
            }

            tx.commit()?;
            Ok(())
        }

        /// Load every SSA callee body for this project.
        ///
        /// Returns rows with full metadata for `FuncKey` reconstruction:
        /// `(file_path, name, lang, arity, namespace, container, disambig, kind, CalleeSsaBody)`.
        pub fn load_all_ssa_bodies(
            &self,
        ) -> NyxResult<
            Vec<(
                String,
                String,
                String,
                i64,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::taint::ssa_transfer::CalleeSsaBody,
            )>,
        > {
            let mut stmt = self.c().prepare(
                "SELECT file_path, name, lang, arity, namespace,
                        container, disambig, kind, body
                 FROM ssa_function_bodies WHERE project = ?1",
            )?;

            let rows: Vec<(
                String,
                String,
                String,
                i64,
                String,
                String,
                Option<i64>,
                String,
                Vec<u8>,
            )> = stmt
                .query_map([&self.project], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, i64>(3)?,
                        row.get::<_, String>(4)?,
                        row.get::<_, String>(5)?,
                        row.get::<_, Option<i64>>(6)?,
                        row.get::<_, String>(7)?,
                        row.get::<_, Vec<u8>>(8)?,
                    ))
                })?
                .filter_map(|r| match r {
                    Ok(v) => Some(v),
                    Err(e) => {
                        tracing::warn!("failed to read SSA body row: {e}");
                        None
                    }
                })
                .collect();

            if rows.len() > 256 {
                use rayon::prelude::*;
                let results: Vec<_> = rows
                    .par_iter()
                    .filter_map(
                        |(fp, name, lang, arity, ns, container, disambig, kind, blob)| {
                            rmp_serde::from_slice::<crate::taint::ssa_transfer::CalleeSsaBody>(blob)
                                .map_err(|e| {
                                    tracing::warn!("failed to deserialize SSA body: {e}");
                                    e
                                })
                                .ok()
                                .map(|mut b| {
                                    // Rehydrate a proxy Cfg from node_meta so
                                    // the taint engine's cross-file inline path can index
                                    // `cfg[inst.cfg_node]` uniformly.  No-op for intra-file
                                    // bodies that carry node_meta empty.
                                    crate::taint::ssa_transfer::rebuild_body_graph(&mut b);
                                    (
                                        fp.clone(),
                                        name.clone(),
                                        lang.clone(),
                                        *arity,
                                        ns.clone(),
                                        container.clone(),
                                        disambig.map(|d| d as u32),
                                        crate::symbol::FuncKind::from_slug(kind),
                                        b,
                                    )
                                })
                        },
                    )
                    .collect();
                Ok(results)
            } else {
                let mut out = Vec::with_capacity(rows.len());
                for (fp, name, lang, arity, ns, container, disambig, kind, blob) in &rows {
                    match rmp_serde::from_slice::<crate::taint::ssa_transfer::CalleeSsaBody>(blob) {
                        Ok(mut b) => {
                            // See note in parallel branch above.
                            crate::taint::ssa_transfer::rebuild_body_graph(&mut b);
                            out.push((
                                fp.clone(),
                                name.clone(),
                                lang.clone(),
                                *arity,
                                ns.clone(),
                                container.clone(),
                                disambig.map(|d| d as u32),
                                crate::symbol::FuncKind::from_slug(kind),
                                b,
                            ));
                        }
                        Err(e) => {
                            tracing::warn!("failed to deserialize SSA body: {e}");
                        }
                    }
                }
                Ok(out)
            }
        }

        /// Atomically replace all `AuthCheckSummary` rows for a single file.
        ///
        /// Mirrors [`Self::replace_ssa_summaries_for_file`].  Each input tuple
        /// is `(name, arity, lang, namespace, container, disambig, kind, summary)`
        ///, the full identity needed to reconstruct the callee's
        /// [`crate::symbol::FuncKey`] on load.
        pub fn replace_auth_summaries_for_file(
            &mut self,
            file_path: &Path,
            file_hash: &[u8],
            summaries: &[(
                String,
                usize,
                String,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::auth_analysis::model::AuthCheckSummary,
            )],
        ) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            let path_str = file_path.to_string_lossy();
            let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;

            tx.execute(
                "DELETE FROM auth_check_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str],
            )?;

            {
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO auth_check_summaries
                        (project, file_path, file_hash, name, arity, lang, namespace,
                         container, disambig, kind, summary, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                )?;

                for (name, arity, lang, namespace, container, disambig, kind, summary) in summaries
                {
                    let json = serde_json::to_string(summary)
                        .map_err(|e| NyxError::Msg(format!("auth summary serialise: {e}")))?;
                    let disambig_sql = disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        name,
                        *arity as i64,
                        lang,
                        namespace,
                        container,
                        disambig_sql,
                        kind.as_str(),
                        json,
                        now
                    ])?;
                }
            }

            tx.commit()?;
            Ok(())
        }

        /// Atomically replace all four per-file caches in a single
        /// transaction.  Equivalent in effect to calling
        /// [`Self::replace_summaries_for_file`],
        /// [`Self::replace_ssa_summaries_for_file`],
        /// [`Self::replace_ssa_bodies_for_file`] and
        /// [`Self::replace_auth_summaries_for_file`] in sequence, but
        /// issues a single fsync at commit instead of four, the
        /// dominant cost on large scans.
        ///
        /// Behaviour parity with the four-call sequence:
        /// * function and auth summaries: DELETE-then-INSERT regardless
        ///   of input length, so emptying a file's summaries clears
        ///   stale rows.
        /// * SSA summaries and bodies: only touched when the input is
        ///   non-empty, matching the existing scan path.
        #[allow(clippy::too_many_arguments)]
        pub fn replace_all_for_file(
            &mut self,
            file_path: &Path,
            file_hash: &[u8],
            func_summaries: &[crate::summary::FuncSummary],
            ssa_summaries: &[(
                String,
                usize,
                String,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::summary::ssa_summary::SsaFuncSummary,
            )],
            ssa_bodies: &[(
                String,
                usize,
                String,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::taint::ssa_transfer::CalleeSsaBody,
            )],
            auth_summaries: &[(
                String,
                usize,
                String,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::auth_analysis::model::AuthCheckSummary,
            )],
        ) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            let path_str = file_path.to_string_lossy();
            let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs() as i64;

            // function_summaries, always replace.
            tx.execute(
                "DELETE FROM function_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str],
            )?;
            {
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO function_summaries
                        (project, file_path, file_hash, name, arity, lang,
                         container, disambig, kind, summary, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)",
                )?;
                for s in func_summaries {
                    let json = serde_json::to_string(s)
                        .map_err(|e| NyxError::Msg(format!("summary serialise: {e}")))?;
                    let disambig_sql = s.disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        s.name,
                        s.param_count as i64,
                        s.lang,
                        s.container,
                        disambig_sql,
                        s.kind.as_str(),
                        json,
                        now
                    ])?;
                }
            }

            // ssa_function_summaries, only touched when non-empty.
            if !ssa_summaries.is_empty() {
                tx.execute(
                    "DELETE FROM ssa_function_summaries
                     WHERE project = ?1 AND file_path = ?2",
                    params![self.project, path_str],
                )?;
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO ssa_function_summaries
                        (project, file_path, file_hash, name, arity, lang, namespace,
                         container, disambig, kind, summary, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                )?;
                for (name, arity, lang, namespace, container, disambig, kind, summary) in
                    ssa_summaries
                {
                    let json = serde_json::to_string(summary)
                        .map_err(|e| NyxError::Msg(format!("SSA summary serialise: {e}")))?;
                    let disambig_sql = disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        name,
                        *arity as i64,
                        lang,
                        namespace,
                        container,
                        disambig_sql,
                        kind.as_str(),
                        json,
                        now
                    ])?;
                }
            }

            // ssa_function_bodies, only touched when non-empty.
            if !ssa_bodies.is_empty() {
                tx.execute(
                    "DELETE FROM ssa_function_bodies
                     WHERE project = ?1 AND file_path = ?2",
                    params![self.project, path_str],
                )?;
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO ssa_function_bodies
                        (project, file_path, file_hash, name, arity, lang, namespace,
                         container, disambig, kind, body, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                )?;
                for (name, arity, lang, namespace, container, disambig, kind, body) in ssa_bodies {
                    let blob = rmp_serde::to_vec_named(body)
                        .map_err(|e| NyxError::Msg(format!("SSA body serialise: {e}")))?;
                    let disambig_sql = disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        name,
                        *arity as i64,
                        lang,
                        namespace,
                        container,
                        disambig_sql,
                        kind.as_str(),
                        blob,
                        now
                    ])?;
                }
            }

            // auth_check_summaries, always replace, even when empty,
            // so a helper that lost its ownership check no longer
            // leaks lifts into subsequent pass-2 runs.
            tx.execute(
                "DELETE FROM auth_check_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str],
            )?;
            {
                let mut stmt = tx.prepare(
                    "INSERT OR REPLACE INTO auth_check_summaries
                        (project, file_path, file_hash, name, arity, lang, namespace,
                         container, disambig, kind, summary, updated_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)",
                )?;
                for (name, arity, lang, namespace, container, disambig, kind, summary) in
                    auth_summaries
                {
                    let json = serde_json::to_string(summary)
                        .map_err(|e| NyxError::Msg(format!("auth summary serialise: {e}")))?;
                    let disambig_sql = disambig.map(|d| d as i64);
                    stmt.execute(params![
                        self.project,
                        path_str,
                        file_hash,
                        name,
                        *arity as i64,
                        lang,
                        namespace,
                        container,
                        disambig_sql,
                        kind.as_str(),
                        json,
                        now
                    ])?;
                }
            }

            tx.commit()?;
            Ok(())
        }

        /// Load every `AuthCheckSummary` for this project.
        ///
        /// Returns rows with full metadata for `FuncKey` reconstruction:
        /// `(file_path, name, lang, arity, namespace, container, disambig, kind, AuthCheckSummary)`.
        pub fn load_all_auth_summaries(
            &self,
        ) -> NyxResult<
            Vec<(
                String,
                String,
                String,
                i64,
                String,
                String,
                Option<u32>,
                crate::symbol::FuncKind,
                crate::auth_analysis::model::AuthCheckSummary,
            )>,
        > {
            let mut stmt = self.c().prepare(
                "SELECT file_path, name, lang, arity, namespace,
                        container, disambig, kind, summary
                 FROM auth_check_summaries WHERE project = ?1",
            )?;

            let rows: Vec<(
                String,
                String,
                String,
                i64,
                String,
                String,
                Option<i64>,
                String,
                String,
            )> = stmt
                .query_map([&self.project], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, i64>(3)?,
                        row.get::<_, String>(4)?,
                        row.get::<_, String>(5)?,
                        row.get::<_, Option<i64>>(6)?,
                        row.get::<_, String>(7)?,
                        row.get::<_, String>(8)?,
                    ))
                })?
                .filter_map(|r| match r {
                    Ok(v) => Some(v),
                    Err(e) => {
                        tracing::warn!("failed to read auth summary row: {e}");
                        None
                    }
                })
                .collect();

            let mut out = Vec::with_capacity(rows.len());
            for (fp, name, lang, arity, ns, container, disambig, kind, json) in &rows {
                match serde_json::from_str::<crate::auth_analysis::model::AuthCheckSummary>(json) {
                    Ok(s) => {
                        out.push((
                            fp.clone(),
                            name.clone(),
                            lang.clone(),
                            *arity,
                            ns.clone(),
                            container.clone(),
                            disambig.map(|d| d as u32),
                            crate::symbol::FuncKind::from_slug(kind),
                            s,
                        ));
                    }
                    Err(e) => {
                        tracing::warn!("failed to deserialize auth summary JSON: {e}");
                    }
                }
            }
            Ok(out)
        }

        /// Remove a file and all derived persisted state for this project.
        ///
        /// This deletes the file row, issues, and all persisted summary rows so
        /// incremental scans can prune deleted files from the index cleanly.
        pub fn remove_file_and_related(&mut self, path: &Path) -> NyxResult<()> {
            let tx = self.conn.transaction()?;
            let path_str = path.to_string_lossy();

            let file_id: Option<i64> = tx
                .query_row(
                    "SELECT id FROM files WHERE project = ?1 AND path = ?2",
                    params![self.project, path_str.as_ref()],
                    |r| r.get(0),
                )
                .optional()?;

            if let Some(file_id) = file_id {
                tx.execute("DELETE FROM issues WHERE file_id = ?1", params![file_id])?;
                tx.execute("DELETE FROM files WHERE id = ?1", params![file_id])?;
            }

            tx.execute(
                "DELETE FROM function_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str.as_ref()],
            )?;
            tx.execute(
                "DELETE FROM ssa_function_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str.as_ref()],
            )?;
            tx.execute(
                "DELETE FROM ssa_function_bodies WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str.as_ref()],
            )?;
            tx.execute(
                "DELETE FROM auth_check_summaries WHERE project = ?1 AND file_path = ?2",
                params![self.project, path_str.as_ref()],
            )?;

            tx.commit()?;
            Ok(())
        }

        /// gets files from the database
        pub fn get_files(&self, project: &str) -> NyxResult<Vec<PathBuf>> {
            let mut stmt = self.c().prepare(
                "SELECT path
         FROM files
         WHERE project = ?1",
            )?;

            let file_iter = stmt.query_map([project], |row| row.get::<_, String>(0))?;

            Ok(file_iter
                .map(|p| p.map(PathBuf::from))
                .collect::<Result<_, _>>()?)
        }

        // -------------------------------------------------------------------------
        // Scan persistence
        // -------------------------------------------------------------------------

        /// Insert a new scan record.
        pub fn insert_scan(&self, record: &ScanRecord) -> NyxResult<()> {
            self.c().execute(
                "INSERT OR REPLACE INTO scans (id, status, scan_root, started_at, finished_at,
                 duration_secs, engine_version, languages, files_scanned, files_skipped,
                 finding_count, findings_json, timing_json, error)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)",
                params![
                    record.id,
                    record.status,
                    record.scan_root,
                    record.started_at,
                    record.finished_at,
                    record.duration_secs,
                    record.engine_version,
                    record.languages,
                    record.files_scanned,
                    record.files_skipped,
                    record.finding_count,
                    record.findings_json,
                    record.timing_json,
                    record.error,
                ],
            )?;
            Ok(())
        }

        /// Update a scan record status and completion fields.
        pub fn update_scan(
            &self,
            id: &str,
            status: &str,
            finished_at: Option<&str>,
            duration_secs: Option<f64>,
            finding_count: Option<i64>,
            findings_json: Option<&str>,
            timing_json: Option<&str>,
            error: Option<&str>,
            files_scanned: Option<i64>,
            files_skipped: Option<i64>,
            languages: Option<&str>,
        ) -> NyxResult<()> {
            self.c().execute(
                "UPDATE scans SET status = ?2, finished_at = ?3, duration_secs = ?4,
                 finding_count = ?5, findings_json = ?6, timing_json = ?7, error = ?8,
                 files_scanned = ?9, files_skipped = ?10, languages = ?11
                 WHERE id = ?1",
                params![
                    id,
                    status,
                    finished_at,
                    duration_secs,
                    finding_count,
                    findings_json,
                    timing_json,
                    error,
                    files_scanned,
                    files_skipped,
                    languages,
                ],
            )?;
            Ok(())
        }

        /// Get a single scan record by ID.
        pub fn get_scan(&self, id: &str) -> NyxResult<Option<ScanRecord>> {
            let result = self
                .c()
                .query_row(
                    "SELECT id, status, scan_root, started_at, finished_at, duration_secs,
                     engine_version, languages, files_scanned, files_skipped, finding_count,
                     findings_json, timing_json, error
                     FROM scans WHERE id = ?1",
                    params![id],
                    |row| {
                        Ok(ScanRecord {
                            id: row.get(0)?,
                            status: row.get(1)?,
                            scan_root: row.get(2)?,
                            started_at: row.get(3)?,
                            finished_at: row.get(4)?,
                            duration_secs: row.get(5)?,
                            engine_version: row.get(6)?,
                            languages: row.get(7)?,
                            files_scanned: row.get(8)?,
                            files_skipped: row.get(9)?,
                            finding_count: row.get(10)?,
                            findings_json: row.get(11)?,
                            timing_json: row.get(12)?,
                            error: row.get(13)?,
                        })
                    },
                )
                .optional()?;
            Ok(result)
        }

        /// List scan records, most recent first, up to `limit`.
        pub fn list_scans(&self, limit: i64) -> NyxResult<Vec<ScanRecord>> {
            let mut stmt = self.c().prepare(
                "SELECT id, status, scan_root, started_at, finished_at, duration_secs,
                 engine_version, languages, files_scanned, files_skipped, finding_count,
                 findings_json, timing_json, error
                 FROM scans ORDER BY started_at DESC LIMIT ?1",
            )?;
            let rows = stmt
                .query_map(params![limit], |row| {
                    Ok(ScanRecord {
                        id: row.get(0)?,
                        status: row.get(1)?,
                        scan_root: row.get(2)?,
                        started_at: row.get(3)?,
                        finished_at: row.get(4)?,
                        duration_secs: row.get(5)?,
                        engine_version: row.get(6)?,
                        languages: row.get(7)?,
                        files_scanned: row.get(8)?,
                        files_skipped: row.get(9)?,
                        finding_count: row.get(10)?,
                        findings_json: row.get(11)?,
                        timing_json: row.get(12)?,
                        error: row.get(13)?,
                    })
                })?
                .filter_map(Result::ok)
                .collect();
            Ok(rows)
        }

        /// Delete a scan and its associated metrics/logs (FK CASCADE).
        pub fn delete_scan(&self, id: &str) -> NyxResult<usize> {
            let rows = self
                .c()
                .execute("DELETE FROM scans WHERE id = ?1", params![id])?;
            Ok(rows)
        }

        /// Insert scan metrics for a completed scan.
        pub fn insert_scan_metrics(
            &self,
            scan_id: &str,
            metrics: &crate::server::progress::ScanMetricsSnapshot,
        ) -> NyxResult<()> {
            self.c().execute(
                "INSERT OR REPLACE INTO scan_metrics (scan_id, cfg_nodes, call_edges,
                 functions_analyzed, summaries_reused, unresolved_calls)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    scan_id,
                    metrics.cfg_nodes as i64,
                    metrics.call_edges as i64,
                    metrics.functions_analyzed as i64,
                    metrics.summaries_reused as i64,
                    metrics.unresolved_calls as i64,
                ],
            )?;
            Ok(())
        }

        /// Get scan metrics by scan ID.
        pub fn get_scan_metrics(
            &self,
            scan_id: &str,
        ) -> NyxResult<Option<crate::server::progress::ScanMetricsSnapshot>> {
            let result = self
                .c()
                .query_row(
                    "SELECT cfg_nodes, call_edges, functions_analyzed,
                     summaries_reused, unresolved_calls
                     FROM scan_metrics WHERE scan_id = ?1",
                    params![scan_id],
                    |row| {
                        Ok(crate::server::progress::ScanMetricsSnapshot {
                            cfg_nodes: row.get::<_, i64>(0)? as u64,
                            call_edges: row.get::<_, i64>(1)? as u64,
                            functions_analyzed: row.get::<_, i64>(2)? as u64,
                            summaries_reused: row.get::<_, i64>(3)? as u64,
                            unresolved_calls: row.get::<_, i64>(4)? as u64,
                        })
                    },
                )
                .optional()?;
            Ok(result)
        }

        /// Insert scan log entries.
        pub fn insert_scan_logs(
            &self,
            scan_id: &str,
            logs: &[crate::server::scan_log::ScanLogEntry],
        ) -> NyxResult<()> {
            let mut stmt = self.c().prepare(
                "INSERT INTO scan_logs (scan_id, timestamp, level, message, file_path, detail)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            )?;
            for log in logs {
                stmt.execute(params![
                    scan_id,
                    log.timestamp.to_rfc3339(),
                    log.level.to_string(),
                    log.message,
                    log.file_path,
                    log.detail,
                ])?;
            }
            Ok(())
        }

        /// Get scan logs, optionally filtered by level.
        pub fn get_scan_logs(
            &self,
            scan_id: &str,
            level_filter: Option<&str>,
        ) -> NyxResult<Vec<crate::server::scan_log::ScanLogEntry>> {
            let (sql, params_vec): (&str, Vec<Box<dyn rusqlite::types::ToSql>>) =
                if let Some(level) = level_filter {
                    (
                        "SELECT timestamp, level, message, file_path, detail
                         FROM scan_logs WHERE scan_id = ?1 AND level = ?2
                         ORDER BY id ASC",
                        vec![Box::new(scan_id.to_string()), Box::new(level.to_string())],
                    )
                } else {
                    (
                        "SELECT timestamp, level, message, file_path, detail
                         FROM scan_logs WHERE scan_id = ?1
                         ORDER BY id ASC",
                        vec![Box::new(scan_id.to_string())],
                    )
                };

            let mut stmt = self.c().prepare(sql)?;
            let params_refs: Vec<&dyn rusqlite::types::ToSql> =
                params_vec.iter().map(|p| p.as_ref()).collect();
            let rows = stmt
                .query_map(params_refs.as_slice(), |row| {
                    let ts_str: String = row.get(0)?;
                    let level_str: String = row.get(1)?;
                    Ok((
                        ts_str,
                        level_str,
                        row.get::<_, String>(2)?,
                        row.get::<_, Option<String>>(3)?,
                        row.get::<_, Option<String>>(4)?,
                    ))
                })?
                .filter_map(Result::ok)
                .filter_map(|(ts_str, level_str, message, file_path, detail)| {
                    let timestamp = chrono::DateTime::parse_from_rfc3339(&ts_str)
                        .ok()?
                        .with_timezone(&chrono::Utc);
                    let level = level_str.parse().ok()?;
                    Some(crate::server::scan_log::ScanLogEntry {
                        timestamp,
                        level,
                        message,
                        file_path,
                        detail,
                    })
                })
                .collect();
            Ok(rows)
        }

        // -------------------------------------------------------------------------
        // Triage state management
        // -------------------------------------------------------------------------

        /// Get the triage state for a single finding fingerprint.
        /// Returns (state, note, updated_at) or None if no triage state exists.
        #[allow(dead_code)]
        pub fn get_triage_state(
            &self,
            fingerprint: &str,
        ) -> NyxResult<Option<(String, String, String)>> {
            let result = self
                .c()
                .query_row(
                    "SELECT state, note, updated_at FROM triage_states WHERE fingerprint = ?1",
                    params![fingerprint],
                    |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
                )
                .optional()?;
            Ok(result)
        }

        /// Set the triage state for a single finding. Upserts the state and
        /// appends an audit log entry. Returns the previous state (or "open").
        #[allow(dead_code)]
        pub fn set_triage_state(
            &self,
            fingerprint: &str,
            state: &str,
            note: &str,
            action: &str,
        ) -> NyxResult<String> {
            let now = chrono::Utc::now().to_rfc3339();
            let prev: String = self
                .c()
                .query_row(
                    "SELECT state FROM triage_states WHERE fingerprint = ?1",
                    params![fingerprint],
                    |row| row.get(0),
                )
                .optional()?
                .unwrap_or_else(|| "open".to_string());

            self.c().execute(
                "INSERT INTO triage_states (fingerprint, state, note, updated_at)
                 VALUES (?1, ?2, ?3, ?4)
                 ON CONFLICT(fingerprint) DO UPDATE
                 SET state = excluded.state, note = excluded.note, updated_at = excluded.updated_at",
                params![fingerprint, state, note, now],
            )?;

            self.c().execute(
                "INSERT INTO triage_audit_log (fingerprint, action, previous_state, new_state, note, timestamp)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![fingerprint, action, prev, state, note, now],
            )?;

            Ok(prev)
        }

        /// Bulk set triage state. Returns vec of (fingerprint, previous_state).
        pub fn set_triage_states_bulk(
            &self,
            fingerprints: &[String],
            state: &str,
            note: &str,
            action: &str,
        ) -> NyxResult<Vec<(String, String)>> {
            let now = chrono::Utc::now().to_rfc3339();
            let mut results = Vec::with_capacity(fingerprints.len());

            // Read all previous states first
            let mut prev_stmt = self
                .c()
                .prepare("SELECT state FROM triage_states WHERE fingerprint = ?1")?;

            for fp in fingerprints {
                let prev: String = prev_stmt
                    .query_row(params![fp], |row| row.get(0))
                    .optional()?
                    .unwrap_or_else(|| "open".to_string());
                results.push((fp.clone(), prev));
            }
            drop(prev_stmt);

            // Upsert all states
            let mut upsert_stmt = self.c().prepare(
                "INSERT INTO triage_states (fingerprint, state, note, updated_at)
                 VALUES (?1, ?2, ?3, ?4)
                 ON CONFLICT(fingerprint) DO UPDATE
                 SET state = excluded.state, note = excluded.note, updated_at = excluded.updated_at",
            )?;
            for fp in fingerprints {
                upsert_stmt.execute(params![fp, state, note, now])?;
            }
            drop(upsert_stmt);

            // Insert audit log entries
            let mut audit_stmt = self.c().prepare(
                "INSERT INTO triage_audit_log (fingerprint, action, previous_state, new_state, note, timestamp)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
            )?;
            for (fp, prev) in &results {
                audit_stmt.execute(params![fp, action, prev, state, note, now])?;
            }

            Ok(results)
        }

        /// Load all triage states as a map: fingerprint → (state, note, updated_at).
        pub fn get_all_triage_states(
            &self,
        ) -> NyxResult<std::collections::HashMap<String, (String, String, String)>> {
            let mut stmt = self
                .c()
                .prepare("SELECT fingerprint, state, note, updated_at FROM triage_states")?;
            let rows = stmt
                .query_map([], |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, String>(3)?,
                    ))
                })?
                .filter_map(Result::ok)
                .map(|(fp, state, note, updated)| (fp, (state, note, updated)))
                .collect();
            Ok(rows)
        }

        /// List triage states with optional state filter, paginated.
        /// Returns (entries, total_count).
        pub fn list_triage_states(
            &self,
            state_filter: Option<&str>,
            limit: i64,
            offset: i64,
        ) -> NyxResult<(Vec<(String, String, String, String)>, i64)> {
            let (sql, count_sql, params_vec): (&str, &str, Vec<Box<dyn rusqlite::types::ToSql>>) =
                if let Some(state) = state_filter {
                    (
                        "SELECT fingerprint, state, note, updated_at FROM triage_states
                         WHERE state = ?1 ORDER BY updated_at DESC LIMIT ?2 OFFSET ?3",
                        "SELECT COUNT(*) FROM triage_states WHERE state = ?1",
                        vec![
                            Box::new(state.to_string()),
                            Box::new(limit),
                            Box::new(offset),
                        ],
                    )
                } else {
                    (
                        "SELECT fingerprint, state, note, updated_at FROM triage_states
                         ORDER BY updated_at DESC LIMIT ?1 OFFSET ?2",
                        "SELECT COUNT(*) FROM triage_states",
                        vec![Box::new(limit), Box::new(offset)],
                    )
                };

            let total: i64 = if let Some(state) = state_filter {
                self.c()
                    .query_row(count_sql, params![state], |row| row.get(0))?
            } else {
                self.c().query_row(count_sql, [], |row| row.get(0))?
            };

            let mut stmt = self.c().prepare(sql)?;
            let params_refs: Vec<&dyn rusqlite::types::ToSql> =
                params_vec.iter().map(|p| p.as_ref()).collect();
            let rows = stmt
                .query_map(params_refs.as_slice(), |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, String>(1)?,
                        row.get::<_, String>(2)?,
                        row.get::<_, String>(3)?,
                    ))
                })?
                .filter_map(Result::ok)
                .collect();
            Ok((rows, total))
        }

        /// Get the audit log, optionally filtered by fingerprint, paginated.
        /// Returns (entries, total_count).
        pub fn get_audit_log(
            &self,
            fingerprint_filter: Option<&str>,
            limit: i64,
            offset: i64,
        ) -> NyxResult<(Vec<AuditEntry>, i64)> {
            let (sql, count_sql, params_vec): (&str, &str, Vec<Box<dyn rusqlite::types::ToSql>>) =
                if let Some(fp) = fingerprint_filter {
                    (
                        "SELECT id, fingerprint, action, previous_state, new_state, note, timestamp
                         FROM triage_audit_log WHERE fingerprint = ?1
                         ORDER BY timestamp DESC LIMIT ?2 OFFSET ?3",
                        "SELECT COUNT(*) FROM triage_audit_log WHERE fingerprint = ?1",
                        vec![Box::new(fp.to_string()), Box::new(limit), Box::new(offset)],
                    )
                } else {
                    (
                        "SELECT id, fingerprint, action, previous_state, new_state, note, timestamp
                         FROM triage_audit_log ORDER BY timestamp DESC LIMIT ?1 OFFSET ?2",
                        "SELECT COUNT(*) FROM triage_audit_log",
                        vec![Box::new(limit), Box::new(offset)],
                    )
                };

            let total: i64 = if let Some(fp) = fingerprint_filter {
                self.c()
                    .query_row(count_sql, params![fp], |row| row.get(0))?
            } else {
                self.c().query_row(count_sql, [], |row| row.get(0))?
            };

            let mut stmt = self.c().prepare(sql)?;
            let params_refs: Vec<&dyn rusqlite::types::ToSql> =
                params_vec.iter().map(|p| p.as_ref()).collect();
            let rows = stmt
                .query_map(params_refs.as_slice(), |row| {
                    Ok(AuditEntry {
                        id: row.get(0)?,
                        fingerprint: row.get(1)?,
                        action: row.get(2)?,
                        previous_state: row.get(3)?,
                        new_state: row.get(4)?,
                        note: row.get(5)?,
                        timestamp: row.get(6)?,
                    })
                })?
                .filter_map(Result::ok)
                .collect();
            Ok((rows, total))
        }

        /// Add a pattern-based suppression rule.
        pub fn add_suppression_rule(
            &self,
            suppress_by: &str,
            match_value: &str,
            state: &str,
            note: &str,
        ) -> NyxResult<i64> {
            let now = chrono::Utc::now().to_rfc3339();
            self.c().execute(
                "INSERT OR REPLACE INTO triage_suppression_rules
                 (suppress_by, match_value, state, note, created_at)
                 VALUES (?1, ?2, ?3, ?4, ?5)",
                params![suppress_by, match_value, state, note, now],
            )?;
            Ok(self.c().last_insert_rowid())
        }

        /// Get all suppression rules.
        pub fn get_suppression_rules(&self) -> NyxResult<Vec<SuppressionRule>> {
            let mut stmt = self.c().prepare(
                "SELECT id, suppress_by, match_value, state, note, created_at
                 FROM triage_suppression_rules ORDER BY created_at DESC",
            )?;
            let rows = stmt
                .query_map([], |row| {
                    Ok(SuppressionRule {
                        id: row.get(0)?,
                        suppress_by: row.get(1)?,
                        match_value: row.get(2)?,
                        state: row.get(3)?,
                        note: row.get(4)?,
                        created_at: row.get(5)?,
                    })
                })?
                .filter_map(Result::ok)
                .collect();
            Ok(rows)
        }

        /// Record the first time a finding fingerprint was observed. Idempotent ,
        /// the earliest call wins via INSERT OR IGNORE. Used by the overview
        /// backlog-age computation; ts should be the originating scan's
        /// `started_at` (RFC-3339).
        pub fn record_finding_first_seen(&self, fingerprint: &str, ts: &str) -> NyxResult<()> {
            self.c().execute(
                "INSERT OR IGNORE INTO finding_first_seen (fingerprint, first_seen_at) VALUES (?1, ?2)",
                params![fingerprint, ts],
            )?;
            Ok(())
        }

        /// Bulk variant. Inserts ignoring conflicts.
        pub fn record_finding_first_seen_bulk(
            &self,
            entries: &[(String, String)],
        ) -> NyxResult<()> {
            if entries.is_empty() {
                return Ok(());
            }
            let conn = self.c();
            let tx = conn.unchecked_transaction()?;
            {
                let mut stmt = tx.prepare(
                    "INSERT OR IGNORE INTO finding_first_seen (fingerprint, first_seen_at) VALUES (?1, ?2)",
                )?;
                for (fp, ts) in entries {
                    stmt.execute(params![fp, ts])?;
                }
            }
            tx.commit()?;
            Ok(())
        }

        /// Look up first-seen timestamps for a set of fingerprints. Missing
        /// entries are simply absent from the returned map.
        pub fn get_first_seen_map(
            &self,
            fingerprints: &[String],
        ) -> NyxResult<std::collections::HashMap<String, String>> {
            if fingerprints.is_empty() {
                return Ok(std::collections::HashMap::new());
            }
            // SQLite IN-clause cap is high but parameter count is bounded, chunk
            // for safety with large fingerprint sets.
            let mut out = std::collections::HashMap::with_capacity(fingerprints.len());
            let conn = self.c();
            for chunk in fingerprints.chunks(500) {
                let placeholders = (1..=chunk.len())
                    .map(|i| format!("?{i}"))
                    .collect::<Vec<_>>()
                    .join(",");
                let sql = format!(
                    "SELECT fingerprint, first_seen_at FROM finding_first_seen WHERE fingerprint IN ({placeholders})"
                );
                let mut stmt = conn.prepare(&sql)?;
                let params: Vec<&dyn rusqlite::ToSql> =
                    chunk.iter().map(|s| s as &dyn rusqlite::ToSql).collect();
                let rows = stmt.query_map(params.as_slice(), |row| {
                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
                })?;
                for r in rows.flatten() {
                    out.insert(r.0, r.1);
                }
            }
            Ok(out)
        }

        /// Get a single metadata value by key. Returns None if absent.
        pub fn get_metadata(&self, key: &str) -> NyxResult<Option<String>> {
            let conn = self.c();
            let mut stmt = conn.prepare("SELECT value FROM nyx_metadata WHERE key = ?1")?;
            let mut rows = stmt.query(params![key])?;
            if let Some(row) = rows.next()? {
                Ok(Some(row.get(0)?))
            } else {
                Ok(None)
            }
        }

        /// Set a metadata value (insert-or-replace).
        pub fn set_metadata(&self, key: &str, value: &str) -> NyxResult<()> {
            self.c().execute(
                "INSERT OR REPLACE INTO nyx_metadata (key, value) VALUES (?1, ?2)",
                params![key, value],
            )?;
            Ok(())
        }

        /// Remove a metadata key. Returns true if a row was deleted.
        pub fn delete_metadata(&self, key: &str) -> NyxResult<bool> {
            let n = self
                .c()
                .execute("DELETE FROM nyx_metadata WHERE key = ?1", params![key])?;
            Ok(n > 0)
        }

        /// Delete a suppression rule by ID. Returns true if a row was deleted.
        pub fn delete_suppression_rule(&self, id: i64) -> NyxResult<bool> {
            let count = self.c().execute(
                "DELETE FROM triage_suppression_rules WHERE id = ?1",
                params![id],
            )?;
            Ok(count > 0)
        }

        // -------------------------------------------------------------------------
        // Maintenance utilities
        // -------------------------------------------------------------------------
        pub fn clear(&self) -> NyxResult<()> {
            self.c().execute_batch(
                r#"
        PRAGMA foreign_keys = OFF;

        DROP TABLE IF EXISTS issues;
        DROP TABLE IF EXISTS files;
        DROP TABLE IF EXISTS function_summaries;
        DROP TABLE IF EXISTS ssa_function_summaries;

        PRAGMA foreign_keys = ON;
        VACUUM;
        "#,
            )?;

            self.c().execute_batch(SCHEMA)?;
            Ok(())
        }

        pub fn vacuum(&self) -> NyxResult<()> {
            self.c().execute("VACUUM;", [])?;
            Ok(())
        }

        // -------------------------------------------------------------------------
        // Helpers
        // -------------------------------------------------------------------------
        #[allow(dead_code)] // used by should_scan() and tests
        fn digest_file(path: &Path) -> NyxResult<Vec<u8>> {
            let mut hasher = blake3::Hasher::new();
            let mut file = fs::File::open(path)?;
            std::io::copy(&mut file, &mut hasher)?;
            Ok(hasher.finalize().as_bytes().to_vec())
        }

        /// Hash already-read bytes without re-reading from disk.
        pub fn digest_bytes(bytes: &[u8]) -> Vec<u8> {
            let mut hasher = blake3::Hasher::new();
            hasher.update(bytes);
            hasher.finalize().as_bytes().to_vec()
        }
    }
}

#[test]
fn indexer_should_scan_and_upsert_logic() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let file = td.path().join("sample.rs");
    std::fs::write(&file, "fn main() {}").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let idx = index::Indexer::from_pool("proj", &pool).unwrap();

    // first time: nothing in DB → must scan
    assert!(idx.should_scan(&file).unwrap());

    // after upsert: no changes → should *not* scan
    idx.upsert_file(&file).unwrap();
    assert!(!idx.should_scan(&file).unwrap());

    // modify contents
    std::thread::sleep(std::time::Duration::from_millis(25)); // ensure mtime tick
    std::fs::write(&file, "fn main() { /* changed */ }").unwrap();
    assert!(idx.should_scan(&file).unwrap());
}

#[test]
fn replace_issues_and_query_back() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let file = td.path().join("code.go");
    std::fs::write(&file, "package main").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let fid = idx.upsert_file(&file).unwrap();

    let issues = [
        index::IssueRow {
            rule_id: "X1",
            severity: "High",
            line: 3,
            col: 7,
        },
        index::IssueRow {
            rule_id: "X2",
            severity: "Low",
            line: 4,
            col: 1,
        },
    ];
    idx.replace_issues(fid, issues.clone()).unwrap();

    let stored = idx.get_issues_from_file(&file).unwrap();
    assert_eq!(stored.len(), 2);
    assert!(
        stored
            .iter()
            .any(|d| d.id == "X1" && d.severity == crate::patterns::Severity::High)
    );
    assert!(
        stored
            .iter()
            .any(|d| d.id == "X2" && d.severity == crate::patterns::Severity::Low)
    );
}

#[test]
fn clear_and_vacuum_reset_tables() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("f.rs");
    std::fs::write(&f, "//").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let idx = index::Indexer::from_pool("proj", &pool).unwrap();
    idx.upsert_file(&f).unwrap();

    assert!(!idx.get_files("proj").unwrap().is_empty());
    idx.clear().unwrap();
    idx.vacuum().unwrap();
    assert!(idx.get_files("proj").unwrap().is_empty());
}

#[test]
fn clear_preserves_scan_history_tables() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    let pool = index::Indexer::init(&db).unwrap();
    let idx = index::Indexer::from_pool("_scans", &pool).unwrap();
    idx.insert_scan(&index::ScanRecord {
        id: "scan-1".to_string(),
        status: "completed".to_string(),
        scan_root: td.path().display().to_string(),
        started_at: Some("2026-03-25T12:00:00Z".to_string()),
        finished_at: Some("2026-03-25T12:00:01Z".to_string()),
        duration_secs: Some(1.0),
        engine_version: Some("test".to_string()),
        languages: None,
        files_scanned: Some(1),
        files_skipped: Some(0),
        finding_count: Some(0),
        findings_json: Some("[]".to_string()),
        timing_json: None,
        error: None,
    })
    .unwrap();

    let proj_idx = index::Indexer::from_pool("proj", &pool).unwrap();
    proj_idx.clear().unwrap();

    let loaded = idx
        .get_scan("scan-1")
        .unwrap()
        .expect("scan history should survive index clears");
    assert_eq!(loaded.status, "completed");
}

#[test]
fn ssa_summaries_round_trip() {
    use crate::labels::Cap;
    use crate::summary::ssa_summary::{SsaFuncSummary, TaintTransform};

    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("app.py");
    std::fs::write(&f, "def process(data): return data").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();

    let hash = index::Indexer::digest_bytes(b"def process(data): return data");
    let summaries = vec![
        (
            "process".to_string(),
            1_usize,
            "python".to_string(),
            "app.py".to_string(),
            String::new(),
            None,
            crate::symbol::FuncKind::Function,
            SsaFuncSummary {
                param_to_return: vec![(0, TaintTransform::Identity)],
                param_to_sink: vec![],
                source_caps: Cap::empty(),
                param_to_sink_param: vec![],
                param_container_to_return: vec![],
                param_to_container_store: vec![],
                return_type: None,
                return_abstract: None,
                source_to_callback: vec![],

                receiver_to_return: None,

                receiver_to_sink: Cap::empty(),

                abstract_transfer: vec![],
                param_return_paths: vec![],
                points_to: Default::default(),
                field_points_to: Default::default(),
                return_path_facts: smallvec::SmallVec::new(),
                typed_call_receivers: vec![],
                validated_params_to_return: smallvec::SmallVec::new(),
                param_to_gate_filters: vec![],
            },
        ),
        (
            "sanitize".to_string(),
            1_usize,
            "python".to_string(),
            "app.py".to_string(),
            String::new(),
            None,
            crate::symbol::FuncKind::Function,
            SsaFuncSummary {
                param_to_return: vec![(0, TaintTransform::StripBits(Cap::HTML_ESCAPE))],
                param_to_sink: vec![(
                    0,
                    smallvec::smallvec![crate::summary::SinkSite::cap_only(Cap::SQL_QUERY)],
                )],
                source_caps: Cap::ENV_VAR,
                param_to_sink_param: vec![],
                param_container_to_return: vec![],
                param_to_container_store: vec![],
                return_type: None,
                return_abstract: None,
                source_to_callback: vec![],

                receiver_to_return: None,

                receiver_to_sink: Cap::empty(),

                abstract_transfer: vec![],
                param_return_paths: vec![],
                points_to: Default::default(),
                field_points_to: Default::default(),
                return_path_facts: smallvec::SmallVec::new(),
                typed_call_receivers: vec![],
                validated_params_to_return: smallvec::SmallVec::new(),
                param_to_gate_filters: vec![],
            },
        ),
    ];

    idx.replace_ssa_summaries_for_file(&f, &hash, &summaries)
        .unwrap();

    let loaded = idx.load_all_ssa_summaries().unwrap();
    assert_eq!(loaded.len(), 2);

    // Check first summary
    let (_, name1, lang1, arity1, ns1, _, _, _, sum1) = loaded
        .iter()
        .find(|(_, n, _, _, _, _, _, _, _)| n == "process")
        .unwrap();
    assert_eq!(name1, "process");
    assert_eq!(lang1, "python");
    assert_eq!(*arity1, 1);
    assert_eq!(ns1, "app.py");
    assert_eq!(sum1.param_to_return, vec![(0, TaintTransform::Identity)]);
    assert!(sum1.param_to_sink.is_empty());

    // Check second summary
    let (_, name2, _, _, _, _, _, _, sum2) = loaded
        .iter()
        .find(|(_, n, _, _, _, _, _, _, _)| n == "sanitize")
        .unwrap();
    assert_eq!(name2, "sanitize");
    assert_eq!(
        sum2.param_to_return,
        vec![(0, TaintTransform::StripBits(Cap::HTML_ESCAPE))]
    );
    assert_eq!(sum2.param_to_sink_caps(), vec![(0, Cap::SQL_QUERY)]);
    assert_eq!(sum2.source_caps, Cap::ENV_VAR);
}

/// Round-trip test for [`crate::summary::ssa_summary::PathFactReturnEntry`]:
/// asserts that `return_path_facts` survive serialise → SQLite persist →
/// load → deserialise.  Regression guard for the per-return-path PathFact
/// decomposition that closes the rs-safe-014 / tar-rs / rs-safe-016 FP
/// cluster, without this round-trip working, cross-file callers lose
/// the per-arm narrowing and inline-only callees regain the joined-fact
/// dilution.
#[test]
fn ssa_summaries_round_trip_preserves_return_path_facts() {
    use crate::abstract_interp::PathFact;
    use crate::summary::ssa_summary::{PathFactReturnEntry, SsaFuncSummary, TaintTransform};
    use smallvec::smallvec;

    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("sanitize.rs");
    std::fs::write(&f, "// sanitizer body").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();

    let hash = index::Indexer::digest_bytes(b"// sanitizer body");
    let return_path_facts = smallvec![
        PathFactReturnEntry {
            predicate_hash: 0,
            known_true: 0,
            known_false: 0,
            path_fact: PathFact::top(),
            variant_inner_fact: None,
        },
        PathFactReturnEntry {
            predicate_hash: 17,
            known_true: 0,
            known_false: 0,
            path_fact: PathFact::top(),
            variant_inner_fact: Some(
                PathFact::top()
                    .with_dotdot_cleared()
                    .with_absolute_cleared(),
            ),
        },
    ];
    let summary = SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        return_path_facts: return_path_facts.clone(),
        ..Default::default()
    };
    let row = (
        "sanitize_path".to_string(),
        1_usize,
        "rust".to_string(),
        "sanitize.rs".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        summary,
    );

    idx.replace_ssa_summaries_for_file(&f, &hash, &[row])
        .unwrap();

    let loaded = idx.load_all_ssa_summaries().unwrap();
    assert_eq!(loaded.len(), 1);
    let (_, name, _, _, _, _, _, _, sum) = &loaded[0];
    assert_eq!(name, "sanitize_path");
    assert_eq!(
        sum.return_path_facts.len(),
        2,
        "two distinct return paths must round-trip"
    );
    // Find each entry by predicate hash so order doesn't matter.
    let none_arm = sum
        .return_path_facts
        .iter()
        .find(|e| e.predicate_hash == 0)
        .expect("unguarded entry");
    assert!(none_arm.path_fact.is_top());
    assert!(none_arm.variant_inner_fact.is_none());
    let some_arm = sum
        .return_path_facts
        .iter()
        .find(|e| e.predicate_hash == 17)
        .expect("guarded entry");
    let inner = some_arm
        .variant_inner_fact
        .as_ref()
        .expect("inner fact survives round-trip");
    assert!(
        inner.is_path_safe(),
        "Some arm's inner fact stays path-safe"
    );
}

#[test]
fn ssa_summaries_hash_rescan_replaces_stale() {
    use crate::labels::Cap;
    use crate::summary::ssa_summary::{SsaFuncSummary, TaintTransform};

    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("lib.py");
    std::fs::write(&f, "v1").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();

    let hash_v1 = index::Indexer::digest_bytes(b"v1");
    let sums_v1 = vec![(
        "old_func".to_string(),
        1_usize,
        "python".to_string(),
        "lib.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        SsaFuncSummary {
            param_to_return: vec![(0, TaintTransform::Identity)],
            param_to_sink: vec![],
            source_caps: Cap::empty(),
            param_to_sink_param: vec![],
            param_container_to_return: vec![],
            param_to_container_store: vec![],
            return_type: None,
            return_abstract: None,
            source_to_callback: vec![],

            receiver_to_return: None,

            receiver_to_sink: Cap::empty(),

            abstract_transfer: vec![],
            param_return_paths: vec![],
            points_to: Default::default(),
            field_points_to: Default::default(),
            return_path_facts: smallvec::SmallVec::new(),
            typed_call_receivers: vec![],
            validated_params_to_return: smallvec::SmallVec::new(),
            param_to_gate_filters: vec![],
        },
    )];
    idx.replace_ssa_summaries_for_file(&f, &hash_v1, &sums_v1)
        .unwrap();

    // Simulate file change: different function, different hash
    let hash_v2 = index::Indexer::digest_bytes(b"v2");
    let sums_v2 = vec![(
        "new_func".to_string(),
        2_usize,
        "python".to_string(),
        "lib.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        SsaFuncSummary {
            param_to_return: vec![(0, TaintTransform::StripBits(Cap::SHELL_ESCAPE))],
            param_to_sink: vec![],
            source_caps: Cap::empty(),
            param_to_sink_param: vec![],
            param_container_to_return: vec![],
            param_to_container_store: vec![],
            return_type: None,
            return_abstract: None,
            source_to_callback: vec![],

            receiver_to_return: None,

            receiver_to_sink: Cap::empty(),

            abstract_transfer: vec![],
            param_return_paths: vec![],
            points_to: Default::default(),
            field_points_to: Default::default(),
            return_path_facts: smallvec::SmallVec::new(),
            typed_call_receivers: vec![],
            validated_params_to_return: smallvec::SmallVec::new(),
            param_to_gate_filters: vec![],
        },
    )];
    idx.replace_ssa_summaries_for_file(&f, &hash_v2, &sums_v2)
        .unwrap();

    let loaded = idx.load_all_ssa_summaries().unwrap();
    assert_eq!(
        loaded.len(),
        1,
        "old summary should be replaced, not duplicated"
    );
    assert_eq!(loaded[0].1, "new_func");
}

#[test]
fn clear_drops_ssa_summaries_table() {
    use crate::labels::Cap;
    use crate::summary::ssa_summary::{SsaFuncSummary, TaintTransform};

    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("test.py");
    std::fs::write(&f, "x").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();

    let hash = index::Indexer::digest_bytes(b"x");
    let sums = vec![(
        "f".to_string(),
        1_usize,
        "python".to_string(),
        "test.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        SsaFuncSummary {
            param_to_return: vec![(0, TaintTransform::Identity)],
            param_to_sink: vec![],
            source_caps: Cap::empty(),
            param_to_sink_param: vec![],
            param_container_to_return: vec![],
            param_to_container_store: vec![],
            return_type: None,
            return_abstract: None,
            source_to_callback: vec![],

            receiver_to_return: None,

            receiver_to_sink: Cap::empty(),

            abstract_transfer: vec![],
            param_return_paths: vec![],
            points_to: Default::default(),
            field_points_to: Default::default(),
            return_path_facts: smallvec::SmallVec::new(),
            typed_call_receivers: vec![],
            validated_params_to_return: smallvec::SmallVec::new(),
            param_to_gate_filters: vec![],
        },
    )];
    idx.replace_ssa_summaries_for_file(&f, &hash, &sums)
        .unwrap();
    assert_eq!(idx.load_all_ssa_summaries().unwrap().len(), 1);

    idx.clear().unwrap();
    assert_eq!(idx.load_all_ssa_summaries().unwrap().len(), 0);
}

// ── CalleeSsaBody persistence tests ──────────────────────────────────────

/// Helper: build a minimal CalleeSsaBody for DB tests.
#[allow(dead_code)] // used by tests below
fn make_test_callee_body(
    num_blocks: usize,
    param_count: usize,
) -> crate::taint::ssa_transfer::CalleeSsaBody {
    use crate::ssa::ir::*;
    use smallvec::smallvec;

    let mut blocks = Vec::new();
    for i in 0..num_blocks {
        blocks.push(SsaBlock {
            id: BlockId(i as u32),
            phis: vec![],
            body: vec![SsaInst {
                value: SsaValue(i as u32),
                op: SsaOp::Const(Some(format!("{i}"))),
                cfg_node: petgraph::graph::NodeIndex::new(0),
                var_name: None,
                span: (0, 0),
            }],
            terminator: Terminator::Return(Some(SsaValue(0))),
            preds: smallvec![],
            succs: smallvec![],
        });
    }

    let value_defs: Vec<ValueDef> = (0..num_blocks)
        .map(|i| ValueDef {
            var_name: None,
            cfg_node: petgraph::graph::NodeIndex::new(0),
            block: BlockId(i as u32),
        })
        .collect();

    crate::taint::ssa_transfer::CalleeSsaBody {
        ssa: SsaBody {
            blocks,
            entry: BlockId(0),
            value_defs,
            cfg_node_map: std::collections::HashMap::new(),
            exception_edges: vec![],
            field_interner: crate::ssa::ir::FieldInterner::new(),
            field_writes: std::collections::HashMap::new(),
            synthetic_externals: std::collections::HashSet::new(),
        },
        opt: crate::ssa::OptimizeResult {
            const_values: std::collections::HashMap::new(),
            type_facts: crate::ssa::type_facts::TypeFactResult {
                facts: std::collections::HashMap::new(),
            },
            alias_result: crate::ssa::alias::BaseAliasResult::empty(),
            points_to: crate::ssa::heap::PointsToResult::empty(),
            module_aliases: std::collections::HashMap::new(),
            branches_pruned: 0,
            copies_eliminated: 0,
            dead_defs_removed: 0,
        },
        param_count,
        node_meta: std::collections::HashMap::new(),
        body_graph: None,
    }
}

#[test]
fn ssa_bodies_round_trip() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("helper.py");
    std::fs::write(&f, "def transform(val): return val").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let hash = index::Indexer::digest_bytes(b"def transform(val): return val");

    let body = make_test_callee_body(3, 1);
    let bodies = vec![(
        "transform".to_string(),
        1_usize,
        "python".to_string(),
        "helper.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        body,
    )];

    idx.replace_ssa_bodies_for_file(&f, &hash, &bodies).unwrap();

    let loaded = idx.load_all_ssa_bodies().unwrap();
    assert_eq!(loaded.len(), 1);

    let (fp, name, lang, arity, ns, _, _, _, loaded_body) = &loaded[0];
    assert_eq!(fp, &f.to_string_lossy().to_string());
    assert_eq!(name, "transform");
    assert_eq!(lang, "python");
    assert_eq!(*arity, 1);
    assert_eq!(ns, "helper.py");
    assert_eq!(loaded_body.param_count, 1);
    assert_eq!(loaded_body.ssa.blocks.len(), 3);
}

#[test]
fn ssa_bodies_replace_on_rescan() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("helper.py");
    std::fs::write(&f, "v1").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();

    // Store v1 with 2 blocks
    let hash1 = index::Indexer::digest_bytes(b"v1");
    let bodies1 = vec![(
        "func".to_string(),
        1_usize,
        "python".to_string(),
        "h.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_callee_body(2, 1),
    )];
    idx.replace_ssa_bodies_for_file(&f, &hash1, &bodies1)
        .unwrap();
    assert_eq!(idx.load_all_ssa_bodies().unwrap().len(), 1);
    assert_eq!(idx.load_all_ssa_bodies().unwrap()[0].8.ssa.blocks.len(), 2);

    // Store v2 with 5 blocks, should replace, not accumulate
    let hash2 = index::Indexer::digest_bytes(b"v2");
    let bodies2 = vec![(
        "func".to_string(),
        1_usize,
        "python".to_string(),
        "h.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_callee_body(5, 1),
    )];
    idx.replace_ssa_bodies_for_file(&f, &hash2, &bodies2)
        .unwrap();

    let loaded = idx.load_all_ssa_bodies().unwrap();
    assert_eq!(loaded.len(), 1, "should replace, not accumulate");
    assert_eq!(loaded[0].8.ssa.blocks.len(), 5);
}

#[test]
fn ssa_bodies_with_node_meta_round_trip() {
    use crate::cfg::{NodeInfo, TaintMeta};
    use crate::labels::{Cap, DataLabel};
    use crate::taint::ssa_transfer::CrossFileNodeMeta;

    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("helper.py");
    std::fs::write(&f, "code").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let hash = index::Indexer::digest_bytes(b"code");

    let mut body = make_test_callee_body(1, 0);
    body.node_meta.insert(
        0,
        CrossFileNodeMeta {
            info: NodeInfo {
                bin_op: Some(crate::cfg::BinOp::Add),
                taint: TaintMeta {
                    labels: smallvec::smallvec![DataLabel::Sink(Cap::SQL_QUERY)],
                    ..Default::default()
                },
                ..Default::default()
            },
        },
    );

    let bodies = vec![(
        "f".to_string(),
        0_usize,
        "python".to_string(),
        "h.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        body,
    )];
    idx.replace_ssa_bodies_for_file(&f, &hash, &bodies).unwrap();

    let loaded = idx.load_all_ssa_bodies().unwrap();
    assert_eq!(loaded.len(), 1);

    let meta = &loaded[0].8.node_meta;
    assert_eq!(meta.len(), 1);
    assert_eq!(meta[&0].info.bin_op, Some(crate::cfg::BinOp::Add));
    assert!(matches!(meta[&0].info.taint.labels[0], DataLabel::Sink(cap) if cap == Cap::SQL_QUERY));
}

#[test]
fn ssa_bodies_removed_on_file_delete() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("helper.py");
    std::fs::write(&f, "code").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let hash = index::Indexer::digest_bytes(b"code");

    // Register file first so remove_file_and_related has something to find
    idx.upsert_file(&f).unwrap();

    let bodies = vec![(
        "f".to_string(),
        0_usize,
        "python".to_string(),
        "h.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_callee_body(1, 0),
    )];
    idx.replace_ssa_bodies_for_file(&f, &hash, &bodies).unwrap();
    assert_eq!(idx.load_all_ssa_bodies().unwrap().len(), 1);

    // Delete file, should also remove bodies
    idx.remove_file_and_related(&f).unwrap();
    assert_eq!(idx.load_all_ssa_bodies().unwrap().len(), 0);
}

// ── Persistence hardening tests ─────────────────────────────────────────────

/// Helper: build a minimal SsaFuncSummary for persistence tests.
#[cfg(test)]
fn make_test_ssa_summary() -> crate::summary::ssa_summary::SsaFuncSummary {
    use crate::labels::Cap;
    use crate::summary::ssa_summary::{SsaFuncSummary, TaintTransform};
    SsaFuncSummary {
        param_to_return: vec![(0, TaintTransform::Identity)],
        param_to_sink: vec![],
        source_caps: Cap::empty(),
        param_to_sink_param: vec![],
        param_container_to_return: vec![],
        param_to_container_store: vec![],
        return_type: None,
        return_abstract: None,
        source_to_callback: vec![],

        receiver_to_return: None,

        receiver_to_sink: Cap::empty(),

        abstract_transfer: vec![],
        param_return_paths: vec![],
        points_to: Default::default(),
        field_points_to: Default::default(),
        return_path_facts: smallvec::SmallVec::new(),
        typed_call_receivers: vec![],
        validated_params_to_return: smallvec::SmallVec::new(),
        param_to_gate_filters: vec![],
    }
}

/// Helper: insert a fake summary + SSA summary + file row for a project.
#[cfg(test)]
fn populate_project(
    pool: &r2d2::Pool<r2d2_sqlite::SqliteConnectionManager>,
    project: &str,
    dir: &std::path::Path,
) {
    let f = dir.join("app.py");
    std::fs::write(&f, "# code").unwrap();

    let mut idx = index::Indexer::from_pool(project, pool).unwrap();
    idx.upsert_file(&f).unwrap();

    let hash = index::Indexer::digest_bytes(b"# code");

    // Insert a FuncSummary
    let func_summary = crate::summary::FuncSummary {
        name: "do_stuff".to_string(),
        file_path: f.to_string_lossy().to_string(),
        param_count: 1,
        param_names: vec!["data".to_string()],
        lang: "python".to_string(),
        source_caps: 0,
        sanitizer_caps: 0,
        sink_caps: 0,
        propagating_params: vec![0],
        propagates_taint: true,
        tainted_sink_params: vec![],
        callees: vec![],
        ..Default::default()
    };
    idx.replace_summaries_for_file(&f, &hash, &[func_summary])
        .unwrap();

    // Insert an SSA summary
    let ssa_sums = vec![(
        "do_stuff".to_string(),
        1_usize,
        "python".to_string(),
        "app.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    idx.replace_ssa_summaries_for_file(&f, &hash, &ssa_sums)
        .unwrap();

    // Insert an SSA body
    let bodies = vec![(
        "do_stuff".to_string(),
        1_usize,
        "python".to_string(),
        "app.py".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_callee_body(1, 1),
    )];
    idx.replace_ssa_bodies_for_file(&f, &hash, &bodies).unwrap();
}

// ── 1. Engine Version Tests ─────────────────────────────────────────────────

#[test]
fn version_match_no_reset() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // First init: creates DB and sets version
    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "proj", td.path());

    // Verify data exists
    assert_eq!(
        index::Indexer::count_rows(&pool, "function_summaries", "proj").unwrap(),
        1
    );
    assert_eq!(
        index::Indexer::count_rows(&pool, "ssa_function_summaries", "proj").unwrap(),
        1
    );
    assert_eq!(
        index::Indexer::count_rows(&pool, "ssa_function_bodies", "proj").unwrap(),
        1
    );

    // Second init with same version: data should be preserved
    drop(pool);
    let pool2 = index::Indexer::init(&db).unwrap();

    assert_eq!(
        index::Indexer::count_rows(&pool2, "function_summaries", "proj").unwrap(),
        1
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_summaries", "proj").unwrap(),
        1
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_bodies", "proj").unwrap(),
        1
    );

    let stored = index::Indexer::get_stored_engine_version(&pool2).unwrap();
    assert_eq!(stored.as_deref(), Some(index::ENGINE_VERSION));
}

#[test]
fn version_mismatch_triggers_reset() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // First init
    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "proj", td.path());

    // Simulate an old version
    index::Indexer::set_engine_version(&pool, "0.0.1-old").unwrap();

    // Verify data is populated
    assert_eq!(
        index::Indexer::count_rows(&pool, "function_summaries", "proj").unwrap(),
        1
    );

    // Reopen, version mismatch should trigger full wipe
    drop(pool);
    let pool2 = index::Indexer::init(&db).unwrap();

    assert_eq!(
        index::Indexer::count_rows(&pool2, "function_summaries", "proj").unwrap(),
        0
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_summaries", "proj").unwrap(),
        0
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_bodies", "proj").unwrap(),
        0
    );

    // files table should also be cleared (forces rescan)
    let idx = index::Indexer::from_pool("proj", &pool2).unwrap();
    assert!(idx.get_files("proj").unwrap().is_empty());

    // Version should now be updated
    let stored = index::Indexer::get_stored_engine_version(&pool2).unwrap();
    assert_eq!(stored.as_deref(), Some(index::ENGINE_VERSION));
}

#[test]
fn missing_version_triggers_reset() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // Init the DB
    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "proj", td.path());

    // Remove the metadata row to simulate a pre-version DB
    {
        let conn = pool.get().unwrap();
        conn.execute("DELETE FROM nyx_metadata WHERE key = 'engine_version'", [])
            .unwrap();
    }

    // Reopen
    drop(pool);
    let pool2 = index::Indexer::init(&db).unwrap();

    // All caches should be wiped
    assert_eq!(
        index::Indexer::count_rows(&pool2, "function_summaries", "proj").unwrap(),
        0
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_summaries", "proj").unwrap(),
        0
    );

    // Version should now be set
    let stored = index::Indexer::get_stored_engine_version(&pool2).unwrap();
    assert_eq!(stored.as_deref(), Some(index::ENGINE_VERSION));
}

#[test]
fn multiple_opens_no_repeated_resets() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // First open
    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "proj", td.path());
    drop(pool);

    // Second open, should preserve data
    let pool2 = index::Indexer::init(&db).unwrap();
    assert_eq!(
        index::Indexer::count_rows(&pool2, "function_summaries", "proj").unwrap(),
        1
    );

    // Re-populate after second open
    populate_project(&pool2, "proj2", td.path());
    drop(pool2);

    // Third open, should still preserve both projects
    let pool3 = index::Indexer::init(&db).unwrap();
    assert_eq!(
        index::Indexer::count_rows(&pool3, "function_summaries", "proj").unwrap(),
        1
    );
    assert_eq!(
        index::Indexer::count_rows(&pool3, "function_summaries", "proj2").unwrap(),
        1
    );
}

#[test]
fn write_engine_version_on_scan_completion() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    let pool = index::Indexer::init(&db).unwrap();

    // Simulate writing version after scan
    index::Indexer::write_engine_version(&pool).unwrap();

    let stored = index::Indexer::get_stored_engine_version(&pool).unwrap();
    assert_eq!(stored.as_deref(), Some(index::ENGINE_VERSION));
}

// ── 2. Migration Tests ──────────────────────────────────────────────────────

#[test]
fn fresh_db_no_migration_needed() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // Should not panic and tables should exist
    let pool = index::Indexer::init(&db).unwrap();
    let idx = index::Indexer::from_pool("proj", &pool).unwrap();

    // Verify tables are accessible
    assert!(idx.load_all_summaries().unwrap().is_empty());
    assert!(idx.load_all_ssa_summaries().unwrap().is_empty());
    assert!(idx.load_all_ssa_bodies().unwrap().is_empty());
    assert!(idx.get_files("proj").unwrap().is_empty());
}

#[test]
fn missing_ssa_namespace_column_triggers_recreate() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // Create DB with an outdated SSA table (no namespace column)
    {
        let conn = rusqlite::Connection::open(&db).unwrap();
        conn.execute_batch(
            "CREATE TABLE IF NOT EXISTS files (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                project TEXT NOT NULL, path TEXT NOT NULL,
                hash BLOB NOT NULL, mtime INTEGER NOT NULL,
                scanned_at INTEGER NOT NULL, UNIQUE(project, path)
            );
            CREATE TABLE IF NOT EXISTS function_summaries (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                project TEXT NOT NULL, file_path TEXT NOT NULL,
                file_hash BLOB NOT NULL, name TEXT NOT NULL,
                arity INTEGER NOT NULL DEFAULT -1, lang TEXT NOT NULL,
                summary TEXT NOT NULL, updated_at INTEGER NOT NULL,
                UNIQUE(project, file_path, name, arity)
            );
            CREATE TABLE IF NOT EXISTS ssa_function_summaries (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                project TEXT NOT NULL, file_path TEXT NOT NULL,
                file_hash BLOB NOT NULL, name TEXT NOT NULL,
                arity INTEGER NOT NULL DEFAULT -1, lang TEXT NOT NULL,
                summary TEXT NOT NULL, updated_at INTEGER NOT NULL,
                UNIQUE(project, file_path, name, arity)
            );",
        )
        .unwrap();
    }

    // Open via init, should detect missing namespace and recreate
    let pool = index::Indexer::init(&db).unwrap();

    // Verify the table now has the namespace column by inserting with it
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let f = td.path().join("test.py");
    std::fs::write(&f, "x").unwrap();
    let hash = index::Indexer::digest_bytes(b"x");
    let sums = vec![(
        "func".to_string(),
        1_usize,
        "python".to_string(),
        "ns".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    // This would fail if the namespace column doesn't exist
    idx.replace_ssa_summaries_for_file(&f, &hash, &sums)
        .unwrap();
    assert_eq!(idx.load_all_ssa_summaries().unwrap().len(), 1);
}

#[test]
fn valid_schema_no_recreate() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // First init, creates all tables
    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "proj", td.path());
    drop(pool);

    // Second init, schema is valid, should NOT drop/recreate
    let pool2 = index::Indexer::init(&db).unwrap();
    // Data survives because schema was already correct
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_summaries", "proj").unwrap(),
        1
    );
}

// ── 3. Deserialization Failure Tests ────────────────────────────────────────

#[test]
fn invalid_json_skipped_in_load_summaries() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let pool = index::Indexer::init(&db).unwrap();

    // Insert corrupted JSON directly
    {
        let conn = pool.get().unwrap();
        conn.execute(
            "INSERT INTO function_summaries (project, file_path, file_hash, name, arity, lang, summary, updated_at)
             VALUES ('proj', 'bad.py', X'00', 'bad', 1, 'python', '{not valid json!!!', 0)",
            [],
        ).unwrap();
    }

    let idx = index::Indexer::from_pool("proj", &pool).unwrap();
    // Should not panic; invalid row is skipped
    let loaded = idx.load_all_summaries().unwrap();
    assert_eq!(loaded.len(), 0);
}

#[test]
fn invalid_json_skipped_in_load_ssa_summaries() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let pool = index::Indexer::init(&db).unwrap();

    // Insert corrupted JSON directly
    {
        let conn = pool.get().unwrap();
        conn.execute(
            "INSERT INTO ssa_function_summaries (project, file_path, file_hash, name, arity, lang, namespace, summary, updated_at)
             VALUES ('proj', 'bad.py', X'00', 'bad', 1, 'python', '', 'CORRUPTED', 0)",
            [],
        ).unwrap();
    }

    let idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let loaded = idx.load_all_ssa_summaries().unwrap();
    assert_eq!(loaded.len(), 0);
}

#[test]
fn invalid_json_skipped_in_load_ssa_bodies() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let pool = index::Indexer::init(&db).unwrap();

    {
        let conn = pool.get().unwrap();
        conn.execute(
            "INSERT INTO ssa_function_bodies (project, file_path, file_hash, name, arity, lang, namespace, body, updated_at)
             VALUES ('proj', 'bad.py', X'00', 'bad', 1, 'python', '', '{{{{broken', 0)",
            [],
        ).unwrap();
    }

    let idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let loaded = idx.load_all_ssa_bodies().unwrap();
    assert_eq!(loaded.len(), 0);
}

#[test]
fn partial_failure_does_not_drop_valid_rows() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let pool = index::Indexer::init(&db).unwrap();

    // Insert one valid SSA summary via the normal API
    let f = td.path().join("good.py");
    std::fs::write(&f, "ok").unwrap();
    let hash = index::Indexer::digest_bytes(b"ok");
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();
    let sums = vec![(
        "good_func".to_string(),
        1_usize,
        "python".to_string(),
        "".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    idx.replace_ssa_summaries_for_file(&f, &hash, &sums)
        .unwrap();

    // Insert a corrupted row directly
    {
        let conn = pool.get().unwrap();
        conn.execute(
            "INSERT INTO ssa_function_summaries (project, file_path, file_hash, name, arity, lang, namespace, summary, updated_at)
             VALUES ('proj', 'bad.py', X'00', 'bad_func', 1, 'python', '', 'NOT_JSON', 0)",
            [],
        ).unwrap();
    }

    // Load: should get exactly the 1 valid row
    let loaded = idx.load_all_ssa_summaries().unwrap();
    assert_eq!(loaded.len(), 1);
    assert_eq!(loaded[0].1, "good_func");
}

// ── 4. Integration / Round-Trip Tests ───────────────────────────────────────

#[test]
fn scan_persist_reload_cycle() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "myproject", td.path());

    // Write version as scan completion would
    index::Indexer::write_engine_version(&pool).unwrap();

    // Reload from a fresh pool
    drop(pool);
    let pool2 = index::Indexer::init(&db).unwrap();

    let idx = index::Indexer::from_pool("myproject", &pool2).unwrap();
    assert_eq!(idx.load_all_summaries().unwrap().len(), 1);
    assert_eq!(idx.load_all_ssa_summaries().unwrap().len(), 1);
    assert_eq!(idx.load_all_ssa_bodies().unwrap().len(), 1);
    assert_eq!(idx.get_files("myproject").unwrap().len(), 1);
}

#[test]
fn version_bump_forces_reindex_behavior() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    // Simulate a previous engine version
    let pool = index::Indexer::init(&db).unwrap();
    populate_project(&pool, "proj", td.path());
    index::Indexer::set_engine_version(&pool, "0.1.0-alpha").unwrap();
    drop(pool);

    // Reopen: version bump should force full invalidation
    let pool2 = index::Indexer::init(&db).unwrap();

    // Everything should be wiped
    let idx = index::Indexer::from_pool("proj", &pool2).unwrap();
    assert!(idx.load_all_summaries().unwrap().is_empty());
    assert!(idx.load_all_ssa_summaries().unwrap().is_empty());
    assert!(idx.load_all_ssa_bodies().unwrap().is_empty());
    assert!(idx.get_files("proj").unwrap().is_empty());

    // After wiping, we can re-populate and it persists
    populate_project(&pool2, "proj", td.path());
    assert_eq!(idx.load_all_summaries().unwrap().len(), 1);
}

// ── 5. Edge Cases ───────────────────────────────────────────────────────────

#[test]
fn empty_db_file_works() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("empty.sqlite");

    // Create empty file
    std::fs::write(&db, "").unwrap();

    // init should handle this (SQLite will overwrite the empty file)
    let pool = index::Indexer::init(&db).unwrap();
    let idx = index::Indexer::from_pool("proj", &pool).unwrap();
    assert!(idx.load_all_summaries().unwrap().is_empty());
}

#[test]
fn multiple_projects_isolated() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    let pool = index::Indexer::init(&db).unwrap();

    // Populate two different projects
    let f1 = td.path().join("proj1_file.py");
    let f2 = td.path().join("proj2_file.py");
    std::fs::write(&f1, "p1").unwrap();
    std::fs::write(&f2, "p2").unwrap();

    let mut idx1 = index::Indexer::from_pool("project_a", &pool).unwrap();
    idx1.upsert_file(&f1).unwrap();
    let hash1 = index::Indexer::digest_bytes(b"p1");
    let sums1 = vec![(
        "func_a".to_string(),
        0_usize,
        "python".to_string(),
        "".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    idx1.replace_ssa_summaries_for_file(&f1, &hash1, &sums1)
        .unwrap();

    let mut idx2 = index::Indexer::from_pool("project_b", &pool).unwrap();
    idx2.upsert_file(&f2).unwrap();
    let hash2 = index::Indexer::digest_bytes(b"p2");
    let sums2 = vec![(
        "func_b".to_string(),
        0_usize,
        "python".to_string(),
        "".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    idx2.replace_ssa_summaries_for_file(&f2, &hash2, &sums2)
        .unwrap();

    // Each project sees only its own summaries
    assert_eq!(idx1.load_all_ssa_summaries().unwrap().len(), 1);
    assert_eq!(idx1.load_all_ssa_summaries().unwrap()[0].1, "func_a");

    assert_eq!(idx2.load_all_ssa_summaries().unwrap().len(), 1);
    assert_eq!(idx2.load_all_ssa_summaries().unwrap()[0].1, "func_b");

    // Files are project-scoped too (get_files queries by its argument)
    assert_eq!(idx1.get_files("project_a").unwrap().len(), 1);
    assert_eq!(idx2.get_files("project_b").unwrap().len(), 1);
    // Cross-project: project_a should have no project_b files
    assert_eq!(idx1.get_files("nonexistent_project").unwrap().len(), 0);
}

#[test]
fn version_reset_wipes_all_projects() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    let pool = index::Indexer::init(&db).unwrap();

    // Populate two projects
    let f1 = td.path().join("a.py");
    let f2 = td.path().join("b.py");
    std::fs::write(&f1, "a").unwrap();
    std::fs::write(&f2, "b").unwrap();

    let mut idx1 = index::Indexer::from_pool("proj_x", &pool).unwrap();
    idx1.upsert_file(&f1).unwrap();
    let hash1 = index::Indexer::digest_bytes(b"a");
    let sums1 = vec![(
        "fx".to_string(),
        0_usize,
        "python".to_string(),
        "".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    idx1.replace_ssa_summaries_for_file(&f1, &hash1, &sums1)
        .unwrap();

    let mut idx2 = index::Indexer::from_pool("proj_y", &pool).unwrap();
    idx2.upsert_file(&f2).unwrap();
    let hash2 = index::Indexer::digest_bytes(b"b");
    let sums2 = vec![(
        "fy".to_string(),
        0_usize,
        "python".to_string(),
        "".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        make_test_ssa_summary(),
    )];
    idx2.replace_ssa_summaries_for_file(&f2, &hash2, &sums2)
        .unwrap();

    // Simulate version mismatch
    index::Indexer::set_engine_version(&pool, "0.0.0-stale").unwrap();
    drop(pool);

    let pool2 = index::Indexer::init(&db).unwrap();

    // Both projects' data should be gone (version check is global, not per-project)
    assert_eq!(
        index::Indexer::count_rows(&pool2, "function_summaries", "proj_x").unwrap(),
        0
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_summaries", "proj_x").unwrap(),
        0
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "function_summaries", "proj_y").unwrap(),
        0
    );
    assert_eq!(
        index::Indexer::count_rows(&pool2, "ssa_function_summaries", "proj_y").unwrap(),
        0
    );
}

#[test]
fn metadata_table_survives_clear() {
    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");

    let pool = index::Indexer::init(&db).unwrap();
    index::Indexer::write_engine_version(&pool).unwrap();

    let idx = index::Indexer::from_pool("proj", &pool).unwrap();
    idx.clear().unwrap();

    // Metadata should survive clear (clear only drops analysis tables)
    let stored = index::Indexer::get_stored_engine_version(&pool).unwrap();
    assert_eq!(stored.as_deref(), Some(index::ENGINE_VERSION));
}

/// field_points_to round-trips through
/// the SsaFuncSummary SQLite blob.  Pin that the new field_points_to
/// records preserve param_field_reads, param_field_writes, the
/// receiver sentinel (`u32::MAX`), the container-element marker
/// (`<elem>`), and the `overflow` flag across serialise → store →
/// load → deserialise.  This is the strict-additive contract for
/// pre-Phase-5 blobs (default-empty deserialises cleanly) and the
/// completeness check for the W3 cross-call resolver.
#[test]
fn ssa_summaries_round_trip_preserves_field_points_to() {
    use crate::summary::points_to::FieldPointsToSummary;
    use crate::summary::ssa_summary::SsaFuncSummary;

    let td = tempfile::tempdir().unwrap();
    let db = td.path().join("nyx.sqlite");
    let f = td.path().join("store.rs");
    std::fs::write(&f, "// helper that writes obj.cache").unwrap();

    let pool = index::Indexer::init(&db).unwrap();
    let mut idx = index::Indexer::from_pool("proj", &pool).unwrap();

    let hash = index::Indexer::digest_bytes(b"// helper that writes obj.cache");

    // Build a summary with one read on param 0 ("name"), one write on
    // param 1 ("cache"), one read on the receiver sentinel ("kind"),
    // and an ELEM marker on param 0.  Round-trip must preserve all
    // four channels.
    let mut fpt = FieldPointsToSummary::empty();
    fpt.add_read(0, "name");
    fpt.add_write(1, "cache");
    fpt.add_read(u32::MAX, "kind");
    fpt.add_write(0, "<elem>");

    let summary = SsaFuncSummary {
        field_points_to: fpt.clone(),
        ..Default::default()
    };
    let row = (
        "store".to_string(),
        2_usize,
        "rust".to_string(),
        "store.rs".to_string(),
        String::new(),
        None,
        crate::symbol::FuncKind::Function,
        summary,
    );
    idx.replace_ssa_summaries_for_file(&f, &hash, &[row])
        .unwrap();

    let loaded = idx.load_all_ssa_summaries().unwrap();
    assert_eq!(loaded.len(), 1, "single summary stored, single returned");
    let (_, name, _, _, _, _, _, _, sum) = &loaded[0];
    assert_eq!(name, "store");
    assert_eq!(
        sum.field_points_to, fpt,
        "field_points_to must round-trip byte-equal",
    );

    // Spot-check sentinel + ELEM marker channels.
    let recv_read = sum
        .field_points_to
        .param_field_reads
        .iter()
        .find(|(p, _)| *p == u32::MAX)
        .expect("receiver read at u32::MAX sentinel");
    assert!(recv_read.1.iter().any(|s| s == "kind"));

    let elem_write = sum
        .field_points_to
        .param_field_writes
        .iter()
        .find(|(p, _)| *p == 0)
        .expect("param 0 writes recorded");
    assert!(
        elem_write.1.iter().any(|s| s == "<elem>"),
        "<elem> marker must survive round-trip without conversion",
    );
    assert!(!sum.field_points_to.overflow);
}

/// Pre-Phase-5 blob compatibility: a summary serialised without
/// `field_points_to` deserialises with the empty default, no
/// migration needed because the field is `#[serde(default)]`.
#[test]
fn ssa_summaries_pre_phase5_blob_decodes_with_empty_field_points_to() {
    use crate::summary::ssa_summary::SsaFuncSummary;

    // Hand-craft JSON without the `field_points_to` key.
    let pre_phase5_json = r#"{
        "param_to_return": [],
        "param_to_sink": [],
        "source_caps": 0,
        "param_to_sink_param": [],
        "param_container_to_return": [],
        "param_to_container_store": [],
        "return_type": null,
        "return_abstract": null,
        "source_to_callback": [],
        "receiver_to_return": null,
        "receiver_to_sink": 0,
        "abstract_transfer": [],
        "param_return_paths": [],
        "return_path_facts": [],
        "typed_call_receivers": []
    }"#;
    let sum: SsaFuncSummary = serde_json::from_str(pre_phase5_json).unwrap();
    assert!(
        sum.field_points_to.is_empty(),
        "missing field_points_to must default to empty",
    );
}

/// Pre-`param_to_gate_filters` blob compatibility: a summary serialised
/// before this field existed deserialises with the empty default.
/// `#[serde(default)]` on the field means old SQLite blobs round-trip
/// without a schema migration, the new field is stored inside the JSON
/// `summary` column so SQL-level columns are unchanged.
#[test]
fn ssa_summaries_pre_gate_filters_blob_decodes_with_empty_param_to_gate_filters() {
    use crate::summary::ssa_summary::SsaFuncSummary;

    // Hand-craft JSON without the `param_to_gate_filters` key.
    let pre_gate_filters_json = r#"{
        "param_to_return": [],
        "param_to_sink": [],
        "source_caps": 0,
        "param_to_sink_param": [],
        "param_container_to_return": [],
        "param_to_container_store": [],
        "return_type": null,
        "return_abstract": null,
        "source_to_callback": [],
        "receiver_to_return": null,
        "receiver_to_sink": 0,
        "abstract_transfer": [],
        "param_return_paths": [],
        "return_path_facts": [],
        "typed_call_receivers": []
    }"#;
    let sum: SsaFuncSummary = serde_json::from_str(pre_gate_filters_json).unwrap();
    assert!(
        sum.param_to_gate_filters.is_empty(),
        "missing param_to_gate_filters must default to empty",
    );
}

/// Round-trip: a summary with a populated `param_to_gate_filters`
/// survives JSON serialise + deserialise, including the per-position
/// cap-mask values needed to preserve SSRF-vs-DATA_EXFIL splits across
/// the function-summary boundary.
#[test]
fn ssa_summaries_param_to_gate_filters_round_trip() {
    use crate::labels::Cap;
    use crate::summary::ssa_summary::SsaFuncSummary;

    let mut sum = SsaFuncSummary::default();
    sum.param_to_gate_filters.push((0, Cap::SSRF));
    sum.param_to_gate_filters.push((1, Cap::DATA_EXFIL));

    let json = serde_json::to_string(&sum).expect("serialize");
    let restored: SsaFuncSummary = serde_json::from_str(&json).expect("deserialize");
    assert_eq!(
        restored.param_to_gate_filters,
        vec![(0, Cap::SSRF), (1, Cap::DATA_EXFIL)],
        "per-position cap masks must round-trip exactly",
    );
}