tokensave 7.3.0

Code intelligence tool that builds a semantic knowledge graph from Rust, Go, Java, Scala, TypeScript, Python, C, C++, Kotlin, C#, Swift, and many more codebases
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
use tokensave::context::*;
use tokensave::types::*;

#[tokio::test]
async fn test_reranking_demotes_fixture_nodes() {
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    // Fixture node: enum variant in tests/fixtures/
    let fixture_node = Node {
        id: "enum_variant:fixture_debug".to_string(),
        kind: NodeKind::EnumVariant,
        name: "debug".to_string(),
        qualified_name: "tests/fixtures/sample.dart::LogLevel::debug".to_string(),
        file_path: "tests/fixtures/sample.dart".to_string(),
        start_line: 14,
        attrs_start_line: 14,
        end_line: 14,
        start_column: 0,
        end_column: 10,
        signature: Some("debug".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    };
    db.insert_node(&fixture_node).await.unwrap();

    // Source node: function in src/
    let source_node = Node {
        id: "function:debug_handler".to_string(),
        kind: NodeKind::Function,
        name: "debug_handler".to_string(),
        qualified_name: "src/debug.rs::debug_handler".to_string(),
        file_path: "src/debug.rs".to_string(),
        start_line: 1,
        attrs_start_line: 1,
        end_line: 10,
        start_column: 0,
        end_column: 1,
        signature: Some("pub fn debug_handler()".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    };
    db.insert_node(&source_node).await.unwrap();

    let builder = ContextBuilder::new(&db, project);
    let result = builder
        .build_context("debug", &BuildContextOptions::default())
        .await
        .unwrap();

    assert!(!result.entry_points.is_empty());
    assert_eq!(
        result.entry_points[0].id, "function:debug_handler",
        "source function should outrank fixture enum variant after re-ranking"
    );
}

#[test]
fn test_extract_symbols_from_query() {
    let symbols = extract_symbols_from_query("fix the process_request function");
    assert!(symbols.contains(&"process_request".to_string()));
}

#[test]
fn test_extract_camel_case_symbols() {
    let symbols = extract_symbols_from_query("update UserService handler");
    assert!(symbols.contains(&"UserService".to_string()));
}

#[test]
fn test_extract_qualified_symbols() {
    let symbols = extract_symbols_from_query("look at crate::types::Node");
    assert!(symbols.iter().any(|s| s.contains("Node")));
}

#[test]
fn test_extract_screaming_snake_symbols() {
    let symbols = extract_symbols_from_query("increase MAX_RETRIES");
    assert!(symbols.contains(&"MAX_RETRIES".to_string()));
}

#[test]
fn test_extract_no_symbols_from_plain_english() {
    let symbols = extract_symbols_from_query("the is in for to a an");
    assert!(symbols.is_empty());
}

#[test]
fn test_format_context_markdown() {
    let context = TaskContext {
        query: "test query".to_string(),
        summary: "Test summary".to_string(),
        subgraph: Subgraph::default(),
        entry_points: vec![],
        code_blocks: vec![],
        related_files: vec![],
        seen_node_ids: vec![],
    };
    let md = format_context_as_markdown(&context);
    assert!(md.contains("## Code Context"));
    assert!(md.contains("test query"));
}

#[test]
fn test_format_context_json() {
    let context = TaskContext {
        query: "test".to_string(),
        summary: "Summary".to_string(),
        subgraph: Subgraph::default(),
        entry_points: vec![],
        code_blocks: vec![],
        related_files: vec![],
        seen_node_ids: vec![],
    };
    let json = format_context_as_json(&context);
    let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed["query"], "test");
}

#[tokio::test]
async fn test_build_context_with_db() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    // Create a source file
    fs::create_dir_all(project.join("src")).unwrap();
    fs::write(project.join("src/lib.rs"), "pub fn process_data() {}\n").unwrap();

    // Init DB and insert a node
    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();
    let node = Node {
        id: "function:test123".to_string(),
        kind: NodeKind::Function,
        name: "process_data".to_string(),
        qualified_name: "src/lib.rs::process_data".to_string(),
        file_path: "src/lib.rs".to_string(),
        start_line: 1,
        attrs_start_line: 1,
        end_line: 1,
        start_column: 0,
        end_column: 24,
        signature: Some("pub fn process_data()".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    };
    db.insert_node(&node).await.unwrap();

    let builder = ContextBuilder::new(&db, project);
    let result = builder
        .build_context("process_data", &BuildContextOptions::default())
        .await;
    assert!(result.is_ok());
    let ctx = result.unwrap();
    assert!(!ctx.entry_points.is_empty());
}

#[tokio::test]
async fn test_get_code_reads_source_file() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    fs::create_dir_all(project.join("src")).unwrap();
    fs::write(
        project.join("src/main.rs"),
        "fn main() {\n    println!(\"hello\");\n}\n",
    )
    .unwrap();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    let node = Node {
        id: "function:main123".to_string(),
        kind: NodeKind::Function,
        name: "main".to_string(),
        qualified_name: "src/main.rs::main".to_string(),
        file_path: "src/main.rs".to_string(),
        start_line: 0,
        attrs_start_line: 0,
        end_line: 2,
        start_column: 0,
        end_column: 1,
        signature: Some("fn main()".to_string()),
        docstring: None,
        visibility: Visibility::Private,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    };

    let builder = ContextBuilder::new(&db, project);
    let code = builder.get_code(&node).unwrap();
    assert!(code.is_some());
    let content = code.unwrap();
    assert!(content.contains("fn main()"));
    assert!(content.contains("println!"));
}

