code-kb-core 1.1.3

Core library for code-kb AST fact querying, slicing, and progressive disclosure
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
use code_kb_core::db::{Connection, open_read_write};
use code_kb_core::queries::*;
use code_kb_core::sync::reconcile_offline_edits;
#[allow(unused_imports)]
use code_kb_core::workspace::{
    Workspace, normalize_path, parse_file_uri, paths_equal, strip_prefix_lossy,
};
use sha2::Digest;
use std::path::{Path, PathBuf};

#[test]
fn test_sync_reconcile_case_mismatch_and_verbatim() {
    let temp = code_kb_core::safe_tempdir();
    let db_path = temp.path().join("test.db");
    let conn = open_read_write(&db_path).unwrap();

    conn.execute_batch(
        "CREATE TABLE files (
            file_id TEXT PRIMARY KEY,
            path TEXT NOT NULL,
            language TEXT,
            content_hash TEXT,
            content_bytes INTEGER,
            line_count INTEGER,
            indexed_at TEXT
        );
        CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL
        );",
    )
    .unwrap();

    let src_dir = temp.path().join("src");
    std::fs::create_dir_all(&src_dir).unwrap();
    let main_file = src_dir.join("main.rs");
    let lib_file = src_dir.join("lib.rs");

    let main_content = "fn main() { println!(\"hello\"); }\n";
    let lib_content = "pub fn add(a: i32, b: i32) -> i32 { a + b }\n";

    std::fs::write(&main_file, main_content).unwrap();
    std::fs::write(&lib_file, lib_content).unwrap();

    let main_hash = hex::encode(sha2::Sha256::digest(main_content.as_bytes()));
    let lib_hash = hex::encode(sha2::Sha256::digest(lib_content.as_bytes()));

    conn.execute(
        "INSERT INTO files VALUES ('f1', 'src/main.rs', 'rust', ?1, ?2, 1, '2026-09-14T00:00:00Z')",
        rusqlite::params![main_hash, main_content.len() as i64],
    )
    .unwrap();
    conn.execute(
        "INSERT INTO files VALUES ('f2', 'src/lib.rs', 'rust', ?1, ?2, 1, '2026-09-14T00:00:00Z')",
        rusqlite::params![lib_hash, lib_content.len() as i64],
    )
    .unwrap();

    // 1. Scenario A: Inverted drive letter casing
    #[allow(unused_mut)]
    let mut ws_cased = Workspace::new(temp.path().to_path_buf());
    #[cfg(windows)]
    {
        let root_str = ws_cased.canonical_root.to_string_lossy().to_string();
        if let Some(first_char) = root_str.chars().next() {
            let flipped = if first_char.is_ascii_uppercase() {
                first_char.to_ascii_lowercase()
            } else {
                first_char.to_ascii_uppercase()
            };
            ws_cased.canonical_root = PathBuf::from(format!("{}{}", flipped, &root_str[1..]));
        }
    }

    let report_cased = reconcile_offline_edits(&ws_cased, &db_path, &conn).unwrap();
    assert!(
        report_cased.deleted.is_empty(),
        "Scenario A (drive case mismatch): Files should not be marked deleted: {:?}",
        report_cased.deleted
    );
    assert!(
        report_cased.modified.is_empty(),
        "Scenario A: Unmodified files should not be marked modified: {:?}",
        report_cased.modified
    );

    // 2. Scenario B: Verbatim prefix on workspace canonical root
    #[allow(unused_mut)]
    let mut ws_verbatim = Workspace::new(temp.path().to_path_buf());
    #[cfg(windows)]
    {
        let root_str = ws_verbatim.canonical_root.to_string_lossy().to_string();
        if !root_str.starts_with(r"\\?\") {
            ws_verbatim.canonical_root = PathBuf::from(format!(r"\\?\{}", root_str));
        }
    }

    let report_verbatim = reconcile_offline_edits(&ws_verbatim, &db_path, &conn).unwrap();
    assert!(
        report_verbatim.deleted.is_empty(),
        "Scenario B (verbatim root): Files should not be marked deleted: {:?}",
        report_verbatim.deleted
    );
    assert!(
        report_verbatim.modified.is_empty(),
        "Scenario B: Files should not be marked modified: {:?}",
        report_verbatim.modified
    );

    // 3. Scenario C: Trailing slash on canonical root
    let mut ws_trailing = Workspace::new(temp.path().to_path_buf());
    let trailing_str = format!("{}/", ws_trailing.canonical_root.to_string_lossy());
    ws_trailing.canonical_root = PathBuf::from(trailing_str);

    let report_trailing = reconcile_offline_edits(&ws_trailing, &db_path, &conn).unwrap();
    assert!(
        report_trailing.deleted.is_empty(),
        "Scenario C (trailing slash): Files should not be marked deleted: {:?}",
        report_trailing.deleted
    );

    // 4. Scenario D: Real edit on disk with drive case mismatch
    let new_lib_content = "pub fn add(a: i32, b: i32) -> i32 { a + b + 1 }\n";
    std::fs::write(&lib_file, new_lib_content).unwrap();

    let report_edit = reconcile_offline_edits(&ws_cased, &db_path, &conn).unwrap();
    assert_eq!(
        report_edit.modified,
        vec!["src/lib.rs".to_string()],
        "Scenario D: Edited file must be detected as modified even with drive casing mismatch"
    );
    assert!(
        report_edit.deleted.is_empty(),
        "Scenario D: No files should be deleted"
    );
}

#[test]
fn test_queries_collate_nocase_exact_lookups() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE files (
            file_id TEXT PRIMARY KEY,
            path TEXT NOT NULL,
            language TEXT,
            content_hash TEXT,
            content_bytes INTEGER,
            line_count INTEGER,
            indexed_at TEXT
        );
        CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        -- Insert with backslashes and camel-casing
        INSERT INTO files VALUES ('f1', 'src\\Services\\PaymentService.rs', 'rust', 'hash1', 200, 20, '2026-09-14T00:00:00Z');
        INSERT INTO symbols VALUES (
            's1', 'f1', 'src\\Services\\PaymentService.rs', 'rust', 'ProcessPayment', 'function',
            'pub fn ProcessPayment(amount: u64)', 'Processes incoming payment', 'pub', NULL,
            1, 0, 10, 0, 0, 200, 2, 4, 9, 1, 35, 195, 'bhash_proc', 'function', 0, 0
        );",
    )
    .unwrap();

    // 1. get_file with mixed cases and slashes
    let query_variations = [
        "src/Services/PaymentService.rs",
        "SRC/SERVICES/PAYMENTSERVICE.RS",
        "src/services/paymentservice.rs",
        "src\\services\\paymentservice.rs",
        "SRC\\SERVICES\\PAYMENTSERVICE.RS",
    ];

    for q in &query_variations {
        let f = get_file(&conn, q)
            .unwrap()
            .unwrap_or_else(|| panic!("get_file failed for query: {}", q));
        assert_eq!(
            f.path, "src/Services/PaymentService.rs",
            "Path must be strictly normalized to forward slashes for query: {}",
            q
        );
    }

    // 2. load_file_symbols with mixed cases and slashes
    for q in &query_variations {
        let syms = load_file_symbols(&conn, q).unwrap();
        assert_eq!(syms.len(), 1, "load_file_symbols failed for query: {}", q);
        assert_eq!(syms[0].name, "ProcessPayment");
        assert_eq!(
            syms[0].path, "src/Services/PaymentService.rs",
            "Symbol path must be strictly normalized to forward slashes for query: {}",
            q
        );
    }

    // 3. get_symbol_by_name with exact full-path filters
    let full_path_filters = [
        Some("SRC/SERVICES/PAYMENTSERVICE.RS"),
        Some("src/services/paymentservice.rs"),
        Some("src\\Services\\PaymentService.rs"),
    ];

    for pf in &full_path_filters {
        let sym = get_symbol_by_name(&conn, "ProcessPayment", *pf)
            .unwrap()
            .unwrap_or_else(|| panic!("get_symbol_by_name failed for filter: {:?}", pf));
        assert_eq!(sym.name, "ProcessPayment");
        assert_eq!(sym.path, "src/Services/PaymentService.rs");
    }

    // 4. get_symbol_by_name_exact with full path filters
    let exact_filters = [
        "src/Services/PaymentService.rs",
        "SRC/SERVICES/PAYMENTSERVICE.RS",
        "src/services/paymentservice.rs",
        "src\\services\\paymentservice.rs",
    ];

    for ef in &exact_filters {
        let sym = get_symbol_by_name_exact(&conn, "ProcessPayment", ef)
            .unwrap()
            .unwrap_or_else(|| panic!("get_symbol_by_name_exact failed for filter: {}", ef));
        assert_eq!(sym.name, "ProcessPayment");
        assert_eq!(sym.path, "src/Services/PaymentService.rs");
    }
}

