llmgrep 3.4.5

Smart grep over Magellan code maps with schema-aligned JSON output
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
//! AST module tests
//!
//! Tests for AST filtering and backward compatibility.

use llmgrep::ast::{ast_nodes_table_schema, check_ast_table_exists, AstContext};
use llmgrep::query::{
    search_symbols, AstOptions, ContextOptions, DepthOptions, FqnOptions, MetricsOptions,
    SearchOptions, SnippetOptions,
};
use llmgrep::AlgorithmOptions;
use rusqlite::{params, Connection};
use tempfile::TempDir;

fn setup_db_with_ast(path: &std::path::Path) -> Connection {
    let conn = Connection::open(path).expect("open db");

    // Create graph_entities table
    conn.execute_batch(
        "CREATE TABLE graph_entities (
            id INTEGER PRIMARY KEY,
            kind TEXT NOT NULL,
            name TEXT,
            data TEXT
        );
        CREATE TABLE graph_edges (
            id INTEGER PRIMARY KEY,
            from_id INTEGER,
            to_id INTEGER,
            edge_type TEXT
        );
        CREATE TABLE symbol_metrics (
            symbol_id INTEGER PRIMARY KEY,
            fan_in INTEGER,
            fan_out INTEGER,
            cyclomatic_complexity INTEGER
        );",
    )
    .expect("create base tables");

    // Create ast_nodes table
    conn.execute(ast_nodes_table_schema(), [])
        .expect("create ast_nodes table");

    conn
}

fn insert_symbol(
    conn: &Connection,
    id: i64,
    name: &str,
    kind: &str,
    _file_id: i64,
    byte_start: u64,
    byte_end: u64,
) {
    conn.execute(
        "INSERT INTO graph_entities (id, kind, name, data) VALUES (?1, 'Symbol', ?2, ?3)",
        params![
            id,
            name,
            format!(
                r#"{{"name":"{}","kind":"{}","symbol_id":"{:040x}","byte_start":{},"byte_end":{},"start_line":1,"start_col":0,"end_line":1,"end_col":{}}}"#,
                name,
                kind,
                id,
                byte_start,
                byte_end,
                byte_end - byte_start
            )
        ],
    )
    .expect("insert symbol");
}