#[tokio::test]
async fn test_get_code_returns_none_for_missing_file() {
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    let node = Node {
        id: "function:missing".to_string(),
        kind: NodeKind::Function,
        name: "missing".to_string(),
        qualified_name: "nonexistent.rs::missing".to_string(),
        file_path: "nonexistent.rs".to_string(),
        start_line: 1,
        attrs_start_line: 1,
        end_line: 1,
        start_column: 0,
        end_column: 10,
        signature: None,
        docstring: None,
        visibility: Visibility::Private,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    };

    let builder = ContextBuilder::new(&db, project);
    let code = builder.get_code(&node).unwrap();
    assert!(code.is_none());
}

#[tokio::test]
async fn test_find_relevant_context() {
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();
    let node = Node {
        id: "function:ctx_test".to_string(),
        kind: NodeKind::Function,
        name: "compute".to_string(),
        qualified_name: "src/lib.rs::compute".to_string(),
        file_path: "src/lib.rs".to_string(),
        start_line: 1,
        attrs_start_line: 1,
        end_line: 5,
        start_column: 0,
        end_column: 1,
        signature: Some("pub fn compute()".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    };
    db.insert_node(&node).await.unwrap();

    let builder = ContextBuilder::new(&db, project);
    let subgraph = builder
        .find_relevant_context("compute", &BuildContextOptions::default())
        .await
        .unwrap();
    assert!(!subgraph.nodes.is_empty());
}

#[tokio::test]
async fn test_exclude_node_ids_deduplication() {
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    for (id, name) in [("fn:first", "compute"), ("fn:second", "compute_batch")] {
        db.insert_node(&Node {
            id: id.to_string(),
            kind: NodeKind::Function,
            name: name.to_string(),
            qualified_name: format!("src/lib.rs::{name}"),
            file_path: "src/lib.rs".to_string(),
            start_line: 1,
            attrs_start_line: 1,
            end_line: 5,
            start_column: 0,
            end_column: 1,
            signature: Some(format!("pub fn {name}()")),
            docstring: None,
            visibility: Visibility::Pub,
            is_async: false,
            branches: 0,
            loops: 0,
            returns: 0,
            max_nesting: 0,
            unsafe_blocks: 0,
            unchecked_calls: 0,
            assertions: 0,
            cognitive_complexity: 0,
            distinct_operators: 0,
            distinct_operands: 0,
            total_operators: 0,
            total_operands: 0,
            updated_at: 0,
            parent_id: None,
        })
        .await
        .unwrap();
    }

    let builder = ContextBuilder::new(&db, project);

    // First call — fn:first should appear
    let opts = BuildContextOptions::default();
    let ctx1 = builder.build_context("compute", &opts).await.unwrap();
    assert!(ctx1.entry_points.iter().any(|n| n.id == "fn:first"));

    // Second call — exclude fn:first
    let opts2 = BuildContextOptions {
        exclude_node_ids: vec!["fn:first".to_string()].into_iter().collect(),
        ..Default::default()
    };
    let ctx2 = builder.build_context("compute", &opts2).await.unwrap();
    assert!(
        !ctx2.entry_points.iter().any(|n| n.id == "fn:first"),
        "excluded node should not appear in second call"
    );
}

#[tokio::test]
async fn test_exact_name_match_wins_max_merge() {
    // Regression for #117: a node that matches BOTH an FTS term (with a tiny
    // BM25 score) and the exact-name lookup must carry the exact-match base
    // score, not the low FTS score it happened to be seen with first.
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    // Exact-match target: a low-boost node (enum variant, private). Without the
    // exact-match score it would rank dead last after structural re-ranking.
    // Name is camelCase so the query token is extracted as a symbol (a plain
    // lowercase word is not), which is what feeds the exact-name lookup.
    db.insert_node(&Node {
        id: "variant:validate".to_string(),
        kind: NodeKind::EnumVariant,
        name: "validateInput".to_string(),
        qualified_name: "src/lib.rs::Action::validateInput".to_string(),
        file_path: "src/lib.rs".to_string(),
        start_line: 1,
        attrs_start_line: 1,
        end_line: 1,
        start_column: 0,
        end_column: 10,
        signature: Some("validateInput".to_string()),
        docstring: None,
        visibility: Visibility::Private,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    })
    .await
    .unwrap();

    // Competitor: a high-boost node (public function) that only matches the FTS
    // "validate" prefix term, never the exact symbol names. Its structural boost
    // dwarfs the enum variant's, so under the old first-seen bug it ranks first.
    db.insert_node(&Node {
        id: "fn:validate_helper".to_string(),
        kind: NodeKind::Function,
        name: "validateRequest".to_string(),
        qualified_name: "src/lib.rs::validateRequest".to_string(),
        file_path: "src/lib.rs".to_string(),
        start_line: 2,
        attrs_start_line: 2,
        end_line: 6,
        start_column: 0,
        end_column: 1,
        signature: Some("pub fn validateRequest()".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    })
    .await
    .unwrap();

    let builder = ContextBuilder::new(&db, project);

    // Both nodes match the "validate" FTS term; only validateInput is an exact
    // name match for the query's extracted symbols.
    let ctx = builder
        .build_context("validateInput", &BuildContextOptions::default())
        .await
        .unwrap();

    // The exact-match node must carry the high base score and rank first,
    // despite its much weaker structural boost.
    assert_eq!(
        ctx.entry_points.first().map(|n| n.id.as_str()),
        Some("variant:validate"),
        "exact-name match should rank first via MAX-merge, not be buried by BM25"
    );

    // Excluding the exact-match node must still keep it out entirely.
    let opts_excl = BuildContextOptions {
        exclude_node_ids: vec!["variant:validate".to_string()].into_iter().collect(),
        ..Default::default()
    };
    let ctx_excl = builder
        .build_context("validateInput", &opts_excl)
        .await
        .unwrap();
    assert!(
        !ctx_excl
            .entry_points
            .iter()
            .any(|n| n.id == "variant:validate"),
        "excluded node must not reappear via the exact-name supplement"
    );
}

#[tokio::test]
async fn test_query_ignore_filters_context_entry_points() {
    use tempfile::TempDir;
    use tokensave::config::{load_query_ignore, QueryIgnore};
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    // Two nodes with the same searchable name in different directories.
    for (id, file) in [
        ("fn:src", "src/widget.rs"),
        ("fn:gen", "generated/widget.rs"),
    ] {
        db.insert_node(&Node {
            id: id.to_string(),
            kind: NodeKind::Function,
            name: "widget".to_string(),
            qualified_name: format!("{file}::widget"),
            file_path: file.to_string(),
            start_line: 1,
            attrs_start_line: 1,
            end_line: 5,
            start_column: 0,
            end_column: 1,
            signature: Some("pub fn widget()".to_string()),
            docstring: None,
            visibility: Visibility::Pub,
            is_async: false,
            branches: 0,
            loops: 0,
            returns: 0,
            max_nesting: 0,
            unsafe_blocks: 0,
            unchecked_calls: 0,
            assertions: 0,
            cognitive_complexity: 0,
            distinct_operators: 0,
            distinct_operands: 0,
            total_operators: 0,
            total_operands: 0,
            updated_at: 0,
            parent_id: None,
        })
        .await
        .unwrap();
    }

    let builder = ContextBuilder::new(&db, project);

    // Without an ignore file, both nodes are reachable.
    let opts = BuildContextOptions::default();
    let ctx = builder.build_context("widget", &opts).await.unwrap();
    assert!(ctx.entry_points.iter().any(|n| n.id == "fn:gen"));

    // With a matching queryignore pattern, the generated node is filtered out.
    let ts_dir = project.join(".tokensave");
    std::fs::write(ts_dir.join("queryignore"), "generated\n").unwrap();
    let query_ignore = load_query_ignore(project);
    assert!(!query_ignore.is_empty());

    let opts_ignored = BuildContextOptions {
        query_ignore,
        ..Default::default()
    };
    let ctx_ignored = builder
        .build_context("widget", &opts_ignored)
        .await
        .unwrap();
    assert!(
        !ctx_ignored.entry_points.iter().any(|n| n.id == "fn:gen"),
        "queryignore-matched node should not appear as an entry point"
    );
    assert!(
        ctx_ignored.entry_points.iter().any(|n| n.id == "fn:src"),
        "non-matching node should still appear"
    );

    // Sanity: an empty QueryIgnore matches nothing.
    assert!(!QueryIgnore::default().is_ignored("generated/widget.rs"));
}

#[tokio::test]
async fn test_merge_adjacent_code_blocks() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("src")).unwrap();
    fs::write(
        project.join("src/lib.rs"),
        "fn alpha() {}\n\nfn beta() {}\n\nfn gamma() {}\n",
    )
    .unwrap();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    // Two adjacent functions in same file
    db.insert_node(&Node {
        id: "fn:alpha".to_string(),
        kind: NodeKind::Function,
        name: "alpha".to_string(),
        qualified_name: "src/lib.rs::alpha".to_string(),
        file_path: "src/lib.rs".to_string(),
        start_line: 0,
        attrs_start_line: 0,
        end_line: 0,
        start_column: 0,
        end_column: 13,
        signature: Some("fn alpha()".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    })
    .await
    .unwrap();

    db.insert_node(&Node {
        id: "fn:beta".to_string(),
        kind: NodeKind::Function,
        name: "beta".to_string(),
        qualified_name: "src/lib.rs::beta".to_string(),
        file_path: "src/lib.rs".to_string(),
        start_line: 2,
        attrs_start_line: 2,
        end_line: 2,
        start_column: 0,
        end_column: 12,
        signature: Some("fn beta()".to_string()),
        docstring: None,
        visibility: Visibility::Pub,
        is_async: false,
        branches: 0,
        loops: 0,
        returns: 0,
        max_nesting: 0,
        unsafe_blocks: 0,
        unchecked_calls: 0,
        assertions: 0,
        cognitive_complexity: 0,
        distinct_operators: 0,
        distinct_operands: 0,
        total_operators: 0,
        total_operands: 0,
        updated_at: 0,
        parent_id: None,
    })
    .await
    .unwrap();

    let builder = ContextBuilder::new(&db, project);
    let ctx = builder
        .build_context(
            "alpha beta",
            &BuildContextOptions {
                include_code: true,
                merge_adjacent: true,
                max_code_blocks: 10,
                ..Default::default()
            },
        )
        .await
        .unwrap();

    // With merge_adjacent, the two adjacent blocks should merge into one
    assert_eq!(
        ctx.code_blocks.len(),
        1,
        "adjacent blocks should merge into one, got {}",
        ctx.code_blocks.len()
    );
    assert!(ctx.code_blocks[0].content.contains("alpha"));
    assert!(ctx.code_blocks[0].content.contains("beta"));
}

#[tokio::test]
async fn test_entry_points_capped_to_search_limit() {
    // Regression test for #120: when many candidates match, the number of
    // entry points (BFS roots) must be bounded by `search_limit` so each
    // root's traversal budget stays meaningful.
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::db::Database;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("src")).unwrap();

    let (db, _) = Database::initialize(&project.join(".tokensave/tokensave.db"))
        .await
        .unwrap();

    // Insert many distinct nodes, each matching a distinct keyword. Each
    // per-keyword FTS search surfaces its node, so the candidate pool greatly
    // exceeds `search_limit`.
    const NUM_NODES: usize = 12;
    let keywords: Vec<String> = (0..NUM_NODES).map(|i| format!("widgetkind{i}")).collect();
    let mut nodes = Vec::new();
    for (i, kw) in keywords.iter().enumerate() {
        nodes.push(Node {
            id: format!("function:{kw}"),
            kind: NodeKind::Function,
            name: kw.clone(),
            qualified_name: format!("src/file{i}.rs::{kw}"),
            file_path: format!("src/file{i}.rs"),
            start_line: 1,
            attrs_start_line: 1,
            end_line: 5,
            start_column: 0,
            end_column: 1,
            signature: Some(format!("pub fn {kw}()")),
            docstring: None,
            visibility: Visibility::Pub,
            is_async: false,
            branches: 0,
            loops: 0,
            returns: 0,
            max_nesting: 0,
            unsafe_blocks: 0,
            unchecked_calls: 0,
            assertions: 0,
            cognitive_complexity: 0,
            distinct_operators: 0,
            distinct_operands: 0,
            total_operators: 0,
            total_operands: 0,
            updated_at: 0,
            parent_id: None,
        });
    }
    db.insert_nodes(&nodes).await.unwrap();

    const SEARCH_LIMIT: usize = 5;
    let opts = BuildContextOptions {
        search_limit: SEARCH_LIMIT,
        max_nodes: 100, // large, so search_limit is the binding cap on roots
        max_per_file: Some(100),
        extra_keywords: keywords.clone(),
        ..Default::default()
    };

    let builder = ContextBuilder::new(&db, project);
    // Query the first keyword; the rest surface via extra_keywords, producing
    // far more candidates than `search_limit`.
    let ctx = builder.build_context(&keywords[0], &opts).await.unwrap();

    assert!(
        ctx.entry_points.len() > 1,
        "expected multiple matching candidates, got {}",
        ctx.entry_points.len()
    );
    assert!(
        ctx.entry_points.len() <= SEARCH_LIMIT,
        "entry points (BFS roots) must be capped to search_limit ({}), got {}",
        SEARCH_LIMIT,
        ctx.entry_points.len()
    );
}