#[test]
fn test_forward_slash_invariants_across_internal_models() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE files (
            file_id TEXT PRIMARY KEY,
            path TEXT NOT NULL,
            language TEXT,
            content_hash TEXT,
            content_bytes INTEGER,
            line_count INTEGER,
            indexed_at TEXT
        );
        CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        CREATE TABLE relationships (
            relationship_id TEXT PRIMARY KEY,
            from_symbol_id TEXT,
            to_symbol_id TEXT,
            kind TEXT,
            path TEXT,
            start_line INTEGER,
            start_column INTEGER
        );
        CREATE TABLE pending_relationships (
            from_symbol_id TEXT,
            target_terminal_name TEXT,
            kind TEXT,
            path TEXT,
            start_line INTEGER,
            start_column INTEGER
        );
        CREATE TABLE structural_facts (
            structural_fact_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            pattern_id TEXT,
            capture_name TEXT,
            node_kind TEXT,
            containing_symbol_id TEXT,
            start_line INTEGER,
            end_line INTEGER,
            confidence REAL,
            metadata_json TEXT
        );
        CREATE TABLE literals (
            literal_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            kind TEXT,
            literal_text TEXT,
            carrier TEXT,
            containing_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER
        );

        -- Insert all data using Windows backslashes
        INSERT INTO files VALUES ('f1', 'src\\models\\user.rs', 'rust', 'h1', 100, 10, '2026-09-14');
        INSERT INTO symbols VALUES (
            's1', 'f1', 'src\\models\\user.rs', 'rust', 'User', 'struct',
            'pub struct User', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 100,
            1, 0, 5, 0, 0, 100, 'hash1', 'struct', 0, 0
        );
        INSERT INTO symbols VALUES (
            's2', 'f1', 'src\\models\\user.rs', 'rust', 'save_user', 'function',
            'pub fn save_user()', NULL, 'pub', NULL, 6, 0, 10, 0, 101, 200,
            6, 0, 10, 0, 101, 200, 'hash2', 'function', 0, 0
        );
        INSERT INTO relationships VALUES ('r1', 's2', 's1', 'constructs', 'src\\models\\user.rs', 7, 4);
        INSERT INTO structural_facts VALUES (
            'fact1', 'f1', 'src\\models\\user.rs', 'rust', 'route', 'route',
            'endpoint', 's2', 6, 6, 1.0, NULL
        );
        INSERT INTO literals VALUES (
            'lit1', 'f1', 'src\\models\\user.rs', 'rust', 'string',
            'user_table', 'carrier1', 's2', 8, 14, 8, 24, 150, 160
        );",
    )
    .unwrap();

    // 1. load_scoped_files
    let files = load_scoped_files(&conn, None).unwrap();
    for f in files {
        assert!(
            !f.path.contains('\\'),
            "FileFact path contains backslash: {}",
            f.path
        );
    }

    // 2. find_references (callers)
    let callers = find_references(&conn, "User", "callers", 10).unwrap();
    for r in callers {
        assert!(
            !r.path.contains('\\'),
            "ReferenceSite path contains backslash: {}",
            r.path
        );
    }

    // 3. find_callee_signatures (internal only)
    let callee_sigs = find_callee_signatures(&conn, "save_user", "s2", 10, false).unwrap();
    for entry in callee_sigs {
        assert!(
            !entry.contains('\\'),
            "Callee signature contains backslash: {}",
            entry
        );
    }

    // 4. find_structural_facts
    let facts = find_structural_facts(&conn, "%", 10).unwrap();
    for fact in facts {
        assert!(
            !fact.path.contains('\\'),
            "StructuralFact path contains backslash: {}",
            fact.path
        );
    }

    // 5. find_literals
    let lits = find_literals(&conn, "%", 10).unwrap();
    for lit in lits {
        assert!(
            !lit.path.contains('\\'),
            "LiteralFact path contains backslash: {}",
            lit.path
        );
    }

    // 6. compute_blast_radius
    let blast = compute_blast_radius(&conn, &["User"], &[], 2, 10).unwrap();
    for sym in blast.impacted_symbols {
        assert!(
            !sym.path.contains('\\'),
            "ImpactedSymbol path contains backslash: {}",
            sym.path
        );
    }
    for test in blast.likely_tests {
        assert!(
            !test.path.contains('\\'),
            "TestTarget path contains backslash: {}",
            test.path
        );
    }
}

#[test]
fn test_paths_equal_adversarial_stress() {
    assert!(paths_equal(
        Path::new("src/lib.rs"),
        Path::new("src/lib.rs")
    ));
    assert!(paths_equal(
        Path::new("src/lib.rs"),
        Path::new("src\\lib.rs")
    ));
    assert!(!paths_equal(
        Path::new("src/lib.rs"),
        Path::new("src/main.rs")
    ));

    #[cfg(windows)]
    {
        // 1. Casing variations
        assert!(paths_equal(
            Path::new(r"C:\source\code-kb\src\lib.rs"),
            Path::new(r"c:\source\code-kb\src\lib.rs")
        ));
        assert!(paths_equal(
            Path::new(r"C:\Source\Code-Kb\Src\Lib.rs"),
            Path::new(r"c:\source\code-kb\src\lib.rs")
        ));

        // 2. Trailing slashes
        assert!(paths_equal(
            Path::new(r"C:\source\code-kb\"),
            Path::new(r"c:\source\code-kb")
        ));
        assert!(paths_equal(
            Path::new(r"C:/source/code-kb/"),
            Path::new(r"c:\source\code-kb")
        ));

        // 3. Verbatim prefixes vs standard
        assert!(paths_equal(
            Path::new(r"\\?\C:\source\code-kb\src\lib.rs"),
            Path::new(r"C:\source\code-kb\src\lib.rs")
        ));
        assert!(paths_equal(
            Path::new(r"\\?\c:\source\code-kb\src\lib.rs"),
            Path::new(r"C:\source\code-kb\src\lib.rs")
        ));

        // 4. Verbatim with mixed slashes
        assert!(paths_equal(
            Path::new(r"\\?\C:/source/code-kb/src/lib.rs"),
            Path::new(r"c:\source\code-kb\src\lib.rs")
        ));

        // 5. Different drive letters must NOT match
        assert!(!paths_equal(
            Path::new(r"C:\source\code-kb\src\lib.rs"),
            Path::new(r"D:\source\code-kb\src\lib.rs")
        ));

        // 6. Prefix path vs longer path must NOT match
        assert!(!paths_equal(
            Path::new(r"C:\source\code-kb"),
            Path::new(r"C:\source\code-kb\src")
        ));

        // 7. UNC paths
        assert!(paths_equal(
            Path::new(r"\\server\share\file.txt"),
            Path::new(r"\\SERVER\SHARE\file.txt")
        ));
    }
}

#[test]
fn test_parse_file_uri_standard_variations() {
    #[cfg(windows)]
    {
        // Two-slash
        let p1 = parse_file_uri("file://C:/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p1,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        // Three-slash
        let p2 = parse_file_uri("file:///C:/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p2,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        // Lowercase drive letter
        let p3 = parse_file_uri("file://c:/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p3,
            normalize_path(Path::new(r"c:\projects\code-kb\src\lib.rs"))
        );

        // Percent-encoded spaces
        let p4 = parse_file_uri("file:///C:/My%20Projects/Code%20KB/lib.rs").unwrap();
        assert_eq!(
            p4,
            normalize_path(Path::new(r"C:\My Projects\Code KB\lib.rs"))
        );

        let p5 = parse_file_uri("file://C:/My%20Projects/Code%20KB/lib.rs").unwrap();
        assert_eq!(
            p5,
            normalize_path(Path::new(r"C:\My Projects\Code KB\lib.rs"))
        );
    }
}

#[test]
fn test_strip_prefix_lossy_adversarial_stress() {
    #[cfg(windows)]
    {
        // 1. Verbatim path vs plain base
        let path = Path::new(r"\\?\C:\repo\src\main.rs");
        let base = Path::new(r"C:\repo");
        let rel = strip_prefix_lossy(path, base).expect("Must strip prefix with verbatim path");
        assert_eq!(
            code_kb_core::workspace::to_forward_slash(rel),
            "src/main.rs"
        );

        // 2. Plain path vs verbatim base
        let path = Path::new(r"C:\repo\src\main.rs");
        let base = Path::new(r"\\?\C:\repo");
        let rel = strip_prefix_lossy(path, base).expect("Must strip prefix with verbatim base");
        assert_eq!(
            code_kb_core::workspace::to_forward_slash(rel),
            "src/main.rs"
        );

        // 3. Drive casing difference
        let path = Path::new(r"c:\repo\src\main.rs");
        let base = Path::new(r"C:\repo");
        let rel =
            strip_prefix_lossy(path, base).expect("Must strip prefix with drive casing difference");
        assert_eq!(
            code_kb_core::workspace::to_forward_slash(rel),
            "src/main.rs"
        );

        // 4. Directory casing difference
        let path = Path::new(r"C:\REPO\src\main.rs");
        let base = Path::new(r"C:\repo");
        let rel = strip_prefix_lossy(path, base)
            .expect("Must strip prefix with directory casing difference");
        assert_eq!(
            code_kb_core::workspace::to_forward_slash(rel),
            "src/main.rs"
        );

        // 5. Trailing slash on base
        let path = Path::new(r"C:\repo\src\main.rs");
        let base = Path::new(r"C:\repo\");
        let rel =
            strip_prefix_lossy(path, base).expect("Must strip prefix with trailing slash on base");
        assert_eq!(
            code_kb_core::workspace::to_forward_slash(rel),
            "src/main.rs"
        );

        // 6. Forward slashes in base
        let path = Path::new(r"C:\repo\src\main.rs");
        let base = Path::new("C:/repo");
        let rel =
            strip_prefix_lossy(path, base).expect("Must strip prefix with forward slashes in base");
        assert_eq!(
            code_kb_core::workspace::to_forward_slash(rel),
            "src/main.rs"
        );

        // 7. Different drives must return None
        let path = Path::new(r"D:\repo\src\main.rs");
        let base = Path::new(r"C:\repo");
        assert!(strip_prefix_lossy(path, base).is_none());

        // 8. Path shorter than base must return None
        let path = Path::new(r"C:\repo");
        let base = Path::new(r"C:\repo\src");
        assert!(strip_prefix_lossy(path, base).is_none());
    }
}

// ------------------------------------------------------------------------------------------------
// EMPIRICAL BUG REPRODUCTIONS & REMEDIATION VERIFICATIONS
// The following 4 tests verify remediation of specific bugs discovered during adversarial stress testing.
// ------------------------------------------------------------------------------------------------

/// Bug 1 Remediation: `find_callee_signatures` emits forward slashes for external callees
/// even when `pending_relationships.path` contains Windows backslashes.
#[test]
fn test_bug_repro_find_callee_signatures_external_path_backslash() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        CREATE TABLE relationships (
            relationship_id TEXT PRIMARY KEY,
            from_symbol_id TEXT,
            to_symbol_id TEXT,
            kind TEXT,
            path TEXT,
            start_line INTEGER,
            start_column INTEGER
        );
        CREATE TABLE pending_relationships (
            from_symbol_id TEXT,
            target_terminal_name TEXT,
            kind TEXT,
            path TEXT,
            start_line INTEGER,
            start_column INTEGER
        );
        INSERT INTO symbols VALUES (
            's1', 'f1', 'src\\models\\user.rs', 'rust', 'save_user', 'function',
            'pub fn save_user()', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'hash1', 'function', 0, 0
        );
        -- Insert pending external callee with Windows backslashes in path
        INSERT INTO pending_relationships VALUES ('s1', 'db_insert', 'call', 'src\\models\\user.rs', 8, 4);",
    )
    .unwrap();

    let callee_sigs = find_callee_signatures(&conn, "save_user", "s1", 10, true).unwrap();
    assert_eq!(callee_sigs.len(), 1);
    assert!(
        !callee_sigs[0].contains('\\'),
        "External callee signature must strictly format paths with forward slashes: {}",
        callee_sigs[0]
    );
    assert_eq!(
        callee_sigs[0], "db_insert (src/models/user.rs:8)",
        "External callee signature path must match expected forward slash string"
    );
}

/// Bug 2 Remediation: `get_symbol_by_name` partial/suffix path filter succeeds when SQLite has backslashes
/// using both forward-slash and backslash patterns with literal backslash matching.
#[test]
fn test_bug_repro_get_symbol_by_name_suffix_filter_with_backslash_db() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        -- Insert with backslashes
        INSERT INTO symbols VALUES (
            's1', 'f1', 'src\\Services\\PaymentService.rs', 'rust', 'ProcessPayment', 'function',
            'pub fn ProcessPayment()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'hash1', 'function', 0, 0
        );",
    )
    .unwrap();

    // 1. Filename suffix filter "PaymentService.rs"
    let sym = get_symbol_by_name(&conn, "ProcessPayment", Some("PaymentService.rs")).unwrap();
    assert!(
        sym.is_some(),
        "Suffix filter must find symbol when DB contains backslashes"
    );
    let s = sym.unwrap();
    assert_eq!(s.name, "ProcessPayment");
    assert_eq!(s.path, "src/Services/PaymentService.rs");

    // 2. Multi-segment suffix filter with forward slash
    let sym2 =
        get_symbol_by_name(&conn, "ProcessPayment", Some("Services/PaymentService.rs")).unwrap();
    assert!(
        sym2.is_some(),
        "Multi-segment forward slash suffix filter must find symbol when DB contains backslashes"
    );

    // 3. Multi-segment suffix filter with backslash
    let sym3 =
        get_symbol_by_name(&conn, "ProcessPayment", Some(r"Services\PaymentService.rs")).unwrap();
    assert!(
        sym3.is_some(),
        "Multi-segment backslash suffix filter must find symbol when DB contains backslashes"
    );

    // 4. Case-insensitive suffix filter
    let sym4 = get_symbol_by_name(&conn, "ProcessPayment", Some("paymentservice.rs")).unwrap();
    assert!(
        sym4.is_some(),
        "Case-insensitive suffix filter must find symbol when DB contains backslashes"
    );

    // 5. Negative boundary test: ensure substring without path separator does not match
    let sym5 = get_symbol_by_name(&conn, "ProcessPayment", Some("FooPaymentService.rs")).unwrap();
    assert!(
        sym5.is_none(),
        "Substring match without path separator must not match"
    );
}

