tokensave 7.0.3

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
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: 1,
        attrs_start_line: 1,
        end_line: 3,
        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: 1,
        attrs_start_line: 1,
        end_line: 1,
        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: 3,
        attrs_start_line: 3,
        end_line: 3,
        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()
    );
}