#[tokio::test]
async fn exact_qualified_expression_seeds_every_enclosing_symbol() {
    use std::collections::HashSet;
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::tokensave::TokenSave;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("crates/sonium-bem/src")).unwrap();
    fs::create_dir_all(project.join("crates/sonium-qa/tests")).unwrap();
    fs::create_dir_all(project.join("crates/unrelated/src")).unwrap();
    fs::write(
        project.join("crates/sonium-bem/src/linear.rs"),
        r#"
pub enum BasisOrder { Linear, Quadratic }

pub fn standard_assembly(order: BasisOrder) {
    if matches!(order, BasisOrder::Linear) {}
}

pub fn stabilized_assembly(order: BasisOrder) {
    if matches!(order, BasisOrder::Linear) {}
}

pub fn incident_rhs(order: BasisOrder) {
    if matches!(order, BasisOrder::Linear) {}
}

pub fn validate_backend(order: BasisOrder) {
    if matches!(order, BasisOrder::Linear) {}
}
"#,
    )
    .unwrap();
    fs::write(
        project.join("crates/sonium-qa/tests/linear_regression.rs"),
        r#"
pub fn physical_pressure() {
    let order = BasisOrder::Linear;
    export(order);
}

#[test]
fn linear_regression() {
    let order = BasisOrder::Linear;
    assert_supported(order);
}
"#,
    )
    .unwrap();
    fs::write(
        project.join("crates/unrelated/src/ignored.rs"),
        "pub fn excluded_path() { let _ = BasisOrder::Linear; }\n",
    )
    .unwrap();

    let cg = TokenSave::init(project).await.unwrap();
    cg.index_all().await.unwrap();
    let builder = ContextBuilder::new(cg.db(), project);
    let context = builder
        .build_context(
            "Find every code path specific to BasisOrder::Linear, including assembly, validation, output, and regression tests.",
            &BuildContextOptions {
                max_nodes: 10,
                search_limit: 2,
                max_per_file: Some(2),
                extra_keywords: vec!["BasisOrder::Linear".to_string()],
                path_include: vec![
                    "crates/sonium-bem".to_string(),
                    "crates/sonium-qa".to_string(),
                ],
                ..Default::default()
            },
        )
        .await
        .unwrap();

    let names: HashSet<&str> = context
        .entry_points
        .iter()
        .map(|node| node.name.as_str())
        .collect();
    let expected = HashSet::from([
        "standard_assembly",
        "stabilized_assembly",
        "incident_rhs",
        "validate_backend",
        "physical_pressure",
        "linear_regression",
    ]);
    assert!(
        expected.is_subset(&names),
        "entry points: {:?}",
        context.entry_points
    );
    assert!(context.entry_points.len() <= expected.len() + 2);
    assert_eq!(context.seen_node_ids.len(), context.entry_points.len());
    assert!(!names.contains("excluded_path"));
}