/// Bug 3 Remediation: `load_scoped_files` and `load_scoped_outline_symbols` match case-insensitively
/// and support both forward-slash and backslash paths with dual-separator depth bounding.
#[test]
fn test_bug_repro_load_scoped_files_case_insensitivity() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE files (
            file_id TEXT PRIMARY KEY,
            path TEXT NOT NULL,
            language TEXT,
            content_hash TEXT,
            content_bytes INTEGER,
            line_count INTEGER,
            indexed_at TEXT
        );
        CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        -- Insert forward slash file
        INSERT INTO files VALUES ('f1', 'src/Services/PaymentService.rs', 'rust', 'h1', 100, 10, '2026-09-14');
        -- Insert backslash file
        INSERT INTO files VALUES ('f2', 'src\\Services\\OtherService.rs', 'rust', 'h2', 150, 15, '2026-09-14');
        INSERT INTO symbols VALUES (
            's1', 'f1', 'src/Services/PaymentService.rs', 'rust', 'process', 'function',
            'pub fn process()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh1', 'function', 0, 0
        );
        INSERT INTO symbols VALUES (
            's2', 'f2', 'src\\Services\\OtherService.rs', 'rust', 'other', 'function',
            'pub fn other()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh2', 'function', 0, 0
        );",
    )
    .unwrap();

    // 1. Exact path lookup with uppercase
    let files = load_scoped_files(&conn, Some("SRC/SERVICES/PAYMENTSERVICE.RS")).unwrap();
    assert_eq!(
        files.len(),
        1,
        "load_scoped_files must find uppercase forward slash file"
    );
    assert_eq!(files[0].path, "src/Services/PaymentService.rs");

    // 2. Exact backslash path lookup with uppercase
    let files_bs = load_scoped_files(&conn, Some("SRC\\SERVICES\\OTHERSERVICE.RS")).unwrap();
    assert_eq!(
        files_bs.len(),
        1,
        "load_scoped_files must find uppercase backslash file"
    );
    assert_eq!(files_bs[0].path, "src/Services/OtherService.rs");

    // 3. Directory scope with mixed case and forward slash
    let scoped_fwd = load_scoped_files(&conn, Some("SRC/SERVICES")).unwrap();
    assert_eq!(
        scoped_fwd.len(),
        2,
        "Directory scope with forward slash must find both files"
    );

    // 4. Directory scope with mixed case and backslash
    let scoped_bs = load_scoped_files(&conn, Some("src\\services")).unwrap();
    assert_eq!(
        scoped_bs.len(),
        2,
        "Directory scope with backslash must find both files"
    );

    // 5. Scoped outline symbols
    let syms = load_scoped_outline_symbols(&conn, Some("SRC/SERVICES"), 2, 5).unwrap();
    assert_eq!(
        syms.len(),
        2,
        "Scoped outline symbols must find symbols for both files"
    );
    assert!(syms.contains_key("src/Services/PaymentService.rs"));
    assert!(syms.contains_key("src/Services/OtherService.rs"));

    // 6. End-to-end codebase_outline_op with case-insensitive scope and backslashes
    let ws = Workspace::new(PathBuf::from(r"C:\test_repo"));
    let outline_dir =
        code_kb_core::codebase_outline_op(&ws, &conn, 3, Some("SRC/SERVICES")).unwrap();
    assert!(
        outline_dir.contains("PaymentService.rs"),
        "Outline must contain PaymentService.rs: {}",
        outline_dir
    );
    assert!(
        outline_dir.contains("OtherService.rs"),
        "Outline must contain OtherService.rs: {}",
        outline_dir
    );

    let outline_file =
        code_kb_core::codebase_outline_op(&ws, &conn, 3, Some("SRC/SERVICES/PAYMENTSERVICE.RS"))
            .unwrap();
    assert!(
        outline_file.contains("PaymentService.rs"),
        "Outline for single file must contain PaymentService.rs: {}",
        outline_file
    );
}