fn insert_file(conn: &Connection, id: i64, path: &str) {
    conn.execute(
        "INSERT INTO graph_entities (id, kind, data) VALUES (?1, 'File', ?2)",
        params![id, format!(r#"{{"path":"{}"}}"#, path)],
    )
    .expect("insert file");
}

fn insert_define_edge(conn: &Connection, from_id: i64, to_id: i64) {
    conn.execute(
        "INSERT INTO graph_edges (from_id, to_id, edge_type) VALUES (?1, ?2, 'DEFINES')",
        params![from_id, to_id],
    )
    .expect("insert edge");
}

fn insert_ast_node(
    conn: &Connection,
    id: i64,
    kind: &str,
    parent_id: Option<i64>,
    byte_start: u64,
    byte_end: u64,
) {
    conn.execute(
        "INSERT INTO ast_nodes (id, kind, parent_id, byte_start, byte_end) VALUES (?1, ?2, ?3, ?4, ?5)",
        params![id, kind, parent_id, byte_start, byte_end],
    )
    .expect("insert ast node");
}

#[test]
fn test_check_ast_table_exists() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");

    // Test with ast_nodes table
    let conn = setup_db_with_ast(&db_path);
    assert!(
        check_ast_table_exists(&conn).expect("failed to check AST table"),
        "Should return true when ast_nodes table exists"
    );
    drop(conn);

    // Test without ast_nodes table
    let conn2 = Connection::open(&db_path).expect("open db");
    conn2
        .execute("DROP TABLE ast_nodes", [])
        .expect("drop ast_nodes");
    assert!(
        !check_ast_table_exists(&conn2).expect("failed to check AST table"),
        "Should return false when ast_nodes table doesn't exist"
    );
}

#[test]
fn test_ast_context_serialization() {
    let ctx = AstContext {
        ast_id: 123,
        kind: "function_item".to_string(),
        parent_id: Some(122),
        byte_start: 100,
        byte_end: 200,
        depth: None,
        parent_kind: None,
        children_count_by_kind: None,
        decision_points: None,
    };

    let json = serde_json::to_string(&ctx).expect("failed to serialize context");
    assert!(json.contains(r#""ast_id":123"#));
    assert!(json.contains(r#""kind":"function_item""#));
    assert!(json.contains(r#""parent_id":122"#));
    assert!(json.contains(r#""byte_start":100"#));
    assert!(json.contains(r#""byte_end":200"#));
}

#[test]
fn test_ast_context_without_parent() {
    let ctx = AstContext {
        ast_id: 1,
        kind: "mod_item".to_string(),
        parent_id: None,
        byte_start: 0,
        byte_end: 50,
        depth: None,
        parent_kind: None,
        children_count_by_kind: None,
        decision_points: None,
    };

    let json = serde_json::to_string(&ctx).expect("failed to serialize context");
    assert!(json.contains(r#""parent_id":null"#));
}

#[test]
fn test_ast_kind_filter() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    insert_file(&conn, 1, "src/lib.rs");

    // Insert symbols with matching byte ranges
    insert_symbol(&conn, 10, "my_function", "Function", 1, 0, 100);
    insert_symbol(&conn, 11, "my_block", "Block", 1, 10, 90);
    insert_symbol(&conn, 12, "my_call", "Call", 1, 20, 80);
    insert_define_edge(&conn, 1, 10);
    insert_define_edge(&conn, 1, 11);
    insert_define_edge(&conn, 1, 12);

    // Insert AST nodes with different kinds
    insert_ast_node(&conn, 10, "function_item", None, 0, 100);
    insert_ast_node(&conn, 11, "block", Some(10), 10, 90);
    insert_ast_node(&conn, 12, "call_expression", Some(11), 20, 80);

    // Search for function_item only
    let options = SearchOptions {
        db_path: &db_path,
        query: "my_",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["function_item".to_string()],
            with_ast_context: true, // Enable to use overlap matching
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    // Debug: print results
    for result in &response.results {
        eprintln!(
            "Result: {} -> ast_context: {:?}",
            result.name,
            result.ast_context.as_ref().map(|c| &c.kind)
        );
    }
    // Overlap semantics: all 3 symbols overlap with function_item (0-100)
    // This is correct behavior for real Magellan DBs where spans don't align exactly
    assert_eq!(
        response.results.len(),
        3,
        "Should return all symbols that overlap with function_item"
    );
    // All results should have function_item in their ast_context
    for result in &response.results {
        assert_eq!(
            result
                .ast_context
                .as_ref()
                .expect("ast_context should be Some")
                .kind,
            "function_item"
        );
    }
}

#[test]
fn test_backward_compat_no_ast_table() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = Connection::open(&db_path).expect("open db");

    // Create basic schema without ast_nodes table (but with symbol_metrics for compatibility)
    conn.execute_batch(
        "CREATE TABLE graph_entities (
            id INTEGER PRIMARY KEY,
            kind TEXT NOT NULL,
            name TEXT,
            data TEXT
        );
        CREATE TABLE graph_edges (
            id INTEGER PRIMARY KEY,
            from_id INTEGER,
            to_id INTEGER,
            edge_type TEXT
        );
        CREATE TABLE symbol_metrics (
            symbol_id INTEGER PRIMARY KEY,
            fan_in INTEGER,
            fan_out INTEGER,
            cyclomatic_complexity INTEGER
        );",
    )
    .expect("create base tables");

    // Insert file and symbol
    insert_file(&conn, 1, "src/lib.rs");
    insert_symbol(&conn, 10, "my_function", "Function", 1, 0, 100);
    insert_define_edge(&conn, 1, 10);

    // Verify table doesn't exist
    assert!(
        !check_ast_table_exists(&conn).expect("failed to check AST table"),
        "ast_nodes table should not exist"
    );

    // Search with ast_kind filter (should be gracefully ignored)
    let options = SearchOptions {
        db_path: &db_path,
        query: "my_function",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["function_item".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(response.results.len(), 1);
    assert_eq!(response.results[0].name, "my_function");
    // ast_context should be None when table doesn't exist
    assert!(
        response.results[0].ast_context.is_none(),
        "ast_context should be None when ast_nodes table doesn't exist"
    );
}

#[test]
fn test_ast_context_population() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file and symbol
    insert_file(&conn, 1, "src/lib.rs");
    insert_symbol(&conn, 10, "parent_function", "Function", 1, 100, 200);
    insert_define_edge(&conn, 1, 10);

    // Insert AST node with parent (matching symbol byte range)
    insert_ast_node(&conn, 10, "function_item", Some(5), 100, 200);

    // Search
    let options = SearchOptions {
        db_path: &db_path,
        query: "parent_function",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions::default(),
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(response.results.len(), 1);

    let ast_ctx = response.results[0]
        .ast_context
        .as_ref()
        .expect("ast_context should be present");

    assert_eq!(ast_ctx.ast_id, 10);
    assert_eq!(ast_ctx.kind, "function_item");
    assert_eq!(ast_ctx.parent_id, Some(5));
    assert_eq!(ast_ctx.byte_start, 100);
    assert_eq!(ast_ctx.byte_end, 200);
}

#[test]
fn test_multiple_ast_kinds() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    insert_file(&conn, 1, "src/lib.rs");

    // Insert symbols with different AST kinds (matching byte ranges)
    insert_symbol(&conn, 10, "func_one", "Function", 1, 0, 100);
    insert_symbol(&conn, 11, "func_two", "Function", 1, 100, 200);
    insert_define_edge(&conn, 1, 10);
    insert_define_edge(&conn, 1, 11);

    insert_ast_node(&conn, 10, "function_item", None, 0, 100);
    insert_ast_node(&conn, 11, "function_item", None, 100, 200);

    // Test filtering by call_expression (should return none since we only have functions)
    let options = SearchOptions {
        db_path: &db_path,
        query: "func",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["call_expression".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(
        response.results.len(),
        0,
        "Should return no results for call_expression kind"
    );

    // Test filtering by function_item (should return both)
    let options = SearchOptions {
        db_path: &db_path,
        query: "func",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["function_item".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(
        response.results.len(),
        2,
        "Should return both function_item results"
    );
}

#[test]
fn test_ast_nodes_table_schema() {
    let schema = ast_nodes_table_schema();
    assert!(schema.contains("CREATE TABLE ast_nodes"));
    assert!(schema.contains("id INTEGER PRIMARY KEY"));
    assert!(schema.contains("parent_id"));
    assert!(schema.contains("kind TEXT NOT NULL"));
    assert!(schema.contains("byte_start INTEGER NOT NULL"));
    assert!(schema.contains("byte_end INTEGER NOT NULL"));
}

// Test: Calculate AST depth for nested nodes
#[test]
fn test_calculate_ast_depth() {
    use llmgrep::ast::calculate_ast_depth;

    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = Connection::open(&db_path).expect("open db");

    // Create ast_nodes table
    conn.execute(ast_nodes_table_schema(), [])
        .expect("create ast_nodes");

    // Create a tree structure:
    //   id=1: root (parent_id=NULL) -> depth 0
    //   id=2: child of 1 -> depth 1
    //   id=3: child of 2 -> depth 2
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (1, NULL, 'mod_item', 0, 1000),
        (2, 1, 'function_item', 100, 500),
        (3, 2, 'block', 150, 450)",
        [],
    )
    .expect("insert nodes");

    // Test depth calculation
    assert_eq!(
        calculate_ast_depth(&conn, 1)
            .expect("failed to calculate AST depth")
            .expect("AST depth should be Some"),
        0,
        "Root should have depth 0"
    );
    assert_eq!(
        calculate_ast_depth(&conn, 2)
            .expect("failed to calculate AST depth")
            .expect("AST depth should be Some"),
        1,
        "Child should have depth 1"
    );
    assert_eq!(
        calculate_ast_depth(&conn, 3)
            .expect("failed to calculate AST depth")
            .expect("AST depth should be Some"),
        2,
        "Grandchild should have depth 2"
    );
}

// Test: Get parent kind for AST nodes
#[test]
fn test_get_parent_kind() {
    use llmgrep::ast::get_parent_kind;

    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = Connection::open(&db_path).expect("open db");

    conn.execute(ast_nodes_table_schema(), [])
        .expect("create ast_nodes");

    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (1, NULL, 'mod_item', 0, 1000),
        (2, 1, 'function_item', 100, 500)",
        [],
    )
    .expect("insert nodes");

    // Test parent kind lookup
    assert_eq!(
        get_parent_kind(&conn, Some(1))
            .expect("failed to get parent kind")
            .expect("parent kind should be Some"),
        "mod_item",
        "Parent kind should be mod_item"
    );
    assert_eq!(
        get_parent_kind(&conn, None).expect("failed to get parent kind for None"),
        None,
        "None parent_id should return None"
    );
    assert_eq!(
        get_parent_kind(&conn, Some(999)).expect("failed to get parent kind for nonexistent"),
        None,
        "Non-existent parent should return None"
    );
}

// Test: Count children by kind
#[test]
fn test_count_children_by_kind() {
    use llmgrep::ast::count_children_by_kind;

    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = Connection::open(&db_path).expect("open db");

    conn.execute(ast_nodes_table_schema(), [])
        .expect("create ast_nodes");

    // Create a node with multiple child types
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (1, NULL, 'function_item', 0, 1000),
        (2, 1, 'let_declaration', 100, 150),
        (3, 1, 'let_declaration', 150, 200),
        (4, 1, 'let_declaration', 200, 250),
        (5, 1, 'if_expression', 250, 400),
        (6, 1, 'call_expression', 300, 350),
        (7, 1, 'call_expression', 350, 380)",
        [],
    )
    .expect("insert nodes");

    let counts = count_children_by_kind(&conn, 1).expect("failed to count children");
    assert_eq!(
        counts.get("let_declaration"),
        Some(&3),
        "Should have 3 let_declaration"
    );
    assert_eq!(
        counts.get("if_expression"),
        Some(&1),
        "Should have 1 if_expression"
    );
    assert_eq!(
        counts.get("call_expression"),
        Some(&2),
        "Should have 2 call_expression"
    );
}

// Test: Count decision points
#[test]
fn test_count_decision_points() {
    use llmgrep::ast::count_decision_points;

    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = Connection::open(&db_path).expect("open db");

    conn.execute(ast_nodes_table_schema(), [])
        .expect("create ast_nodes");

    // Create a node with decision points (2-7 are decision points, 8-9 are not)
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (1, NULL, 'function_item', 0, 1000),
        (2, 1, 'if_expression', 100, 200),
        (3, 1, 'match_expression', 200, 300),
        (4, 1, 'while_expression', 300, 400),
        (5, 1, 'for_expression', 400, 500),
        (6, 1, 'loop_expression', 500, 600),
        (7, 1, 'conditional_expression', 600, 650),
        (8, 1, 'let_declaration', 650, 700),
        (9, 1, 'call_expression', 700, 750)",
        [],
    )
    .expect("insert nodes");

    let decision_points = count_decision_points(&conn, 1).expect("failed to count decision points");
    assert_eq!(decision_points, 6, "Should count 6 decision points");
}

// Test: Enriched AST context in search results
#[test]
fn test_with_ast_context_flag() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST nodes with nested structure
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (1, NULL, 'mod_item', 0, 1000),
        (2, 1, 'function_item', 100, 500),
        (3, 2, 'let_declaration', 150, 200),
        (4, 2, 'if_expression', 200, 350),
        (5, 2, 'call_expression', 360, 400)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbol and edge
    insert_symbol(&conn, 100, "my_function", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 100);
    conn.execute(
        "UPDATE graph_entities SET data = json_object(
            'byte_start', 150,
            'byte_end', 400,
            'start_line', 10,
            'start_col', 0,
            'end_line', 25,
            'end_col', 1,
            'kind', 'Function',
            'name', 'my_function'
        ) WHERE id = 100",
        [],
    )
    .expect("update symbol data");

    // Update symbol_metrics to match symbol_id
    conn.execute(
        "INSERT INTO symbol_metrics (symbol_id, fan_in, fan_out, cyclomatic_complexity)
        VALUES (100, 5, 3, 2)",
        [],
    )
    .expect("insert metrics");

    // Search with --with-ast-context flag
    let options = SearchOptions {
        db_path: &db_path,
        query: "my_function",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec![],
            with_ast_context: true, // Enable enriched context
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(response.results.len(), 1, "Should find the function");

    let ast_ctx = response.results[0]
        .ast_context
        .as_ref()
        .expect("Should have ast_context");

    // Check basic fields
    assert_eq!(ast_ctx.kind, "function_item");

    // Check enriched fields (should be populated with --with-ast-context)
    assert_eq!(ast_ctx.depth, Some(1), "Depth should be populated");
    assert_eq!(
        ast_ctx.parent_kind.as_deref(),
        Some("mod_item"),
        "Parent kind should be populated"
    );
    assert!(
        ast_ctx.children_count_by_kind.is_some(),
        "Children count should be populated"
    );
    assert_eq!(
        ast_ctx.decision_points,
        Some(1), // One if_expression
        "Decision points should be counted"
    );
}

// Test: Backward compatibility - ast_context without flag
#[test]
fn test_ast_context_without_flag() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST nodes - byte ranges must match the symbol's UPDATE'd values below
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 150, 400)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbol and edge
    insert_symbol(&conn, 100, "my_function", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 100);
    conn.execute(
        "UPDATE graph_entities SET data = json_object(
            'byte_start', 150,
            'byte_end', 400,
            'start_line', 10,
            'start_col', 0,
            'end_line', 25,
            'end_col', 1,
            'kind', 'Function',
            'name', 'my_function'
        ) WHERE id = 100",
        [],
    )
    .expect("update symbol data");

    // Update symbol_metrics
    conn.execute(
        "INSERT INTO symbol_metrics (symbol_id, fan_in, fan_out, cyclomatic_complexity)
        VALUES (100, 5, 3, 2)",
        [],
    )
    .expect("insert metrics");

    // Search WITHOUT --with-ast-context flag
    let options = SearchOptions {
        db_path: &db_path,
        query: "my_function",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec![],
            with_ast_context: false, // NOT enabled
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(response.results.len(), 1, "Should find the function");

    let ast_ctx = response.results[0]
        .ast_context
        .as_ref()
        .expect("Should have basic ast_context from LEFT JOIN");

    // Basic fields should be present
    assert_eq!(ast_ctx.kind, "function_item");

    // Enriched fields should NOT be populated without flag
    assert_eq!(ast_ctx.depth, None, "Depth should not be populated");
    assert_eq!(
        ast_ctx.parent_kind, None,
        "Parent kind should not be populated"
    );
    assert_eq!(
        ast_ctx.children_count_by_kind, None,
        "Children count should not be populated"
    );
    assert_eq!(
        ast_ctx.decision_points, None,
        "Decision points should not be populated"
    );
}

// Test: Sorting by AstComplexity (same as Complexity)
#[test]
fn test_sort_by_ast_complexity() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Insert symbols with different complexities
    insert_symbol(&conn, 100, "simple_func", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 100);
    conn.execute(
        "UPDATE graph_entities SET data = json_object(
            'byte_start', 100, 'byte_end', 150,
            'start_line', 10, 'start_col', 0, 'end_line', 12, 'end_col', 1,
            'kind', 'Function', 'name', 'simple_func'
        ) WHERE id = 100",
        [],
    )
    .expect("update symbol 1");

    insert_symbol(&conn, 200, "complex_func", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 200);
    conn.execute(
        "UPDATE graph_entities SET data = json_object(
            'byte_start', 200, 'byte_end', 300,
            'start_line', 20, 'start_col', 0, 'end_line', 25, 'end_col', 1,
            'kind', 'Function', 'name', 'complex_func'
        ) WHERE id = 200",
        [],
    )
    .expect("update symbol 2");

    // Insert metrics with different complexity values
    conn.execute(
        "INSERT INTO symbol_metrics (symbol_id, fan_in, fan_out, cyclomatic_complexity)
        VALUES (100, 1, 0, 1)",
        [],
    )
    .expect("insert metrics 1");

    conn.execute(
        "INSERT INTO symbol_metrics (symbol_id, fan_in, fan_out, cyclomatic_complexity)
        VALUES (200, 2, 1, 10)",
        [],
    )
    .expect("insert metrics 2");

    // Search with AstComplexity sort
    let options = SearchOptions {
        db_path: &db_path,
        query: "func",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::AstComplexity, // New sort mode
        metrics: MetricsOptions::default(),
        ast: AstOptions::default(),
        depth: DepthOptions::default(),
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");
    assert_eq!(response.results.len(), 2, "Should find both functions");

    // Should be sorted by complexity descending (complex_func first)
    assert_eq!(
        response.results[0].name, "complex_func",
        "Highest complexity should come first"
    );
    assert_eq!(
        response.results[1].name, "simple_func",
        "Lower complexity should come second"
    );
}

// ============================================================================
// Phase 9 Tests: Depth and Structural Search
// ============================================================================

// Test 1: test_calculate_decision_depth (already exists in src/ast.rs)

// Test 2: test_min_depth_filter
#[test]
fn test_min_depth_filter() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST nodes at different decision depths
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 100, 500),  -- depth 0 (root level function)
        (101, 100, 'let_declaration', 150, 200),
        (102, 100, 'if_expression', 250, 350),  -- depth 1 (inside function)
        (103, 102, 'loop_expression', 260, 340), -- depth 2 (inside if)
        (104, 100, 'let_declaration', 400, 450), -- depth 0 (sibling of if)
        (105, 100, 'match_expression', 460, 490), -- depth 1 (inside function)
        (106, 105, 'if_expression', 470, 480), -- depth 2 (inside match)
        (107, 106, 'loop_expression', 472, 478), -- depth 3 (inside if, inside match)
        (108, 100, 'let_declaration', 500, 520)  -- depth 0 (sibling)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols with spans matching their corresponding AST nodes
    // symbol_100 = function_item (100, 500)
    // symbol_102 = if_expression (250, 350)
    // symbol_103 = loop_expression (260, 340)
    // symbol_105 = match_expression (460, 490)
    // symbol_106 = if_expression (470, 480)
    // symbol_107 = loop_expression (472, 478)
    let ast_node_spans: &[(i64, u64, u64)] = &[
        (100, 100, 500),
        (102, 250, 350),
        (103, 260, 340),
        (105, 460, 490),
        (106, 470, 480),
        (107, 472, 478),
    ];
    for &(ast_id, byte_start, byte_end) in ast_node_spans {
        insert_symbol(
            &conn,
            ast_id,
            &format!("symbol_{}", ast_id),
            "Function",
            file_id,
            byte_start,
            byte_end,
        );
        insert_define_edge(&conn, file_id, ast_id);
    }

    // Search with min_depth=2 should return only symbols at depth 2 or 3
    let options = SearchOptions {
        db_path: &db_path,
        query: "symbol_",
        path_filter: None,
        kind_filter: None,
        limit: 100,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions::default(),
        depth: DepthOptions {
            min_depth: Some(2),
            max_depth: None,
            inside: None,
            contains: None,
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find symbols at depth >= 2
    // symbol_103 (loop inside if) = depth 2
    // symbol_107 (if inside match) = depth 2
    // symbol_108 (loop inside if inside match) = depth 3
    assert!(
        response.results.len() >= 2,
        "Should find at least 2 symbols with depth >= 2"
    );
}

// Test 3: test_max_depth_filter
#[test]
fn test_max_depth_filter() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST nodes at different depths
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 100, 600),
        (101, 100, 'if_expression', 150, 250),   -- depth 1
        (102, 101, 'loop_expression', 160, 240), -- depth 2
        (103, 102, 'match_expression', 170, 230), -- depth 3
        (104, 103, 'if_expression', 180, 220),   -- depth 4
        (105, 100, 'let_declaration', 260, 300)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols - use "test" prefix so query matches both
    insert_symbol(&conn, 100, "test_func_depth0", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 100);
    insert_symbol(&conn, 101, "test_if_depth1", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 101);
    insert_symbol(&conn, 102, "test_loop_depth2", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 102);

    // Search with max_depth=1 should return only symbols at depth <= 1
    let options = SearchOptions {
        db_path: &db_path,
        query: "test",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions::default(),
        depth: DepthOptions {
            min_depth: None,
            max_depth: Some(1),
            inside: None,
            contains: None,
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find test_func_depth0 (depth 0) and test_if_depth1 (depth 1)
    // But NOT test_loop_depth2 (depth 2)
    assert!(
        response.results.len() >= 2,
        "Should find at least 2 symbols with depth <= 1"
    );
    let names: Vec<&str> = response.results.iter().map(|r| r.name.as_str()).collect();
    assert!(
        names.contains(&"test_func_depth0"),
        "Should include depth 0 symbol"
    );
    assert!(
        names.contains(&"test_if_depth1"),
        "Should include depth 1 symbol"
    );
}

// Test 4: test_min_max_depth_range
#[test]
fn test_min_max_depth_range() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST nodes at depths 0-4
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 100, 800),
        (101, 100, 'if_expression', 150, 250),   -- depth 1
        (102, 101, 'loop_expression', 160, 240), -- depth 2
        (103, 102, 'match_expression', 170, 230), -- depth 3
        (104, 103, 'if_expression', 180, 220),   -- depth 4
        (105, 100, 'let_declaration', 260, 300)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols with spans matching their corresponding AST nodes
    let ast_node_spans: &[(i64, u64, u64)] = &[
        (100, 100, 800), // function_item
        (101, 150, 250), // if_expression
        (102, 160, 240), // loop_expression
        (103, 170, 230), // match_expression
        (104, 180, 220), // if_expression
    ];
    for &(ast_id, byte_start, byte_end) in ast_node_spans {
        insert_symbol(
            &conn,
            ast_id,
            &format!("depth{}", ast_id - 100),
            "Function",
            file_id,
            byte_start,
            byte_end,
        );
        insert_define_edge(&conn, file_id, ast_id);
    }

    // Search with min_depth=1, max_depth=2
    let options = SearchOptions {
        db_path: &db_path,
        query: "depth",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions::default(),
        depth: DepthOptions {
            min_depth: Some(1),
            max_depth: Some(2),
            inside: None,
            contains: None,
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find depth1 (depth 1) and depth2 (depth 2)
    // But NOT depth0 (depth 0) or depth3/depth4 (depth 3+)
    assert!(
        response.results.len() >= 2,
        "Should find symbols in range [1, 2]"
    );
}

// Test 5: test_inside_function_item
#[test]
fn test_inside_function_item() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST structure: function -> block -> closure_expression
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 0, 100),
        (101, 100, 'block', 10, 90),
        (102, 101, 'closure_expression', 20, 30),
        (103, 101, 'let_declaration', 35, 45),
        (104, NULL, 'function_item', 100, 200),  -- Different function
        (105, 104, 'closure_expression', 110, 120),  -- Closure in different function
        (106, 101, 'call_expression', 50, 60)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols (byte ranges must match AST nodes)
    insert_symbol(
        &conn,
        102,
        "closure_inside_func",
        "Function",
        file_id,
        20,
        30,
    );
    insert_define_edge(&conn, file_id, 102);
    insert_symbol(&conn, 103, "let_inside_func", "Function", file_id, 35, 45);
    insert_define_edge(&conn, file_id, 103);
    insert_symbol(&conn, 105, "closure_other", "Function", file_id, 110, 120);
    insert_define_edge(&conn, file_id, 105);

    // Search for closures inside function_item
    let options = SearchOptions {
        db_path: &db_path,
        query: "closure",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["closure_expression".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions {
            min_depth: None,
            max_depth: None,
            inside: Some("function_item"),
            contains: None,
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find closure_inside_func (inside function with id 100)
    // And closure_other (inside function with id 104)
    // But NOT the let_declaration which is also inside function_item
    assert!(
        response.results.len() >= 2,
        "Should find at least 2 closure_expression nodes inside function_item"
    );

    let names: Vec<&str> = response.results.iter().map(|r| r.name.as_str()).collect();
    assert!(
        names.contains(&"closure_inside_func"),
        "Should find closure in first function"
    );
    assert!(
        names.contains(&"closure_other"),
        "Should find closure in other function"
    );
}

// Test 6: test_inside_block
#[test]
fn test_inside_block() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST structure: function -> block -> let_declaration
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 0, 100),
        (101, 100, 'block', 10, 90),
        (102, 101, 'let_declaration', 20, 30),
        (103, 100, 'let_declaration', 40, 50),  -- Let at function level (not in block)
        (104, 101, 'call_expression', 60, 70)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols (byte ranges must match their corresponding AST nodes)
    insert_symbol(&conn, 102, "let_in_block", "Function", file_id, 20, 30);
    insert_define_edge(&conn, file_id, 102);
    insert_symbol(&conn, 103, "let_at_func_level", "Function", file_id, 40, 50);
    insert_define_edge(&conn, file_id, 103);

    // Search for let_declarations inside block
    let options = SearchOptions {
        db_path: &db_path,
        query: "let",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["let_declaration".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions {
            min_depth: None,
            max_depth: None,
            inside: Some("block"),
            contains: None,
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find let_in_block (inside block)
    // Should NOT find let_at_func_level (direct child of function, not block)
    assert!(
        !response.results.is_empty(),
        "Should find let_declaration inside block"
    );

    let names: Vec<&str> = response.results.iter().map(|r| r.name.as_str()).collect();
    assert!(
        names.contains(&"let_in_block"),
        "Should include let_in_block"
    );
}

// Test 7: test_contains_if_expression
#[test]
fn test_contains_if_expression() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST: function with if_expression child (byte ranges match symbols)
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 0, 100),
        (101, 100, 'if_expression', 10, 50),
        (102, 101, 'let_declaration', 15, 25),
        (200, NULL, 'function_item', 100, 200), -- Function without if
        (201, 200, 'let_declaration', 110, 150),
        (300, NULL, 'function_item', 200, 300), -- Function with multiple if expressions
        (301, 300, 'if_expression', 210, 250),
        (302, 300, 'if_expression', 260, 290)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols
    insert_symbol(&conn, 100, "func_with_if", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 100);
    insert_symbol(&conn, 200, "func_plain", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 200);
    insert_symbol(
        &conn,
        300,
        "func_with_multiple_ifs",
        "Function",
        file_id,
        0,
        100,
    );
    insert_define_edge(&conn, file_id, 300);

    // Search for functions containing if_expression
    let options = SearchOptions {
        db_path: &db_path,
        query: "func",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["function_item".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions {
            min_depth: None,
            max_depth: None,
            inside: None,
            contains: Some("if_expression"),
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find func_with_if and func_with_multiple_ifs
    // Should NOT find func_plain (no if_expression children)
    assert!(
        response.results.len() >= 2,
        "Should find functions containing if_expression"
    );

    let names: Vec<&str> = response.results.iter().map(|r| r.name.as_str()).collect();
    assert!(
        names.contains(&"func_with_if"),
        "Should include func_with_if"
    );
    assert!(
        names.contains(&"func_with_multiple_ifs"),
        "Should include func_with_multiple_ifs"
    );
}

// Test 8: test_contains_multiple_children
#[test]
fn test_contains_multiple_children() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let _conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&_conn, file_id, "src/test.rs");

    // Create AST: function with multiple call_expression children (compact ranges)
    _conn
        .execute(
            "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 0, 100),
        (101, 100, 'call_expression', 10, 20),
        (102, 100, 'call_expression', 30, 40),
        (103, 100, 'call_expression', 50, 60),
        (104, 100, 'let_declaration', 70, 80),
        (200, NULL, 'function_item', 100, 200), -- Function with single call
        (201, 200, 'call_expression', 110, 120),
        (300, NULL, 'function_item', 200, 300), -- Function with no calls
        (301, 300, 'let_declaration', 210, 220)",
            [],
        )
        .expect("insert ast nodes");

    // Insert symbols (byte ranges must match AST nodes)
    insert_symbol(&_conn, 100, "func_many_calls", "Function", file_id, 0, 100);
    insert_define_edge(&_conn, file_id, 100);
    insert_symbol(&_conn, 200, "func_one_call", "Function", file_id, 100, 200);
    insert_define_edge(&_conn, file_id, 200);
    insert_symbol(&_conn, 300, "func_no_calls", "Function", file_id, 200, 300);
    insert_define_edge(&_conn, file_id, 300);

    // Search for functions containing call_expression
    let options = SearchOptions {
        db_path: &db_path,
        query: "func",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["function_item".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions {
            min_depth: None,
            max_depth: None,
            inside: None,
            contains: Some("call_expression"),
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find func_many_calls and func_one_call
    // Should NOT find func_no_calls
    assert!(
        response.results.len() >= 2,
        "Should find functions with call_expression children"
    );

    let names: Vec<&str> = response.results.iter().map(|r| r.name.as_str()).collect();
    assert!(
        names.contains(&"func_many_calls"),
        "Should include func_many_calls"
    );
    assert!(
        names.contains(&"func_one_call"),
        "Should include func_one_call"
    );
}

// Test 9: test_combined_depth_and_inside
#[test]
fn test_combined_depth_and_inside() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create nested structure with varying depths (compact byte ranges)
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 0, 200),      -- func_outer, depth 0
        (101, 100, 'if_expression', 10, 180),      -- depth 1
        (102, 101, 'block', 20, 170),              -- depth 1
        (103, 102, 'closure_expression', 30, 40),  -- depth 1, inside block
        (104, 101, 'if_expression', 50, 100),      -- depth 2
        (105, 104, 'match_expression', 60, 90),    -- depth 3
        (106, 102, 'let_declaration', 110, 120),   -- depth 1
        (107, 100, 'let_declaration', 180, 190),   -- depth 0
        (108, NULL, 'function_item', 200, 400),    -- func_other, depth 0
        (109, 108, 'if_expression', 210, 380),     -- depth 1
        (110, 108, 'let_declaration', 220, 230),    -- depth 1
        (111, 109, 'closure_expression', 240, 250), -- depth 2, inside if
        (112, 109, 'block', 260, 370),             -- depth 1
        (113, 112, 'let_declaration', 270, 280),   -- depth 1
        (114, 112, 'closure_expression', 290, 300), -- depth 1, inside block
        (115, NULL, 'block', 400, 500),            -- orphan block, depth 0
        (116, 115, 'if_expression', 410, 460),     -- depth 1, inside orphan
        (117, 115, 'let_declaration', 470, 480)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols for closures (byte ranges must match AST nodes)
    let closure_ranges: [(i64, u64, u64); 4] = [
        (103, 30, 40),
        (111, 240, 250),
        (114, 290, 300),
        (116, 410, 460),
    ];
    for (ast_id, byte_start, byte_end) in closure_ranges {
        insert_symbol(
            &conn,
            ast_id,
            &format!("closure_{}", ast_id),
            "Function",
            file_id,
            byte_start,
            byte_end,
        );
        insert_define_edge(&conn, file_id, ast_id);
    }

    // Search for closures at depth >= 1 inside function_item
    let options = SearchOptions {
        db_path: &db_path,
        query: "closure",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions {
            ast_kinds: vec!["closure_expression".to_string()],
            with_ast_context: false,
            _phantom: std::marker::PhantomData,
        },
        depth: DepthOptions {
            min_depth: Some(1), // At depth 1 or deeper
            max_depth: None,
            inside: Some("function_item"), // Inside function_item
            contains: None,
        },
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    // Should find:
    // - closure_103 (depth 1, inside block inside func_outer)
    // - closure_111 (depth 2, inside if inside func_other)
    // Should NOT find:
    // - closure_114 (depth 1, inside block inside if, but block is NOT inside function_item directly)
    // - closure_116 (depth 1, inside orphan block, no function parent)
    assert!(
        response.results.len() >= 2,
        "Should find closures at depth >= 1 inside function_item"
    );

    let names: Vec<&str> = response.results.iter().map(|r| r.name.as_str()).collect();
    assert!(names.contains(&"closure_103"), "Should include closure_103");
}

// Test 10: test_backward_compat_no_depth_filter
#[test]
fn test_backward_compat_no_depth_filter() {
    let temp_dir = TempDir::new().expect("tempdir");
    let db_path = temp_dir.path().join("test.db");
    let conn = setup_db_with_ast(&db_path);

    // Insert file
    let file_id = 1i64;
    insert_file(&conn, file_id, "src/test.rs");

    // Create AST nodes (byte ranges must match symbol for exact span JOIN)
    conn.execute(
        "INSERT INTO ast_nodes (id, parent_id, kind, byte_start, byte_end) VALUES
        (100, NULL, 'function_item', 0, 100),
        (101, 100, 'let_declaration', 10, 50),
        (102, 100, 'if_expression', 60, 90)",
        [],
    )
    .expect("insert ast nodes");

    // Insert symbols
    insert_symbol(&conn, 100, "my_function", "Function", file_id, 0, 100);
    insert_define_edge(&conn, file_id, 100);

    // Search without depth flags - should work as before
    let options = SearchOptions {
        db_path: &db_path,
        query: "my_function",
        path_filter: None,
        kind_filter: None,
        limit: 10,
        use_regex: false,
        candidates: 100,
        context: ContextOptions::default(),
        snippet: SnippetOptions::default(),
        fqn: FqnOptions::default(),
        include_score: true,
        sort_by: llmgrep::SortMode::default(),
        metrics: MetricsOptions::default(),
        ast: AstOptions::default(),
        depth: DepthOptions::default(), // No depth filtering
        algorithm: AlgorithmOptions::default(),
        symbol_id: None,
        fqn_pattern: None,
        exact_fqn: None,
        language_filter: None,
        coverage_filter: None,
    };

    let (response, _partial, _) = search_symbols(options).expect("search should succeed");

    assert_eq!(response.results.len(), 1);
    assert_eq!(response.results[0].name, "my_function");
    // ast_context should be present but depth should NOT be populated
    let ast_ctx = response.results[0]
        .ast_context
        .as_ref()
        .expect("ast_context should be present");
    assert_eq!(
        ast_ctx.depth, None,
        "Depth should not be populated without depth filtering or --with-ast-context"
    );
}