#[tokio::test]
async fn conceptual_context_discovers_executable_body_owner() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::tokensave::TokenSave;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("src")).unwrap();
    fs::write(
        project.join("src/solver.rs"),
        r#"
pub fn run_policy(frequencies: &[f64]) {
    let mut preconditioner_cache = None;
    for frequency in frequencies {
        let retry = preconditioner_cache.is_none();
        if retry {
            preconditioner_cache = Some(*frequency);
        }
        let residual = frequency.abs();
        record_diagnostics(residual);
    }
}

fn record_diagnostics(_residual: f64) {}
"#,
    )
    .unwrap();

    let cg = TokenSave::init(project).await.unwrap();
    cg.index_all().await.unwrap();
    let builder = ContextBuilder::new(cg.db(), project);
    let context = builder
        .build_context(
            "frequency retry preconditioner cache diagnostics residual",
            &BuildContextOptions {
                search_limit: 5,
                max_nodes: 20,
                ..Default::default()
            },
        )
        .await
        .unwrap();

    assert!(
        context
            .entry_points
            .iter()
            .any(|node| node.name == "run_policy"),
        "behavioral owner should be discoverable from body concepts; got {:?}",
        context
            .entry_points
            .iter()
            .map(|node| &node.name)
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn conceptual_context_associates_local_control_flow_with_owner() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::tokensave::TokenSave;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("src")).unwrap();
    fs::write(
        project.join("src/runner.rs"),
        r#"
pub fn execute(frequencies: &[f64]) {
    let mut cached_precond = None;
    let rebuild_every = 8;
    for (freq_idx, frequency) in frequencies.iter().enumerate() {
        let must_rebuild = cached_precond.is_none() || freq_idx % rebuild_every == 0;
        if must_rebuild {
            cached_precond = Some(*frequency);
        }
    }
}

"#,
    )
    .unwrap();

    let cg = TokenSave::init(project).await.unwrap();
    cg.index_all().await.unwrap();
    let builder = ContextBuilder::new(cg.db(), project);
    let context = builder
        .build_context(
            "preconditioner cache rebuild",
            &BuildContextOptions {
                search_limit: 5,
                max_nodes: 20,
                ..Default::default()
            },
        )
        .await
        .unwrap();

    assert!(
        context
            .entry_points
            .iter()
            .any(|node| node.name == "execute"),
        "local branch identifiers should retrieve their executable owner"
    );
}