/// Bug 4 Remediation: `parse_file_uri` converts pipe character `|` into a valid drive colon `:`
#[test]
fn test_bug_repro_parse_file_uri_pipe_character() {
    #[cfg(windows)]
    {
        // 1. Three-slash uppercase
        let p1 = parse_file_uri("file:///C|/projects/code-kb/src/lib.rs").unwrap();
        assert!(
            !p1.to_string_lossy().contains('|'),
            "parse_file_uri emitted invalid path containing pipe character: {:?}",
            p1
        );
        assert_eq!(
            p1,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        // 2. Two-slash uppercase
        let p2 = parse_file_uri("file://C|/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p2,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        // 3. Lowercase drive with pipe
        let p3 = parse_file_uri("file:///c|/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p3,
            normalize_path(Path::new(r"c:\projects\code-kb\src\lib.rs"))
        );

        // 4. Percent-encoded pipe %7C and %7c
        let p4 = parse_file_uri("file:///C%7C/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p4,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        let p5 = parse_file_uri("file://C%7c/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p5,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        // 5. Plain path with pipe
        let p6 = parse_file_uri("C|/projects/code-kb/src/lib.rs").unwrap();
        assert_eq!(
            p6,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );

        // 6. Mixed backslashes with pipe
        let p7 = parse_file_uri(r"file:///C|\projects\code-kb\src\lib.rs").unwrap();
        assert_eq!(
            p7,
            normalize_path(Path::new(r"C:\projects\code-kb\src\lib.rs"))
        );
    }
}

/// Adversarial Stress Test: Defect 3 Scoped outline queries, depth limits, and mixed slash/casing combinations.
#[test]
fn test_adversarial_stress_scoped_outline_and_depth_limits() {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE files (
            file_id TEXT PRIMARY KEY,
            path TEXT NOT NULL,
            language TEXT,
            content_hash TEXT,
            content_bytes INTEGER,
            line_count INTEGER,
            indexed_at TEXT
        );
        CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        -- Root files (depth 0 relative to root)
        INSERT INTO files VALUES ('f0_1', 'Cargo.toml', 'toml', 'h0_1', 50, 5, '2026-09-14');
        INSERT INTO files VALUES ('f0_2', 'README.md', 'markdown', 'h0_2', 100, 10, '2026-09-14');
        -- Level 1 files (1 separator)
        INSERT INTO files VALUES ('f1_1', 'src/lib.rs', 'rust', 'h1_1', 120, 12, '2026-09-14');
        INSERT INTO files VALUES ('f1_2', 'src\\main.rs', 'rust', 'h1_2', 130, 13, '2026-09-14');
        -- Level 2 files (2 separators, mixed slashes and mixed casing)
        INSERT INTO files VALUES ('f2_1', 'src/Services/AuthService.rs', 'rust', 'h2_1', 200, 20, '2026-09-14');
        INSERT INTO files VALUES ('f2_2', 'src\\Services\\PaymentService.rs', 'rust', 'h2_2', 210, 21, '2026-09-14');
        INSERT INTO files VALUES ('f2_3', 'src/models\\User.rs', 'rust', 'h2_3', 220, 22, '2026-09-14');
        -- Level 3 files (3 separators)
        INSERT INTO files VALUES ('f3_1', 'src\\Services\\Auth\\Token.rs', 'rust', 'h3_1', 300, 30, '2026-09-14');
        INSERT INTO files VALUES ('f3_2', 'src/Services/Auth/Session.rs', 'rust', 'h3_2', 310, 31, '2026-09-14');
        -- Level 4 file (4 separators)
        INSERT INTO files VALUES ('f4_1', 'src\\Services\\Auth\\Crypto\\Keys.rs', 'rust', 'h4_1', 400, 40, '2026-09-14');
        -- Special directory characters to stress escape_like: '_' vs '-' and '%'
        INSERT INTO files VALUES ('f_spec1', 'special_dir/alpha.rs', 'rust', 'h_s1', 50, 5, '2026-09-14');
        INSERT INTO files VALUES ('f_spec2', 'special-dir/beta.rs', 'rust', 'h_s2', 50, 5, '2026-09-14');
        INSERT INTO files VALUES ('f_spec3', 'special%20dir/gamma.rs', 'rust', 'h_s3', 50, 5, '2026-09-14');

        -- Symbols corresponding to files
        INSERT INTO symbols VALUES ('s0_1', 'f0_1', 'Cargo.toml', 'toml', 'package', 'struct', 'package', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh0_1', 'struct', 0, 0);
        INSERT INTO symbols VALUES ('s1_1', 'f1_1', 'src/lib.rs', 'rust', 'lib_init', 'function', 'pub fn lib_init()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh1_1', 'function', 0, 0);
        INSERT INTO symbols VALUES ('s1_2', 'f1_2', 'src\\main.rs', 'rust', 'main', 'function', 'fn main()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh1_2', 'function', 0, 0);
        INSERT INTO symbols VALUES ('s2_1', 'f2_1', 'src/Services/AuthService.rs', 'rust', 'login', 'function', 'pub fn login()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh2_1', 'function', 0, 0);
        INSERT INTO symbols VALUES ('s2_2', 'f2_2', 'src\\Services\\PaymentService.rs', 'rust', 'pay', 'function', 'pub fn pay()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh2_2', 'function', 0, 0);
        INSERT INTO symbols VALUES ('s3_1', 'f3_1', 'src\\Services\\Auth\\Token.rs', 'rust', 'validate_token', 'function', 'pub fn validate_token()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh3_1', 'function', 0, 0);
        INSERT INTO symbols VALUES ('s4_1', 'f4_1', 'src\\Services\\Auth\\Crypto\\Keys.rs', 'rust', 'generate_key', 'function', 'pub fn generate_key()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh4_1', 'function', 0, 0);
        INSERT INTO symbols VALUES ('s_sp1', 'f_spec1', 'special_dir/alpha.rs', 'rust', 'alpha_fn', 'function', 'pub fn alpha_fn()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50, 1, 0, 5, 0, 0, 50, 'bh_sp1', 'function', 0, 0);
        ",
    ).unwrap();

    let ws = Workspace::new(PathBuf::from(r"C:\test_project"));

    // 1. Root-level outline depth tests
    // depth 1: Only files with 0 slashes (Cargo.toml, README.md)
    let syms_d1 = load_scoped_outline_symbols(&conn, None, 1, 5).unwrap();
    assert!(syms_d1.contains_key("Cargo.toml"));
    assert!(!syms_d1.contains_key("src/lib.rs"));
    assert!(!syms_d1.contains_key("src/main.rs"));

    // depth 2: Root files and files with 1 slash
    let syms_d2 = load_scoped_outline_symbols(&conn, None, 2, 5).unwrap();
    assert!(syms_d2.contains_key("Cargo.toml"));
    assert!(syms_d2.contains_key("src/lib.rs"));
    assert!(syms_d2.contains_key("src/main.rs")); // backslash row normalized to forward slash
    assert!(!syms_d2.contains_key("src/Services/AuthService.rs"));

    // 2. Scoped outline depth tests under "src/Services"
    let filter_cases = [
        "src/Services",
        "SRC/SERVICES",
        r"src\Services",
        r"SRC\SERVICES",
        "src/Services/",
        r"src\Services\",
    ];

    for filter in &filter_cases {
        // Scope depth 1: only immediate children (AuthService.rs, PaymentService.rs)
        let syms_scoped_d1 = load_scoped_outline_symbols(&conn, Some(*filter), 1, 5).unwrap();
        assert!(
            syms_scoped_d1.contains_key("src/Services/AuthService.rs"),
            "Filter {} depth 1 must contain AuthService",
            filter
        );
        assert!(
            syms_scoped_d1.contains_key("src/Services/PaymentService.rs"),
            "Filter {} depth 1 must contain PaymentService",
            filter
        );
        assert!(
            !syms_scoped_d1.contains_key("src/Services/Auth/Token.rs"),
            "Filter {} depth 1 must NOT contain Token.rs",
            filter
        );
        assert!(
            !syms_scoped_d1.contains_key("src/Services/Auth/Crypto/Keys.rs"),
            "Filter {} depth 1 must NOT contain Keys.rs",
            filter
        );

        // Scope depth 2: includes Token.rs and Session.rs
        let syms_scoped_d2 = load_scoped_outline_symbols(&conn, Some(*filter), 2, 5).unwrap();
        assert!(syms_scoped_d2.contains_key("src/Services/AuthService.rs"));
        assert!(syms_scoped_d2.contains_key("src/Services/PaymentService.rs"));
        assert!(syms_scoped_d2.contains_key("src/Services/Auth/Token.rs"));
        assert!(
            !syms_scoped_d2.contains_key("src/Services/Auth/Crypto/Keys.rs"),
            "Filter {} depth 2 must NOT contain Keys.rs",
            filter
        );

        // Scope depth 3: includes Keys.rs
        let syms_scoped_d3 = load_scoped_outline_symbols(&conn, Some(*filter), 3, 5).unwrap();
        assert!(syms_scoped_d3.contains_key("src/Services/Auth/Crypto/Keys.rs"));

        // End-to-end codebase_outline_op verification
        let outline = code_kb_core::codebase_outline_op(&ws, &conn, 1, Some(*filter)).unwrap();
        assert!(
            outline.contains("AuthService.rs"),
            "Outline must contain AuthService.rs: {}",
            outline
        );
        assert!(
            outline.contains("PaymentService.rs"),
            "Outline must contain PaymentService.rs: {}",
            outline
        );
        assert!(
            outline.contains("login"),
            "Outline must contain symbol login: {}",
            outline
        );
        assert!(
            outline.contains("pay"),
            "Outline must contain symbol pay: {}",
            outline
        );
        assert!(
            !outline.contains("generate_key"),
            "Outline depth 1 must not contain generate_key: {}",
            outline
        );
    }

    // 3. Stress-testing LIKE wildcard escaping with underscore and percent
    let underscore_files = load_scoped_files(&conn, Some("special_dir")).unwrap();
    assert_eq!(underscore_files.len(), 1);
    assert_eq!(underscore_files[0].path, "special_dir/alpha.rs");

    let dash_files = load_scoped_files(&conn, Some("special-dir")).unwrap();
    assert_eq!(dash_files.len(), 1);
    assert_eq!(dash_files[0].path, "special-dir/beta.rs");

    let percent_files = load_scoped_files(&conn, Some("special%20dir")).unwrap();
    assert_eq!(percent_files.len(), 1);
    assert_eq!(percent_files[0].path, "special%20dir/gamma.rs");

    // 4. Non-existent filter returns OpError::FileNotFound
    let missing_err =
        code_kb_core::codebase_outline_op(&ws, &conn, 2, Some("nonexistent/dir")).unwrap_err();
    match missing_err {
        code_kb_core::ops::OpError::FileNotFound(f) => assert_eq!(f, "nonexistent/dir"),
        other => panic!("Expected FileNotFound, got {:?}", other),
    }
}

/// Adversarial Stress Test: Defect 4 Comprehensive matrix for file URI pipe normalization.
#[test]
fn test_adversarial_stress_parse_file_uri_comprehensive_matrix() {
    #[cfg(windows)]
    {
        // 1. Drive roots with trailing slash
        let valid_roots = [
            ("file:///C|/", r"C:\"),
            ("file://C|/", r"C:\"),
            ("C|/", r"C:\"),
            ("C|\\", r"C:\"),
        ];
        for (uri, expected) in &valid_roots {
            let res =
                parse_file_uri(uri).unwrap_or_else(|| panic!("Failed to parse root URI: {}", uri));
            assert!(
                !res.to_string_lossy().contains('|'),
                "Result for '{}' contains pipe: {:?}",
                uri,
                res
            );
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for '{}'",
                uri
            );
        }

        // Defect 4.1 Remediation: parse_file_uri handles drive roots without trailing slashes
        // without panicking in url::Url::to_file_path().
        let root_no_slash_cases = [
            ("file:///C|", r"C:\"),
            ("file://C|", r"C:\"),
            ("file:///c|", r"c:\"),
            ("file://c|", r"c:\"),
            ("file:///C:", r"C:\"),
            ("file://C:", r"C:\"),
            ("file:///c:", r"c:\"),
            ("file://c:", r"c:\"),
            ("file:///C%7C", r"C:\"),
            ("file://C%7c", r"C:\"),
            ("file:///C%3A", r"C:\"),
            ("file://c%3a", r"c:\"),
            ("file:///C|?query=foo", r"C:\"),
            ("file:///C|#anchor", r"C:\"),
            ("file://localhost/C|", r"C:\"),
            ("file://localhost/C|/", r"C:\"),
            ("file://localhost/c|", r"c:\"),
            ("file://LOCALHOST/C|", r"C:\"),
        ];
        for (uri, expected) in &root_no_slash_cases {
            let panic_res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(
                panic_res.is_ok(),
                "Expected parse_file_uri('{}') NOT to panic",
                uri
            );
            let res = panic_res
                .unwrap()
                .unwrap_or_else(|| panic!("Expected parse_file_uri('{}') to return Some", uri));
            assert!(
                !res.to_string_lossy().contains('|'),
                "Result for '{}' contains invalid pipe: {:?}",
                uri,
                res
            );
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for '{}'",
                uri
            );
        }

        // Defect 4.2 Remediation: file://localhost with pipe delimiter normalizes cleanly without retaining pipe
        let localhost_pipe_cases = [
            ("file://localhost/C|/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://localhost/c|/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://LOCALHOST/C|/path/to/file.rs", r"C:\path\to\file.rs"),
            (
                r"file://localhost\C|\path\to\file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file:///localhost/C|/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
        ];
        for (uri, expected) in &localhost_pipe_cases {
            let res =
                parse_file_uri(uri).unwrap_or_else(|| panic!("Failed for localhost URI: {}", uri));
            assert!(
                !res.to_string_lossy().contains('|'),
                "Expected file://localhost pipe URI '{}' to normalize without pipe: {:?}",
                uri,
                res
            );
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for '{}'",
                uri
            );
        }

        // 2. Drive letter casing and variety (D, e, Z, y)
        let drives = [
            ("file:///D|/path/to/file.rs", r"D:\path\to\file.rs"),
            ("file://d|/path/to/file.rs", r"d:\path\to\file.rs"),
            ("file:///Z|/deep/dir/mod.rs", r"Z:\deep\dir\mod.rs"),
            ("file://y|/deep/dir/mod.rs", r"y:\deep\dir\mod.rs"),
            ("D|/path/to/file.rs", r"D:\path\to\file.rs"),
            ("d|\\path\\to\\file.rs", r"d:\path\to\file.rs"),
        ];
        for (uri, expected) in &drives {
            let res = parse_file_uri(uri).unwrap_or_else(|| panic!("Failed for {}", uri));
            assert!(!res.to_string_lossy().contains('|'));
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }

        // 3. Percent-encoded colon (%3A and %3a)
        let percent_colons = [
            ("file:///C%3A/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file:///c%3a/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://C%3A/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://c%3a/path/to/file.rs", r"c:\path\to\file.rs"),
        ];
        for (uri, expected) in &percent_colons {
            let res = parse_file_uri(uri).unwrap_or_else(|| panic!("Failed for {}", uri));
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }

        // 4. URL query strings and fragments with pipes
        let query_and_frag = [
            (
                "file:///C|/folder/file.rs?query=param",
                r"C:\folder\file.rs",
            ),
            ("file:///C|/folder/file.rs#L42", r"C:\folder\file.rs"),
            ("file://C|/folder/file.rs?foo=bar#baz", r"C:\folder\file.rs"),
        ];
        for (uri, expected) in &query_and_frag {
            let res = parse_file_uri(uri).unwrap_or_else(|| panic!("Failed for {}", uri));
            assert!(!res.to_string_lossy().contains('|'));
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }

        // 5. Encoded spaces combined with pipe
        let spaces = [
            (
                "file:///C|/Program%20Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                "file://C|/Program%20Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                "file:///C%7C/Program%20Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                "file://C%7c/Program%20Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
        ];
        for (uri, expected) in &spaces {
            let res = parse_file_uri(uri).unwrap_or_else(|| panic!("Failed for {}", uri));
            assert!(!res.to_string_lossy().contains('|'));
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }

        // 6. Mixed forward/backward slashes with pipe
        let mixed = [
            (
                r"file:///C|\Program Files/App\file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                r"file://C|\Program Files/App\file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                r"C|\Program Files/App\file.rs",
                r"C:\Program Files\App\file.rs",
            ),
        ];
        for (uri, expected) in &mixed {
            let res = parse_file_uri(uri).unwrap_or_else(|| panic!("Failed for {}", uri));
            assert!(!res.to_string_lossy().contains('|'));
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }
    }
}

/// Adversarial Boundary & Fuzz Test for Defect 4.1 and 4.2
#[test]
fn test_adversarial_stress_defect4_boundary_cases() {
    #[cfg(windows)]
    {
        // 1. Localhost variations with colon, pipe, encoded, and backslashes
        let localhost_cases = [
            ("file://localhost/C:", r"C:\"),
            ("file://localhost/c:", r"c:\"),
            ("file://localhost/C:/", r"C:\"),
            ("file://LOCALHOST/C:/", r"C:\"),
            ("file://localhost/C:/path/to/file.rs", r"C:\path\to\file.rs"),
            (
                r"file://localhost\C:\path\to\file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file:///localhost/C:/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file://localhost/C%7C/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file://localhost/C%3A/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
            ("file://localhost/C%7C", r"C:\"),
            ("file://localhost/C%3A", r"C:\"),
            ("file://localhost/C|?query=foo#anchor", r"C:\"),
            ("file://localhost/C:?query=foo#anchor", r"C:\"),
            ("file://localhost/C|/dir/subdir/", r"C:\dir\subdir"),
            ("file://localhost/C:/dir/subdir/", r"C:\dir\subdir"),
        ];
        for (uri, expected) in &localhost_cases {
            let panic_res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(panic_res.is_ok(), "URI panicked: {}", uri);
            let res = panic_res
                .unwrap()
                .unwrap_or_else(|| panic!("Returned None for {}", uri));
            assert!(
                !res.to_string_lossy().contains('|'),
                "Contains pipe for {}: {:?}",
                uri,
                res
            );
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }

        // 2. Query and fragment edge cases on drive roots without trailing slash
        let root_query_frag_cases = [
            ("file:///C:?", r"C:\"),
            ("file:///C:#", r"C:\"),
            ("file:///C:?#", r"C:\"),
            ("file:///C|?", r"C:\"),
            ("file:///C|#", r"C:\"),
            ("file:///C|?#", r"C:\"),
            ("file://C:?", r"C:\"),
            ("file://C:#", r"C:\"),
            ("file://C|?", r"C:\"),
            ("file://C|#", r"C:\"),
            ("file:///C%7C?", r"C:\"),
            ("file:///C%7C#", r"C:\"),
            ("file:///C%3A?", r"C:\"),
            ("file:///C%3A#", r"C:\"),
            ("file:///C:?query=foo&bar=baz", r"C:\"),
            ("file:///C|?query=foo&bar=baz", r"C:\"),
            ("file:///C:#section1", r"C:\"),
            ("file:///C|#section1", r"C:\"),
            ("file:///C:?query=foo#section1", r"C:\"),
            ("file:///C|?query=foo#section1", r"C:\"),
            ("file://localhost/C:?query=foo#section1", r"C:\"),
            ("file://localhost/C|?query=foo#section1", r"C:\"),
        ];
        for (uri, expected) in &root_query_frag_cases {
            let panic_res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(panic_res.is_ok(), "URI panicked: {}", uri);
            let res = panic_res
                .unwrap()
                .unwrap_or_else(|| panic!("Returned None for {}", uri));
            assert!(
                !res.to_string_lossy().contains('|'),
                "Contains pipe for {}: {:?}",
                uri,
                res
            );
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for {}",
                uri
            );
        }

        // 3. Drive-relative syntax like "C:file.rs" or "file:///C:file.rs" should NOT panic
        let non_absolute_cases = [
            "file:///C:file.rs",
            "file://C:file.rs",
            "file:///C|file.rs",
            "file://C|file.rs",
            "C:file.rs",
            "C|file.rs",
        ];
        for uri in &non_absolute_cases {
            let panic_res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(panic_res.is_ok(), "Drive-relative URI panicked: {}", uri);
        }

        // 4. Degenerate and empty URI inputs must never panic
        let degenerate_cases = [
            "",
            "   ",
            "file:",
            "file:/",
            "file://",
            "file:///",
            "file:////",
            "file://///",
            "file://localhost",
            "file://localhost/",
            r"file://localhost\",
            "file://localhost/dir",
            "file:///dir",
            "file://127.0.0.1/share/file.rs",
            "file://server/share/file.rs",
            "///",
            ":",
            "|",
            "C",
            "C:",
            "C|",
            "C:/",
            r"C:\",
            "/",
            r"\",
        ];
        for uri in &degenerate_cases {
            let panic_res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(panic_res.is_ok(), "Degenerate URI panicked: '{}'", uri);
        }
    }
}

// ------------------------------------------------------------------------------------------------
// ADVERSARIAL STRESS TESTS: DEFECT 1 & DEFECT 2 (CHALLENGER M1-ITER2-1)
// ------------------------------------------------------------------------------------------------

fn setup_symbols_test_db() -> Connection {
    let conn = Connection::open_in_memory().unwrap();
    conn.execute_batch(
        "CREATE TABLE files (
            file_id TEXT PRIMARY KEY,
            path TEXT NOT NULL,
            language TEXT,
            content_hash TEXT,
            content_bytes INTEGER,
            line_count INTEGER,
            indexed_at TEXT
        );
        CREATE TABLE symbols (
            symbol_id TEXT PRIMARY KEY,
            file_id TEXT,
            path TEXT NOT NULL,
            language TEXT,
            name TEXT,
            kind TEXT,
            signature TEXT,
            doc_comment TEXT,
            visibility TEXT,
            parent_symbol_id TEXT,
            start_line INTEGER,
            start_column INTEGER,
            end_line INTEGER,
            end_column INTEGER,
            start_byte INTEGER,
            end_byte INTEGER,
            body_start_line INTEGER,
            body_start_column INTEGER,
            body_end_line INTEGER,
            body_end_column INTEGER,
            body_start_byte INTEGER,
            body_end_byte INTEGER,
            body_hash TEXT,
            semantic_group TEXT,
            is_test INTEGER,
            test_container INTEGER
        );
        CREATE TABLE relationships (
            relationship_id TEXT PRIMARY KEY,
            from_symbol_id TEXT,
            to_symbol_id TEXT,
            kind TEXT,
            path TEXT,
            start_line INTEGER,
            start_column INTEGER
        );
        CREATE TABLE pending_relationships (
            from_symbol_id TEXT,
            target_terminal_name TEXT,
            kind TEXT,
            path TEXT,
            start_line INTEGER,
            start_column INTEGER
        );",
    )
    .unwrap();
    conn
}

/// Adversarial Stress Test: Defect 1 External callee backslash handling across deep nesting,
/// mixed slashes, Windows drive paths, deduplication, and include_external toggle.
#[test]
fn test_adversarial_defect1_external_callee_backslash_permutations() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "INSERT INTO symbols VALUES (
            's1', 'f1', 'src/api/auth.rs', 'rust', 'authenticate_user', 'function',
            'pub fn authenticate_user()', NULL, 'pub', NULL, 1, 0, 20, 0, 0, 200,
            1, 0, 20, 0, 0, 200, 'hash1', 'function', 0, 0
        );
        -- Deep nested backslash path
        INSERT INTO pending_relationships VALUES ('s1', 'verify_token', 'call', 'src\\security\\crypto\\jwt\\verifier.rs', 45, 8);
        -- Mixed slash path
        INSERT INTO pending_relationships VALUES ('s1', 'query_db', 'call', 'src/database\\postgres\\pool.rs', 102, 12);
        -- Absolute / Windows drive path
        INSERT INTO pending_relationships VALUES ('s1', 'write_audit_log', 'call', 'C:\\logs\\audit\\writer.rs', 15, 4);
        -- Duplicate entry to test deduplication
        INSERT INTO pending_relationships VALUES ('s1', 'verify_token', 'call', 'src\\security\\crypto\\jwt\\verifier.rs', 45, 8);
        ",
    )
    .unwrap();

    // 1. With include_external = false
    let no_ext = find_callee_signatures(&conn, "authenticate_user", "s1", 10, false).unwrap();
    assert!(
        no_ext.is_empty(),
        "When include_external is false, external callees must be empty: {:?}",
        no_ext
    );

    // 2. With include_external = true
    let with_ext = find_callee_signatures(&conn, "authenticate_user", "s1", 10, true).unwrap();
    assert_eq!(
        with_ext.len(),
        3,
        "Expected 3 unique external callees, got {:?}",
        with_ext
    );

    for callee in &with_ext {
        assert!(
            !callee.contains('\\'),
            "External callee signature must strictly format paths with forward slashes: {}",
            callee
        );
    }

    assert_eq!(
        with_ext[0],
        "verify_token (src/security/crypto/jwt/verifier.rs:45)"
    );
    assert_eq!(with_ext[1], "query_db (src/database/postgres/pool.rs:102)");
    assert_eq!(with_ext[2], "write_audit_log (C:/logs/audit/writer.rs:15)");
}

/// Adversarial Stress Test: Defect 2 Single-segment suffix path filter matrix across forward and backslash DBs,
/// root files, casing permutations (lower, upper, mixed), and leading/trailing separators.
#[test]
fn test_adversarial_defect2_suffix_path_filter_single_segment_matrix() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "
        -- 1. Forward-slash path in DB
        INSERT INTO symbols VALUES (
            's_fwd', 'f1', 'src/controllers/user_controller.rs', 'rust', 'UserController', 'struct',
            'pub struct UserController', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h1', 'struct', 0, 0
        );
        -- 2. Backslash path in DB
        INSERT INTO symbols VALUES (
            's_bs', 'f2', 'src\\handlers\\order_handler.rs', 'rust', 'OrderHandler', 'struct',
            'pub struct OrderHandler', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h2', 'struct', 0, 0
        );
        -- 3. Root file (no directories) in DB
        INSERT INTO symbols VALUES (
            's_root', 'f3', 'main.rs', 'rust', 'RunApp', 'function',
            'pub fn RunApp()', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h3', 'function', 0, 0
        );
        ",
    )
    .unwrap();

    // Permutations for forward-slash DB symbol:
    let fwd_queries = [
        "user_controller.rs",
        "USER_CONTROLLER.RS",
        "User_Controller.Rs",
        "/user_controller.rs",
        r"\user_controller.rs",
        "user_controller.rs/",
        r"user_controller.rs\",
        r"\user_controller.rs\",
        "/user_controller.rs/",
    ];
    for q in &fwd_queries {
        let sym = get_symbol_by_name(&conn, "UserController", Some(q))
            .unwrap()
            .unwrap_or_else(|| panic!("Failed to find UserController with filter: {}", q));
        assert_eq!(sym.name, "UserController");
        assert_eq!(sym.path, "src/controllers/user_controller.rs");
    }

    // Permutations for backslash DB symbol:
    let bs_queries = [
        "order_handler.rs",
        "ORDER_HANDLER.RS",
        "Order_Handler.Rs",
        "/order_handler.rs",
        r"\order_handler.rs",
        "order_handler.rs/",
        r"order_handler.rs\",
        r"\order_handler.rs\",
        "/order_handler.rs/",
    ];
    for q in &bs_queries {
        let sym = get_symbol_by_name(&conn, "OrderHandler", Some(q))
            .unwrap()
            .unwrap_or_else(|| panic!("Failed to find OrderHandler with filter: {}", q));
        assert_eq!(sym.name, "OrderHandler");
        assert_eq!(sym.path, "src/handlers/order_handler.rs");
    }

    // Permutations for root file:
    let root_queries = [
        "main.rs",
        "MAIN.RS",
        "Main.Rs",
        "/main.rs",
        r"\main.rs",
        "main.rs/",
        r"main.rs\",
    ];
    for q in &root_queries {
        let sym = get_symbol_by_name(&conn, "RunApp", Some(q))
            .unwrap()
            .unwrap_or_else(|| panic!("Failed to find RunApp with filter: {}", q));
        assert_eq!(sym.name, "RunApp");
        assert_eq!(sym.path, "main.rs");
    }
}

/// Adversarial Stress Test: Defect 2 Multi-segment suffix path filter matrix across forward and backslash DBs,
/// multi-hop paths, mixed slashes, casing permutations, and leading/trailing separators.
#[test]
fn test_adversarial_defect2_suffix_path_filter_multi_segment_matrix() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "
        INSERT INTO symbols VALUES (
            's_fwd', 'f1', 'src/services/billing/tax_calculator.rs', 'rust', 'TaxCalculator', 'struct',
            'pub struct TaxCalculator', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h1', 'struct', 0, 0
        );
        INSERT INTO symbols VALUES (
            's_bs', 'f2', 'src\\services\\shipping\\rate_estimator.rs', 'rust', 'RateEstimator', 'struct',
            'pub struct RateEstimator', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h2', 'struct', 0, 0
        );
        ",
    )
    .unwrap();

    // Test 2-segment, 3-segment, and 4-segment filters in forward-slash DB
    let fwd_multi_filters = [
        // Forward slashes
        "billing/tax_calculator.rs",
        "services/billing/tax_calculator.rs",
        "src/services/billing/tax_calculator.rs",
        // Backslashes
        r"billing\tax_calculator.rs",
        r"services\billing\tax_calculator.rs",
        r"src\services\billing\tax_calculator.rs",
        // Case variations
        "BILLING/TAX_CALCULATOR.RS",
        r"Billing\Tax_Calculator.Rs",
        "Services/Billing/Tax_Calculator.Rs",
        r"SERVICES\BILLING\TAX_CALCULATOR.RS",
        r"SRC\SERVICES\BILLING\TAX_CALCULATOR.RS",
        // Leading / trailing slashes
        "/billing/tax_calculator.rs",
        r"\billing\tax_calculator.rs",
        "billing/tax_calculator.rs/",
        r"billing\tax_calculator.rs\",
        r"\billing\tax_calculator.rs\",
    ];

    for q in &fwd_multi_filters {
        let sym = get_symbol_by_name(&conn, "TaxCalculator", Some(q))
            .unwrap()
            .unwrap_or_else(|| panic!("Failed to find TaxCalculator with filter: {}", q));
        assert_eq!(sym.name, "TaxCalculator");
        assert_eq!(sym.path, "src/services/billing/tax_calculator.rs");
    }

    // Test 2-segment, 3-segment, and 4-segment filters in backslash DB
    let bs_multi_filters = [
        // Forward slashes
        "shipping/rate_estimator.rs",
        "services/shipping/rate_estimator.rs",
        "src/services/shipping/rate_estimator.rs",
        // Backslashes
        r"shipping\rate_estimator.rs",
        r"services\shipping\rate_estimator.rs",
        r"src\services\shipping\rate_estimator.rs",
        // Case variations
        "SHIPPING/RATE_ESTIMATOR.RS",
        r"Shipping\Rate_Estimator.Rs",
        "Services/Shipping/Rate_Estimator.Rs",
        r"SERVICES\SHIPPING\RATE_ESTIMATOR.RS",
        r"SRC\SERVICES\SHIPPING\RATE_ESTIMATOR.RS",
        // Leading / trailing slashes
        "/shipping/rate_estimator.rs",
        r"\shipping\rate_estimator.rs",
        "shipping/rate_estimator.rs/",
        r"shipping\rate_estimator.rs\",
        r"\shipping\rate_estimator.rs\",
    ];

    for q in &bs_multi_filters {
        let sym = get_symbol_by_name(&conn, "RateEstimator", Some(q))
            .unwrap()
            .unwrap_or_else(|| panic!("Failed to find RateEstimator with filter: {}", q));
        assert_eq!(sym.name, "RateEstimator");
        assert_eq!(sym.path, "src/services/shipping/rate_estimator.rs");
    }
}

/// Adversarial Stress Test: Defect 2 LIKE special character escaping (`_` and `%`) in path filters.
#[test]
fn test_adversarial_defect2_path_filter_special_chars_escaping() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "
        -- Two files differing only by an underscore vs single character
        INSERT INTO symbols VALUES (
            's_target', 'f1', 'src/models/user_account.rs', 'rust', 'TargetModel', 'struct',
            'pub struct TargetModel', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h1', 'struct', 0, 0
        );
        INSERT INTO symbols VALUES (
            's_other', 'f2', 'src/models/userXaccount.rs', 'rust', 'TargetModel', 'struct',
            'pub struct TargetModel', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h2', 'struct', 0, 0
        );
        -- Same pair in backslash format
        INSERT INTO symbols VALUES (
            's_target_bs', 'f3', 'src\\models\\admin_account.rs', 'rust', 'AdminModel', 'struct',
            'pub struct AdminModel', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h3', 'struct', 0, 0
        );
        INSERT INTO symbols VALUES (
            's_other_bs', 'f4', 'src\\models\\adminZaccount.rs', 'rust', 'AdminModel', 'struct',
            'pub struct AdminModel', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h4', 'struct', 0, 0
        );
        -- File with percent sign in directory name
        INSERT INTO symbols VALUES (
            's_pct', 'f5', 'src/special%dir/item.rs', 'rust', 'SpecialItem', 'struct',
            'pub struct SpecialItem', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h5', 'struct', 0, 0
        );
        INSERT INTO symbols VALUES (
            's_pct_bs', 'f6', 'src\\special%dir\\item_bs.rs', 'rust', 'SpecialItemBs', 'struct',
            'pub struct SpecialItemBs', NULL, 'pub', NULL, 1, 0, 10, 0, 0, 100,
            1, 0, 10, 0, 0, 100, 'h6', 'struct', 0, 0
        );
        ",
    )
    .unwrap();

    // 1. In forward-slash DB: user_account.rs must match user_account.rs and NOT match userXaccount.rs
    let sym = get_symbol_by_name(&conn, "TargetModel", Some("user_account.rs")).unwrap();
    assert!(
        sym.is_some(),
        "user_account.rs should match exactly one target"
    );
    assert_eq!(sym.unwrap().path, "src/models/user_account.rs");

    let sym_multi =
        get_symbol_by_name(&conn, "TargetModel", Some("models/user_account.rs")).unwrap();
    assert_eq!(sym_multi.unwrap().path, "src/models/user_account.rs");

    // 2. In backslash DB: admin_account.rs must match admin_account.rs and NOT match adminZaccount.rs
    let sym_bs = get_symbol_by_name(&conn, "AdminModel", Some("admin_account.rs")).unwrap();
    assert!(
        sym_bs.is_some(),
        "admin_account.rs should match exactly one target in backslash DB"
    );
    assert_eq!(sym_bs.unwrap().path, "src/models/admin_account.rs");

    let sym_bs_multi =
        get_symbol_by_name(&conn, "AdminModel", Some(r"models\admin_account.rs")).unwrap();
    assert_eq!(sym_bs_multi.unwrap().path, "src/models/admin_account.rs");

    // 3. Percent sign in path
    let sym_pct1 = get_symbol_by_name(&conn, "SpecialItem", Some("special%dir/item.rs")).unwrap();
    assert!(sym_pct1.is_some());
    assert_eq!(sym_pct1.unwrap().path, "src/special%dir/item.rs");

    let sym_pct2 =
        get_symbol_by_name(&conn, "SpecialItemBs", Some(r"special%dir\item_bs.rs")).unwrap();
    assert!(sym_pct2.is_some());
    assert_eq!(sym_pct2.unwrap().path, "src/special%dir/item_bs.rs");
}

/// Adversarial Stress Test: Defect 2 Negative non-boundary matches across filenames, directories, and extensions.
#[test]
fn test_adversarial_defect2_negative_non_boundary_matches() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "
        INSERT INTO symbols VALUES (
            's1', 'f1', 'src/Services/PaymentService.rs', 'rust', 'ProcessPayment', 'function',
            'pub fn ProcessPayment()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'h1', 'function', 0, 0
        );
        INSERT INTO symbols VALUES (
            's2', 'f2', 'src\\Services\\OrderService.rs', 'rust', 'ProcessOrder', 'function',
            'pub fn ProcessOrder()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'h2', 'function', 0, 0
        );
        ",
    )
    .unwrap();

    let non_boundary_negatives_payment = [
        // Substrings inside filename without slash boundary
        "Payment.rs",
        "Service.rs",
        "entService.rs",
        "ymentService.rs",
        "FooPaymentService.rs",
        "PaymentService",
        "PaymentService.rsx",
        "PaymentService.rs.bak",
        // Substrings inside directory without boundary
        "vice/PaymentService.rs",
        r"vice\PaymentService.rs",
        "vices/PaymentService.rs",
        r"vices\PaymentService.rs",
        "FooServices/PaymentService.rs",
        r"FooServices\PaymentService.rs",
        // Directory only without filename
        "Services",
        "Services/",
        r"Services\",
        "src/Services",
        r"src\Services",
        // Earlier prefix only
        "src",
        "src/",
    ];

    for neg in &non_boundary_negatives_payment {
        let sym = get_symbol_by_name(&conn, "ProcessPayment", Some(neg)).unwrap();
        assert!(
            sym.is_none(),
            "Non-boundary filter '{}' must NOT match 'src/Services/PaymentService.rs'",
            neg
        );
    }

    let non_boundary_negatives_order = [
        // Substrings inside filename without slash boundary
        "Order.rs",
        "Service.rs",
        "derService.rs",
        "FooOrderService.rs",
        "OrderService",
        "OrderService.rsx",
        // Substrings inside directory without boundary
        "vice/OrderService.rs",
        r"vice\OrderService.rs",
        "vices/OrderService.rs",
        r"vices\OrderService.rs",
        "FooServices/OrderService.rs",
        r"FooServices\OrderService.rs",
        // Directory only without filename
        "Services",
        "Services/",
        r"Services\",
    ];

    for neg in &non_boundary_negatives_order {
        let sym = get_symbol_by_name(&conn, "ProcessOrder", Some(neg)).unwrap();
        assert!(
            sym.is_none(),
            "Non-boundary filter '{}' must NOT match 'src\\Services\\OrderService.rs'",
            neg
        );
    }
}

/// Adversarial Stress Test: Defect 2 Disambiguation of identical symbol names across directories with slashes.
#[test]
fn test_adversarial_defect2_disambiguation_with_slashes() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "
        INSERT INTO symbols VALUES (
            's_http', 'f1', 'src\\http\\client.rs', 'rust', 'build_client', 'function',
            'pub fn build_client() -> HttpClient', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'h1', 'function', 0, 0
        );
        INSERT INTO symbols VALUES (
            's_grpc', 'f2', 'src/grpc/client.rs', 'rust', 'build_client', 'function',
            'pub fn build_client() -> GrpcClient', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'h2', 'function', 0, 0
        );
        ",
    )
    .unwrap();

    // 1. Ambiguous query with just symbol name
    let err = get_symbol_by_name(&conn, "build_client", None);
    match err {
        Err(QueryError::AmbiguousSymbol(name, count, candidates)) => {
            assert_eq!(name, "build_client");
            assert_eq!(count, 2);
            assert!(candidates.contains("src/http/client.rs"));
            assert!(candidates.contains("src/grpc/client.rs"));
            assert!(
                !candidates.contains('\\'),
                "Candidates list must use forward slashes: {}",
                candidates
            );
        }
        other => panic!("Expected AmbiguousSymbol error, got {:?}", other),
    }

    // 2. Ambiguous query with just filename "client.rs" (both have client.rs)
    let err_file = get_symbol_by_name(&conn, "build_client", Some("client.rs"));
    match err_file {
        Err(QueryError::AmbiguousSymbol(name, count, _)) => {
            assert_eq!(name, "build_client");
            assert_eq!(count, 2);
        }
        other => panic!(
            "Expected AmbiguousSymbol error for client.rs, got {:?}",
            other
        ),
    }

    // 3. Disambiguate http client using forward slash
    let sym_http1 = get_symbol_by_name(&conn, "build_client", Some("http/client.rs"))
        .unwrap()
        .unwrap();
    assert_eq!(sym_http1.symbol_id, "s_http");
    assert_eq!(sym_http1.path, "src/http/client.rs");

    // 4. Disambiguate http client using backslash
    let sym_http2 = get_symbol_by_name(&conn, "build_client", Some(r"http\client.rs"))
        .unwrap()
        .unwrap();
    assert_eq!(sym_http2.symbol_id, "s_http");
    assert_eq!(sym_http2.path, "src/http/client.rs");

    // 5. Disambiguate grpc client using forward slash
    let sym_grpc1 = get_symbol_by_name(&conn, "build_client", Some("grpc/client.rs"))
        .unwrap()
        .unwrap();
    assert_eq!(sym_grpc1.symbol_id, "s_grpc");
    assert_eq!(sym_grpc1.path, "src/grpc/client.rs");

    // 6. Disambiguate grpc client using backslash
    let sym_grpc2 = get_symbol_by_name(&conn, "build_client", Some(r"grpc\client.rs"))
        .unwrap()
        .unwrap();
    assert_eq!(sym_grpc2.symbol_id, "s_grpc");
    assert_eq!(sym_grpc2.path, "src/grpc/client.rs");

    // 7. Case variations in disambiguation
    let sym_http_case = get_symbol_by_name(&conn, "build_client", Some("HTTP/CLIENT.RS"))
        .unwrap()
        .unwrap();
    assert_eq!(sym_http_case.symbol_id, "s_http");

    let sym_grpc_case = get_symbol_by_name(&conn, "build_client", Some(r"GRPC\CLIENT.RS"))
        .unwrap()
        .unwrap();
    assert_eq!(sym_grpc_case.symbol_id, "s_grpc");
}

/// Adversarial Stress Test: Defect 2 Exact path matching (`get_symbol_by_name_exact`) matrix.
#[test]
fn test_adversarial_defect2_exact_path_matching_matrix() {
    let conn = setup_symbols_test_db();
    conn.execute_batch(
        "
        INSERT INTO symbols VALUES (
            's_fwd', 'f1', 'src/services/payment.rs', 'rust', 'Process', 'function',
            'pub fn Process()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'h1', 'function', 0, 0
        );
        INSERT INTO symbols VALUES (
            's_bs', 'f2', 'src\\services\\order.rs', 'rust', 'Process', 'function',
            'pub fn Process()', NULL, 'pub', NULL, 1, 0, 5, 0, 0, 50,
            1, 0, 5, 0, 0, 50, 'h2', 'function', 0, 0
        );
        ",
    )
    .unwrap();

    // Exact matches must work across both slashes and casing:
    let sym1 = get_symbol_by_name_exact(&conn, "Process", "src/services/payment.rs").unwrap();
    assert!(sym1.is_some());
    assert_eq!(sym1.unwrap().path, "src/services/payment.rs");

    let sym2 = get_symbol_by_name_exact(&conn, "Process", r"src\services\payment.rs").unwrap();
    assert!(sym2.is_some());
    assert_eq!(sym2.unwrap().path, "src/services/payment.rs");

    let sym3 = get_symbol_by_name_exact(&conn, "Process", "SRC/SERVICES/PAYMENT.RS").unwrap();
    assert!(sym3.is_some());
    assert_eq!(sym3.unwrap().path, "src/services/payment.rs");

    // Exact match for backslash DB row:
    let sym4 = get_symbol_by_name_exact(&conn, "Process", "src/services/order.rs").unwrap();
    assert!(sym4.is_some());
    assert_eq!(sym4.unwrap().path, "src/services/order.rs");

    let sym5 = get_symbol_by_name_exact(&conn, "Process", r"src\services\order.rs").unwrap();
    assert!(sym5.is_some());
    assert_eq!(sym5.unwrap().path, "src/services/order.rs");

    let sym6 = get_symbol_by_name_exact(&conn, "Process", r"SRC\SERVICES\ORDER.RS").unwrap();
    assert!(sym6.is_some());
    assert_eq!(sym6.unwrap().path, "src/services/order.rs");

    // Suffixes must NOT match under get_symbol_by_name_exact:
    assert!(
        get_symbol_by_name_exact(&conn, "Process", "payment.rs")
            .unwrap()
            .is_none()
    );
    assert!(
        get_symbol_by_name_exact(&conn, "Process", "services/payment.rs")
            .unwrap()
            .is_none()
    );
    assert!(
        get_symbol_by_name_exact(&conn, "Process", r"services\payment.rs")
            .unwrap()
            .is_none()
    );
    assert!(
        get_symbol_by_name_exact(&conn, "Process", "order.rs")
            .unwrap()
            .is_none()
    );
    assert!(
        get_symbol_by_name_exact(&conn, "Process", "services/order.rs")
            .unwrap()
            .is_none()
    );
    assert!(
        get_symbol_by_name_exact(&conn, "Process", r"services\order.rs")
            .unwrap()
            .is_none()
    );
}

/// Adversarial Stress Test: Defect 4.1 & 4.2 Comprehensive Matrix
/// Tests drive roots (with/without trailing slash, ?, #, percent encodings, casing)
/// and localhost permutations (slashes, casing, paths, spaces, queries, fragments, no slashes).
#[test]
fn test_adversarial_defect4_remediation_deep_stress_matrix() {
    #[cfg(windows)]
    {
        // 1. Drive roots with and without trailing slash, casing, percent-encoding, query, fragment
        let root_matrix = [
            // Drive root no slash
            ("file:///C|", r"C:\"),
            ("file://C|", r"C:\"),
            ("file:///c|", r"c:\"),
            ("file://c|", r"c:\"),
            ("file:///C:", r"C:\"),
            ("file://C:", r"C:\"),
            ("file:///c:", r"c:\"),
            ("file://c:", r"c:\"),
            // Percent-encoded drive delimiters
            ("file:///C%7C", r"C:\"),
            ("file://C%7C", r"C:\"),
            ("file:///C%7c", r"C:\"),
            ("file://C%7c", r"C:\"),
            ("file:///c%7C", r"c:\"),
            ("file://c%7c", r"c:\"),
            ("file:///C%3A", r"C:\"),
            ("file://C%3A", r"C:\"),
            ("file:///C%3a", r"C:\"),
            ("file://C%3a", r"C:\"),
            ("file:///c%3A", r"c:\"),
            ("file://c%3a", r"c:\"),
            // Alternative drive letters
            ("file:///D|", r"D:\"),
            ("file:///d|", r"d:\"),
            ("file://D:", r"D:\"),
            ("file:///z:", r"z:\"),
            ("file://Z|", r"Z:\"),
            // Queries and fragments on roots
            ("file:///C|?foo=bar", r"C:\"),
            ("file://C|?foo=bar", r"C:\"),
            ("file:///c|?foo=bar", r"c:\"),
            ("file://c|?foo=bar", r"c:\"),
            ("file:///C:?foo=bar", r"C:\"),
            ("file://C:?foo=bar", r"C:\"),
            ("file:///c:?foo=bar", r"c:\"),
            ("file://c:?foo=bar", r"c:\"),
            ("file:///C|#frag", r"C:\"),
            ("file://C|#frag", r"C:\"),
            ("file:///c|#frag", r"c:\"),
            ("file://c|#frag", r"c:\"),
            ("file:///C:#frag", r"C:\"),
            ("file://C:#frag", r"C:\"),
            ("file:///c:#frag", r"c:\"),
            ("file://c:#frag", r"c:\"),
            ("file:///C|?foo=bar#frag", r"C:\"),
            ("file:///C:?foo=bar#frag", r"C:\"),
            ("file:///C%7C?foo=bar", r"C:\"),
            ("file:///C%7C#frag", r"C:\"),
            ("file:///C%3A?foo=bar", r"C:\"),
            ("file:///C%3A#frag", r"C:\"),
            // Four slashes
            ("file:////C|", r"C:\"),
            ("file:////C|/", r"C:\"),
            ("file:////c|", r"c:\"),
            ("file:////C:", r"C:\"),
        ];

        for (uri, expected) in &root_matrix {
            let res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(res.is_ok(), "URI '{}' must not panic", uri);
            let path_opt = res.unwrap();
            assert!(path_opt.is_some(), "URI '{}' must return Some", uri);
            let path = path_opt.unwrap();
            assert!(
                !path.to_string_lossy().contains('|'),
                "URI '{}' must not contain pipe in resolved path: {:?}",
                uri,
                path
            );
            assert_eq!(
                path,
                normalize_path(Path::new(expected)),
                "Mismatch for root URI '{}'",
                uri
            );
        }

        // 2. Localhost root variants (with/without slash, pipe/colon, casing, query, fragment)
        let localhost_roots = [
            ("file://localhost/C|", r"C:\"),
            ("file://localhost/C|/", r"C:\"),
            ("file://localhost/c|", r"c:\"),
            ("file://localhost/c|/", r"c:\"),
            ("file://localhost/C:", r"C:\"),
            ("file://localhost/C:/", r"C:\"),
            ("file://localhost/c:", r"c:\"),
            ("file://localhost/c:/", r"c:\"),
            ("file://LOCALHOST/C|", r"C:\"),
            ("file://LOCALHOST/C|/", r"C:\"),
            ("file://LOCALHOST/c|", r"c:\"),
            ("file://LOCALHOST/c|/", r"c:\"),
            ("file://LOCALHOST/C:", r"C:\"),
            ("file://LOCALHOST/C:/", r"C:\"),
            ("file://LOCALHOST/c:", r"c:\"),
            ("file://LOCALHOST/c:/", r"c:\"),
            ("file://LocalHost/C|", r"C:\"),
            ("file://LocalHost/c|", r"c:\"),
            ("file://LocalHost/C:", r"C:\"),
            ("file://LocalHost/c:", r"c:\"),
            ("file://localhost/C%7C", r"C:\"),
            ("file://localhost/c%7c", r"c:\"),
            ("file://localhost/C%3A", r"C:\"),
            ("file://localhost/c%3a", r"c:\"),
            ("file://localhost/C|?foo=bar", r"C:\"),
            ("file://localhost/C|#frag", r"C:\"),
            ("file://localhost/C:?foo=bar", r"C:\"),
            ("file://localhost/C:#frag", r"C:\"),
            ("file://localhost/c|?foo=bar", r"c:\"),
            ("file://localhost/c|#frag", r"c:\"),
            ("file://localhost/c:?foo=bar", r"c:\"),
            ("file://localhost/c:#frag", r"c:\"),
            // Backslash localhost variants
            (r"file://localhost\C|", r"C:\"),
            (r"file://localhost\c|", r"c:\"),
            (r"file://localhost\C:", r"C:\"),
            (r"file://localhost\c:", r"c:\"),
            (r"file://localhost\C|\", r"C:\"),
            (r"file://localhost\c|\", r"c:\"),
            (r"file://localhost\C:\", r"C:\"),
            (r"file://localhost\c:\", r"c:\"),
            (r"file://LOCALHOST\C|", r"C:\"),
            (r"file://LOCALHOST\C|\", r"C:\"),
            // Three-slash localhost roots
            ("file:///localhost/C|", r"C:\"),
            ("file:///localhost/C|/", r"C:\"),
            ("file:///localhost/c|", r"c:\"),
            ("file:///localhost/c|/", r"c:\"),
            ("file:///localhost/C:", r"C:\"),
            ("file:///localhost/C:/", r"C:\"),
            ("file:///localhost/c:", r"c:\"),
            ("file:///localhost/c:/", r"c:\"),
        ];

        for (uri, expected) in &localhost_roots {
            let res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(res.is_ok(), "Localhost root URI '{}' must not panic", uri);
            let path_opt = res.unwrap();
            assert!(
                path_opt.is_some(),
                "Localhost root URI '{}' must return Some",
                uri
            );
            let path = path_opt.unwrap();
            assert!(
                !path.to_string_lossy().contains('|'),
                "Localhost root URI '{}' must not contain pipe: {:?}",
                uri,
                path
            );
            assert_eq!(
                path,
                normalize_path(Path::new(expected)),
                "Mismatch for localhost root URI '{}'",
                uri
            );
        }

        // 3. Localhost path variants (casing, slashes, spaces, encoded, subdirs)
        let localhost_paths = [
            ("file://localhost/C|/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://localhost/c|/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://localhost/C:/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://localhost/c:/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://LOCALHOST/C|/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://LOCALHOST/c|/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://LOCALHOST/C:/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://LOCALHOST/c:/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://LocalHost/C|/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://LocalHost/c|/path/to/file.rs", r"c:\path\to\file.rs"),
            ("file://LocalHost/C:/path/to/file.rs", r"C:\path\to\file.rs"),
            ("file://LocalHost/c:/path/to/file.rs", r"c:\path\to\file.rs"),
            (
                "file://localhost/C|/folder/sub/code.rs?rev=1#L10",
                r"C:\folder\sub\code.rs",
            ),
            (
                "file://localhost/C|/Program Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                "file://localhost/C|/Program%20Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                "file://localhost/C:/Program%20Files/App/file.rs",
                r"C:\Program Files\App\file.rs",
            ),
            (
                r"file://localhost\C|\path\to\file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                r"file://localhost\c|\path\to\file.rs",
                r"c:\path\to\file.rs",
            ),
            (
                r"file://localhost\C:\path\to\file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                r"file://localhost\c:\path\to\file.rs",
                r"c:\path\to\file.rs",
            ),
            (
                r"file://LOCALHOST\C|\path\to\file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                r"file://LOCALHOST\C:\path\to\file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file:///localhost/C|/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file:///localhost/c|/path/to/file.rs",
                r"c:\path\to\file.rs",
            ),
            (
                "file:///localhost/C:/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file:///localhost/c:/path/to/file.rs",
                r"c:\path\to\file.rs",
            ),
            (
                "file:///LOCALHOST/C|/path/to/file.rs",
                r"C:\path\to\file.rs",
            ),
            (
                "file:///LOCALHOST/c|/path/to/file.rs",
                r"c:\path\to\file.rs",
            ),
            ("file:////C|/path/to/file.rs", r"C:\path\to\file.rs"),
        ];

        for (uri, expected) in &localhost_paths {
            let res = std::panic::catch_unwind(|| parse_file_uri(uri));
            assert!(res.is_ok(), "Localhost path URI '{}' must not panic", uri);
            let path_opt = res.unwrap();
            assert!(
                path_opt.is_some(),
                "Localhost path URI '{}' must return Some",
                uri
            );
            let path = path_opt.unwrap();
            assert!(
                !path.to_string_lossy().contains('|'),
                "Localhost path URI '{}' must not contain pipe: {:?}",
                uri,
                path
            );
            assert_eq!(
                path,
                normalize_path(Path::new(expected)),
                "Mismatch for localhost path URI '{}'",
                uri
            );
        }

        // 4. Plain strings (non-file://) with pipes and colons
        let plain_strings = [
            ("C|", r"C:\"),
            ("c|", r"c:\"),
            ("C:", r"C:\"),
            ("c:", r"c:\"),
            ("/C|", r"C:\"),
            ("/c|", r"c:\"),
            ("C|/path/to/file.rs", r"C:\path\to\file.rs"),
            ("c|/path/to/file.rs", r"c:\path\to\file.rs"),
            (r"C|\path\to\file.rs", r"C:\path\to\file.rs"),
            (r"c|\path\to\file.rs", r"c:\path\to\file.rs"),
            ("/C|/path/to/file.rs", r"C:\path\to\file.rs"),
        ];

        for (plain, expected) in &plain_strings {
            let res = parse_file_uri(plain)
                .unwrap_or_else(|| panic!("Failed for plain string: {}", plain));
            assert!(
                !res.to_string_lossy().contains('|'),
                "Result for '{}' contains pipe: {:?}",
                plain,
                res
            );
            assert_eq!(
                res,
                normalize_path(Path::new(expected)),
                "Mismatch for plain string '{}'",
                plain
            );
        }

        // 5. Robustness / No-Panic checks on extreme boundary inputs
        let boundary_cases = [
            "",
            "file://",
            "file:///",
            "file://localhost",
            "file://localhost/",
            "file:///|",
            "file:///123|",
            "file:///:::",
            "file:///C:foo",
            "file:///C|foo",
            "file:///Ä|/",
        ];

        for input in &boundary_cases {
            let panic_res = std::panic::catch_unwind(|| {
                let _ = parse_file_uri(input);
            });
            assert!(
                panic_res.is_ok(),
                "Extreme input '{}' must not panic",
                input
            );
        }
    }
}