#[tokio::test]
async fn requested_type_expands_to_its_behavioral_api() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::tokensave::TokenSave;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("src")).unwrap();
    fs::write(
        project.join("src/source.rs"),
        r#"
pub struct Source {
    gain: f64,
}

impl Source {
    pub fn amplitude_towards(&self, angle: f64) -> f64 {
        self.gain * angle.cos()
    }

    pub fn polar_weight(&self, angle: f64) -> f64 {
        self.gain * angle.sin()
    }
}
"#,
    )
    .unwrap();

    let cg = TokenSave::init(project).await.unwrap();
    cg.index_all().await.unwrap();
    let builder = ContextBuilder::new(cg.db(), project);
    let context = builder
        .build_context(
            "Source behavior",
            &BuildContextOptions {
                search_limit: 10,
                max_nodes: 20,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    let names: Vec<_> = context
        .entry_points
        .iter()
        .map(|node| node.name.as_str())
        .collect();

    assert!(
        names.contains(&"amplitude_towards"),
        "entry points: {names:?}"
    );
    assert!(names.contains(&"polar_weight"), "entry points: {names:?}");
}

#[tokio::test]
async fn executable_body_index_is_replaced_by_incremental_sync() {
    use std::fs;
    use tempfile::TempDir;
    use tokensave::context::ContextBuilder;
    use tokensave::tokensave::TokenSave;

    let dir = TempDir::new().unwrap();
    let project = dir.path();
    fs::create_dir_all(project.join("src")).unwrap();
    let source_path = project.join("src/policy.rs");
    fs::write(
        &source_path,
        "pub fn policy() { let cached_precond = true; let must_rebuild = cached_precond; }\n",
    )
    .unwrap();

    let cg = TokenSave::init(project).await.unwrap();
    cg.index_all().await.unwrap();
    let options = BuildContextOptions {
        search_limit: 5,
        max_nodes: 20,
        ..Default::default()
    };
    let builder = ContextBuilder::new(cg.db(), project);
    let before = builder
        .build_context("preconditioner rebuild", &options)
        .await
        .unwrap();
    assert!(before.entry_points.iter().any(|node| node.name == "policy"));

    fs::write(
        &source_path,
        "pub fn policy() { let session_rotation = true; let renew_credentials = session_rotation; }\n",
    )
    .unwrap();
    cg.sync().await.unwrap();

    let old_terms = builder
        .build_context("preconditioner rebuild", &options)
        .await
        .unwrap();
    assert!(!old_terms
        .entry_points
        .iter()
        .any(|node| node.name == "policy"));
    let new_terms = builder
        .build_context("session rotation credentials renewal", &options)
        .await
        .unwrap();
    assert!(new_terms
        .entry_points
        .iter()
        .any(|node| node.name == "policy"));
}