ochna 0.3.1

A structural code graph indexing and analysis CLI using Tree-sitter and SQLite
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
//! CLI subcommand implementations, split by concern:
//! - [`index`] — the `init`/`sync` indexing pipeline.
//! - [`status`] — read-only `status`/`files` inspection.
//! - [`query`] — `search`/`callers`/`node`/`explore` graph queries.

mod diff;
mod index;
mod query;
mod status;

pub use diff::run_diff;
pub use index::run_init;
pub(crate) use index::{discover_source_files, language_for_path};
pub(crate) use query::run_impact;
pub use query::{
    run_callees, run_callers, run_explore, run_howto, run_node, run_search, run_tests_for,
};
pub use status::{run_doctor, run_files, run_status, run_unresolved};

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db;
    use rusqlite::Connection;
    use std::fs;
    use std::path::PathBuf;

    fn create_temp_dir() -> PathBuf {
        use std::sync::atomic::{AtomicUsize, Ordering};
        use std::time::{SystemTime, UNIX_EPOCH};
        static COUNTER: AtomicUsize = AtomicUsize::new(0);
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let count = COUNTER.fetch_add(1, Ordering::SeqCst);
        let path = std::env::temp_dir().join(format!("ochna_test_{}_{}", now, count));
        fs::create_dir_all(&path).unwrap();
        path
    }

    #[test]
    fn test_commands_workflow() {
        let temp_workspace = create_temp_dir();

        // 1. Create a sub-directory and some mock files
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        let rust_file = src_dir.join("main.rs");
        let rust_code = r#"
            /// A main entry point.
            fn main() {
                helper();
            }

            fn helper() {
                println!("hello");
            }
        "#;
        fs::write(&rust_file, rust_code).unwrap();

        let go_file = temp_workspace.join("main.go");
        let go_code = r#"
            package main
            import "fmt"

            // GoHelper function
            func GoHelper() {
                fmt.Println("go helper")
            }
        "#;
        fs::write(&go_file, go_code).unwrap();

        let c_file = temp_workspace.join("main.c");
        let c_code = r#"
            int c_helper(void) {
                return 1;
            }
        "#;
        fs::write(&c_file, c_code).unwrap();

        let cpp_file = temp_workspace.join("main.cpp");
        let cpp_code = r#"
            int cpp_helper() {
                return 2;
            }
        "#;
        fs::write(&cpp_file, cpp_code).unwrap();

        let zig_file = temp_workspace.join("main.zig");
        let zig_code = r#"
            fn zigHelper() i32 {
                return 3;
            }
        "#;
        fs::write(&zig_file, zig_code).unwrap();

        // Let's create an ignored directory/file to ensure they are skipped
        let ignored_dir = temp_workspace.join(".git");
        fs::create_dir_all(&ignored_dir).unwrap();
        fs::write(ignored_dir.join("config"), "dummy content").unwrap();

        let target_dir = temp_workspace.join("target");
        fs::create_dir_all(&target_dir).unwrap();
        fs::write(target_dir.join("binary.rs"), "dummy rust in target").unwrap();

        // 2. Run run_init
        run_init(&temp_workspace, false).unwrap();

        // Verify .ochna/ochna.db was created
        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        assert!(db_path.exists());
        let agent_pointer = temp_workspace.join(".ochna").join("AGENT.md");
        assert!(agent_pointer.exists());
        let pointer_text = fs::read_to_string(&agent_pointer).unwrap();
        assert!(pointer_text.contains("generated by ochna init"));
        assert!(pointer_text.contains("ochna howto"));

        // Verify status fetches expected data
        let conn = Connection::open(&db_path).unwrap();
        let files_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM files", [], |row| row.get(0))
            .unwrap();
        let nodes_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes", [], |row| row.get(0))
            .unwrap();

        // files should only contain supported source files outside ignored directories.
        assert_eq!(files_count, 5);
        // nodes:
        // rust: "main" (function), "helper" (function) -> 2 nodes
        // go: "GoHelper" (function) -> 1 node
        // c: "c_helper" (function) -> 1 node
        // cpp: "cpp_helper" (function) -> 1 node
        // zig: "zigHelper" (function) -> 1 node
        // Total nodes: 6
        assert_eq!(nodes_count, 6);

        // Run status command and verify it succeeds (text + json)
        run_status(&temp_workspace, false).unwrap();
        run_status(&temp_workspace, true).unwrap();
        run_howto(false).unwrap();
        run_howto(true).unwrap();

        // Run files command and verify it succeeds (text + json)
        run_files(&temp_workspace, false).unwrap();
        run_files(&temp_workspace, true).unwrap();

        // Verify new query commands query the SQLite database successfully and print expected output formats
        run_search(&temp_workspace, "helper", false, false, 30).unwrap();
        run_search(&temp_workspace, "helper", true, false, 30).unwrap();
        run_callers(&temp_workspace, "helper", false, false, None, false, None).unwrap();
        run_callers(&temp_workspace, "helper", true, false, None, false, None).unwrap();
        run_callees(&temp_workspace, "helper", false, false, None, false, None).unwrap();
        run_callees(&temp_workspace, "helper", true, false, None, false, None).unwrap();
        // Test --in path filter
        run_callers(
            &temp_workspace,
            "helper",
            false,
            false,
            None,
            false,
            Some("src"),
        )
        .unwrap();
        run_callees(
            &temp_workspace,
            "helper",
            false,
            false,
            None,
            false,
            Some("src"),
        )
        .unwrap();

        // Test run_node with file (symbols_only = false)
        run_node(
            &temp_workspace,
            Some("src/main.rs".to_string()),
            Some(1),
            Some(10),
            false,
            None,
            false,
            None,
            false,
            false,
            false,
        )
        .unwrap();
        // Test run_node with file (symbols_only = true)
        run_node(
            &temp_workspace,
            Some("src/main.rs".to_string()),
            None,
            None,
            true,
            None,
            false,
            None,
            false,
            false,
            false,
        )
        .unwrap();
        // Test run_node with symbol (include_code = true)
        run_node(
            &temp_workspace,
            None,
            None,
            None,
            false,
            Some("helper".to_string()),
            true,
            None,
            false,
            false,
            false,
        )
        .unwrap();
        // Test run_node with symbol (include_code = true, JSON output)
        run_node(
            &temp_workspace,
            None,
            None,
            None,
            false,
            Some("helper".to_string()),
            true,
            None,
            true,
            false,
            false,
        )
        .unwrap();
        // Test run_node with symbol (include_code = true and line filtering)
        run_node(
            &temp_workspace,
            None,
            None,
            None,
            false,
            Some("helper".to_string()),
            true,
            Some(6),
            false,
            false,
            false,
        )
        .unwrap();

        // Test run_explore (text + json)
        run_explore(&temp_workspace, "helper", false, false, false).unwrap();
        run_explore(&temp_workspace, "helper", true, false, false).unwrap();

        // 3. Modify a file and check that re-indexing works
        let rust_code_modified = r#"
            /// Modified main entry point.
            fn main() {
                // calls deleted helper
            }
        "#;
        fs::write(&rust_file, rust_code_modified).unwrap();

        // FileMetadata updates
        run_init(&temp_workspace, false).unwrap();

        let nodes_count_after: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes", [], |row| row.get(0))
            .unwrap();
        // Now rust file has 1 node ("main"). Other source files retain one node each.
        assert_eq!(nodes_count_after, 5);

        // Clean up temporary workspace
        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_status_json_fails_when_git_baseline_is_stale() {
        let temp_workspace = create_temp_dir();
        fs::write(temp_workspace.join(".gitignore"), ".ochna\n").unwrap();
        fs::write(temp_workspace.join("main.rs"), "fn first() {}\n").unwrap();

        std::process::Command::new("git")
            .args(["init"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.email", "ochna@example.invalid"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.name", "Ochna Test"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["add", ".gitignore", "main.rs"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "test baseline"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();

        run_init(&temp_workspace, false).unwrap();
        run_status(&temp_workspace, true).unwrap();

        fs::write(temp_workspace.join("main.rs"), "fn second() {}\n").unwrap();
        let err = run_status(&temp_workspace, true).unwrap_err();
        assert!(err.to_string().contains("ochna sync"));

        // Clean up temporary workspace
        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_status_json_fresh_immediately_after_init_on_dirty_worktree() {
        let temp_workspace = create_temp_dir();
        fs::write(temp_workspace.join(".gitignore"), ".ochna\n").unwrap();
        fs::write(temp_workspace.join("main.rs"), "fn first() {}\n").unwrap();

        std::process::Command::new("git")
            .args(["init"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.email", "ochna@example.invalid"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.name", "Ochna Test"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["add", ".gitignore", "main.rs"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "test baseline"])
            .current_dir(&temp_workspace)
            .output()
            .unwrap();

        // Change main.rs on disk without committing, so the working tree is
        // git-dirty relative to HEAD *before* indexing. init/status must
        // still report fresh right after, because ochna's freshness is
        // "does the index match disk", not "is the git working tree clean".
        fs::write(temp_workspace.join("main.rs"), "fn second() {}\n").unwrap();
        run_init(&temp_workspace, false).unwrap();
        run_status(&temp_workspace, true).unwrap();

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_cross_file_edges_and_unresolved() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // a.rs calls target() (defined in b.rs) and missing() (defined nowhere).
        fs::write(
            src_dir.join("a.rs"),
            "fn caller() {\n    target();\n    missing();\n}\n",
        )
        .unwrap();
        fs::write(src_dir.join("b.rs"), "fn target() {}\n").unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();

        // A call edge must cross the file boundary: src/a.rs::caller -> src/b.rs::target.
        let cross_file: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges e \
                 JOIN nodes s ON e.source_nid = s.nid \
                 JOIN nodes t ON e.target_nid = t.nid \
                 WHERE s.file_path <> t.file_path",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(cross_file, 1, "expected one cross-file call edge");

        // The call to an unindexed symbol must be recorded as an unresolved reference.
        let unresolved: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM unresolved_refs WHERE specifier = 'missing'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(unresolved, 1, "expected one unresolved reference");

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_scope_classification_tags_tests_and_skips_libraries() {
        let temp_workspace = create_temp_dir();
        fs::create_dir_all(temp_workspace.join("src/test/java")).unwrap();
        fs::create_dir_all(temp_workspace.join("tests")).unwrap();
        fs::create_dir_all(temp_workspace.join("vendor")).unwrap();
        fs::create_dir_all(temp_workspace.join("target")).unwrap();

        fs::write(temp_workspace.join("src/main.rs"), "fn app_main() {}\n").unwrap();
        fs::write(
            temp_workspace.join("tests/parser.rs"),
            "fn parser_test() {}\n",
        )
        .unwrap();
        fs::write(
            temp_workspace.join("client_test.go"),
            "package main\nfunc TestClient() {}\n",
        )
        .unwrap();
        fs::write(
            temp_workspace.join("src/test/java/AppTest.java"),
            "public class AppTest { public void runs() {} }\n",
        )
        .unwrap();
        fs::write(temp_workspace.join("vendor/lib.rs"), "fn vendored() {}\n").unwrap();
        fs::write(
            temp_workspace.join("target/generated.rs"),
            "fn generated() {}\n",
        )
        .unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();
        let files_count: i64 = conn
            .query_row("SELECT COUNT(*) FROM files", [], |row| row.get(0))
            .unwrap();
        assert_eq!(files_count, 4, "library directories should be skipped");

        let test_files: i64 = conn
            .query_row("SELECT COUNT(*) FROM files WHERE is_test = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert_eq!(test_files, 3);

        let test_nodes: i64 = conn
            .query_row("SELECT COUNT(*) FROM nodes WHERE is_test = 1", [], |row| {
                row.get(0)
            })
            .unwrap();
        assert!(test_nodes >= 3);

        run_init(&temp_workspace, true).unwrap();
        let library_files: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM files WHERE file_path IN ('vendor/lib.rs', 'target/generated.rs')",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            library_files, 2,
            "--include-library should index library dirs"
        );

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_fresh_init_rebuilds_fts_index() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(
            src_dir.join("main.rs"),
            "/// Performs a searchable calibration.\nfn calibrate() {}\n",
        )
        .unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();
        let fts_results = db::search_nodes_fts(&conn, "calibration").unwrap();
        assert_eq!(fts_results.len(), 1);
        assert_eq!(fts_results[0].name, "calibrate");

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_incremental_sync_keeps_fts_triggers_after_fresh_rebuild() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();
        let rust_file = src_dir.join("main.rs");
        fs::write(
            &rust_file,
            "/// Mentions the original marker.\nfn searchable() {}\n",
        )
        .unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();
        assert_eq!(db::search_nodes_fts(&conn, "original").unwrap().len(), 1);

        fs::write(
            &rust_file,
            "/// Mentions the replacement marker.\nfn searchable() {}\n",
        )
        .unwrap();
        run_init(&temp_workspace, false).unwrap();

        assert_eq!(db::search_nodes_fts(&conn, "replacement").unwrap().len(), 1);
        assert!(
            db::search_nodes_fts(&conn, "original").unwrap().is_empty(),
            "updated file should remove stale FTS content"
        );

        fs::remove_file(&rust_file).unwrap();
        run_init(&temp_workspace, false).unwrap();

        assert!(
            db::search_nodes_fts(&conn, "replacement")
                .unwrap()
                .is_empty(),
            "deleted file should remove FTS content"
        );

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_incremental_sync_re_resolves_unmodified_incoming_callers() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();
        let caller_file = src_dir.join("a.rs");
        let old_target_file = src_dir.join("b.rs");
        let new_target_file = src_dir.join("c.rs");
        fs::write(
            &caller_file,
            "fn caller() {\n    target();\n    local_keep();\n}\nfn local_keep() {}\n",
        )
        .unwrap();
        fs::write(
            src_dir.join("incoming.rs"),
            "fn incoming() {\n    caller();\n}\n",
        )
        .unwrap();
        fs::write(&old_target_file, "fn target() {}\n").unwrap();

        run_init(&temp_workspace, false).unwrap();

        fs::write(&old_target_file, "fn other() {}\n").unwrap();
        fs::write(&new_target_file, "fn target() {}\n").unwrap();
        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();
        let moved_edge: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges
                 WHERE source_nid = (SELECT nid FROM nodes WHERE id = 'src/a.rs::caller')
                   AND target_nid = (SELECT nid FROM nodes WHERE id = 'src/c.rs::target')",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            moved_edge, 1,
            "unmodified caller should point at new target"
        );

        let stale_edge: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges
                 WHERE source_nid = (SELECT nid FROM nodes WHERE id = 'src/a.rs::caller')
                   AND target_nid = (SELECT nid FROM nodes WHERE id = 'src/b.rs::target')",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(stale_edge, 0, "stale target edge should be removed");

        let preserved_edge: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges
                 WHERE source_nid = (SELECT nid FROM nodes WHERE id = 'src/a.rs::caller')
                   AND target_nid = (SELECT nid FROM nodes WHERE id = 'src/a.rs::local_keep')",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            preserved_edge, 1,
            "other edges from the source are reinserted"
        );
        let preserved_incoming_edge: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges
                 WHERE source_nid = (SELECT nid FROM nodes WHERE id = 'src/incoming.rs::incoming')
                   AND target_nid = (SELECT nid FROM nodes WHERE id = 'src/a.rs::caller')",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(
            preserved_incoming_edge, 1,
            "replaying a caller must not delete unrelated incoming edges"
        );

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_incremental_sync_re_resolves_matching_unresolved_refs() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(src_dir.join("a.rs"), "fn caller() {\n    missing();\n}\n").unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();
        let unresolved_before: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM unresolved_refs WHERE specifier = 'missing'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(unresolved_before, 1);

        fs::write(src_dir.join("b.rs"), "fn missing() {}\n").unwrap();
        run_init(&temp_workspace, false).unwrap();

        let resolved_edge: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM edges
                 WHERE source_nid = (SELECT nid FROM nodes WHERE id = 'src/a.rs::caller')
                   AND target_nid = (SELECT nid FROM nodes WHERE id = 'src/b.rs::missing')",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(resolved_edge, 1);

        let unresolved_after: i64 = conn
            .query_row(
                "SELECT COUNT(*) FROM unresolved_refs WHERE specifier = 'missing'",
                [],
                |row| row.get(0),
            )
            .unwrap();
        assert_eq!(unresolved_after, 0);

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_call_resolution_baseline_fixtures() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // 1. Go Fixtures
        let go_code = r#"
            package main
            
            type Cacher struct {}
            func (c *Cacher) GetList() {}
            func (c *Cacher) Add() {}
            func (c *Cacher) Run() {}
            
            type Queue struct {}
            func (q *Queue) GetList() {}
            func (q *Queue) Add() {}
            func (q *Queue) Run() {}
            
            func Run() {}
            
            func work() {
                c := &Cacher{}
                c.GetList()
                c.Add()
                c.Run()
                
                q := &Queue{}
                q.GetList()
                q.Add()
                q.Run()
                
                Run()
            }
        "#;
        fs::write(src_dir.join("main.go"), go_code).unwrap();

        // 2. Java Fixtures
        let java_code_app = r#"
            package demo;
            import demo.StaticHelper;
            
            class Promise {
                public void release() {}
                public void tryFailure() {}
                public void run() {}
            }
            
            class TrafficHandler {
                public void release() {}
                public void tryFailure() {}
                public void run() {}
            }
            
            public class App {
                public static void main(String[] args) {
                    Promise promise = new Promise();
                    promise.release();
                    promise.tryFailure();
                    promise.run();
                    
                    TrafficHandler handler = new TrafficHandler();
                    handler.release();
                    handler.tryFailure();
                    handler.run();
                    
                    StaticHelper.run();
                }
            }
        "#;
        fs::write(src_dir.join("App.java"), java_code_app).unwrap();

        let java_code_helper = r#"
            package demo;
            public class StaticHelper {
                public static void run() {}
            }
        "#;
        fs::write(src_dir.join("StaticHelper.java"), java_code_helper).unwrap();

        // 3. C Fixtures
        let c_code = r#"
            void helper(void) {}
            #define MY_MACRO(x) x
            
            int main(void) {
                helper();
                MY_MACRO(1);
                void (*ptr)(void) = helper;
                ptr();
                return 0;
            }
        "#;
        fs::write(src_dir.join("main.c"), c_code).unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();

        let mut stmt = conn
            .prepare(
                "SELECT (SELECT id FROM nodes WHERE nid = source_nid) as src, \
                        (SELECT id FROM nodes WHERE nid = target_nid) as tgt \
                 FROM edges ORDER BY src, tgt",
            )
            .unwrap();
        let rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, Option<String>>(0)?.unwrap_or_default(),
                    row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                ))
            })
            .unwrap();

        let mut edges_resolved = Vec::new();
        for r in rows {
            let (src, tgt) = r.unwrap();
            edges_resolved.push(format!("{} -> {}", src, tgt));
        }

        // Let's also check unresolved refs to see how macro and indirect pointer calls are handled
        let mut stmt = conn
            .prepare("SELECT (SELECT id FROM nodes WHERE nid = source_nid), specifier FROM unresolved_refs ORDER BY specifier")
            .unwrap();
        let unresolved_rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, Option<String>>(0)?.unwrap_or_default(),
                    row.get::<_, String>(1)?,
                ))
            })
            .unwrap();
        let mut unresolved = Vec::new();
        for r in unresolved_rows {
            let (src, specifier) = r.unwrap();
            unresolved.push(format!("{} -> (unresolved) {}", src, specifier));
        }

        let mut stmt_kinds = conn
            .prepare(
                "SELECT (SELECT id FROM nodes WHERE nid = source_nid) as src, \
                        (SELECT id FROM nodes WHERE nid = target_nid) as tgt, \
                        resolution_kind \
                 FROM edges ORDER BY src, tgt",
            )
            .unwrap();
        let rows_kinds = stmt_kinds
            .query_map([], |row| {
                Ok((
                    row.get::<_, Option<String>>(0)?.unwrap_or_default(),
                    row.get::<_, Option<String>>(1)?.unwrap_or_default(),
                    row.get::<_, i64>(2)?,
                ))
            })
            .unwrap();
        let mut edges_kinds_resolved = Vec::new();
        for r in rows_kinds {
            let (src, tgt, kind) = r.unwrap();
            edges_kinds_resolved.push(format!("{} -> {} (kind={})", src, tgt, kind));
        }

        // Go assertions
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Cacher::GetList (kind=1)".to_string()));
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Cacher::Add (kind=1)".to_string()));
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Cacher::Run (kind=1)".to_string()));
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Queue::GetList (kind=1)".to_string()));
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Queue::Add (kind=1)".to_string()));
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Queue::Run (kind=1)".to_string()));
        assert!(edges_kinds_resolved
            .contains(&"src/main.go::work -> src/main.go::Run (kind=1)".to_string()));

        // Java assertions
        assert!(edges_kinds_resolved.contains(
            &"src/App.java::demo::App::main -> src/App.java::demo::Promise::release (kind=4)"
                .to_string()
        ));
        assert!(edges_kinds_resolved.contains(
            &"src/App.java::demo::App::main -> src/App.java::demo::Promise::tryFailure (kind=4)"
                .to_string()
        ));
        assert!(edges_kinds_resolved.contains(
            &"src/App.java::demo::App::main -> src/App.java::demo::Promise::run (kind=4)"
                .to_string()
        ));
        assert!(edges_kinds_resolved.contains(&"src/App.java::demo::App::main -> src/App.java::demo::TrafficHandler::release (kind=4)".to_string()));
        assert!(edges_kinds_resolved.contains(&"src/App.java::demo::App::main -> src/App.java::demo::TrafficHandler::tryFailure (kind=4)".to_string()));
        assert!(edges_kinds_resolved.contains(
            &"src/App.java::demo::App::main -> src/App.java::demo::TrafficHandler::run (kind=4)"
                .to_string()
        ));
        assert!(edges_kinds_resolved.contains(&"src/App.java::demo::App::main -> src/StaticHelper.java::demo::StaticHelper::run (kind=5)".to_string()));

        // C: MY_MACRO and ptr should be unresolved
        assert!(unresolved.contains(&"src/main.c::main -> (unresolved) MY_MACRO".to_string()));
        assert!(unresolved.contains(&"src/main.c::main -> (unresolved) ptr".to_string()));

        // Clean up
        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn test_raw_call_metadata_capture() {
        let temp_workspace = create_temp_dir();
        let src_dir = temp_workspace.join("src");
        fs::create_dir_all(&src_dir).unwrap();

        // 1. Go code with imports and selectors
        let go_code = r#"
            package main
            import (
                "fmt"
                storage "k8s.io/apiserver/pkg/storage"
            )
            func work() {
                storage.ValidateListOptions()
            }
        "#;
        fs::write(src_dir.join("main.go"), go_code).unwrap();

        // 2. Java code with variable types
        let java_code = r#"
            package demo;
            import io.netty.channel.ChannelPromise;
            public class App {
                public void method(ChannelPromise promise) {
                    promise.tryFailure();
                }
            }
        "#;
        fs::write(src_dir.join("App.java"), java_code).unwrap();

        run_init(&temp_workspace, false).unwrap();

        let db_path = temp_workspace.join(".ochna").join("ochna.db");
        let conn = Connection::open(&db_path).unwrap();

        let mut stmt = conn
            .prepare(
                "SELECT callee_name, call_kind, receiver_expr, receiver_type, package_or_namespace, import_hint \
                 FROM raw_calls ORDER BY callee_name",
            )
            .unwrap();
        let rows = stmt
            .query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, Option<String>>(1)?,
                    row.get::<_, Option<String>>(2)?,
                    row.get::<_, Option<String>>(3)?,
                    row.get::<_, Option<String>>(4)?,
                    row.get::<_, Option<String>>(5)?,
                ))
            })
            .unwrap();

        let mut raw_calls_verified = Vec::new();
        for r in rows {
            let (name, kind, rx, rx_t, ns, imp) = r.unwrap();
            raw_calls_verified.push(format!(
                "{} | {:?} | {:?} | {:?} | {:?} | {:?}",
                name, kind, rx, rx_t, ns, imp
            ));
        }

        println!("Raw calls metadata:\n{}", raw_calls_verified.join("\n"));

        // Go assertions
        let go_call = raw_calls_verified
            .iter()
            .find(|c| c.contains("ValidateListOptions"))
            .unwrap();
        assert!(go_call.contains(&r#"Some("method")"#.to_string()));
        assert!(go_call.contains(&r#"Some("storage")"#.to_string()));
        assert!(go_call.contains(&r#"Some("main")"#.to_string()));
        assert!(go_call.contains(&r#"Some("k8s.io/apiserver/pkg/storage")"#.to_string()));

        // Java assertions
        let java_call = raw_calls_verified
            .iter()
            .find(|c| c.contains("tryFailure"))
            .unwrap();
        assert!(java_call.contains(&r#"Some("method")"#.to_string()));
        assert!(java_call.contains(&r#"Some("promise")"#.to_string()));
        assert!(java_call.contains(&r#"Some("ChannelPromise")"#.to_string()));
        assert!(java_call.contains(&r#"Some("demo")"#.to_string()));
        assert!(java_call.contains(&r#"Some("io.netty.channel.ChannelPromise")"#.to_string()));

        fs::remove_dir_all(&temp_workspace).unwrap();
    }

    #[test]
    fn framework_relationships_survive_incremental_reindex() {
        let workspace = create_temp_dir();
        let source = workspace.join("App.java");
        let base = r#"
@RestController class Controller {
  private final Dependency dependency;
  Controller(Dependency dependency) { this.dependency = dependency; }
  @GetMapping("/items") String items() { return "ok"; }
}
interface Dependency {}
"#;
        fs::write(&source, base).unwrap();
        run_init(&workspace, false).unwrap();

        let snapshot = |workspace: &PathBuf| -> (Vec<(String, String, String, i64)>, i64) {
            let conn = Connection::open(workspace.join(".ochna/ochna.db")).unwrap();
            let mut statement = conn
                .prepare(
                    "SELECT source.id, target.id, edges.kind, edges.resolution_kind
                     FROM edges JOIN nodes source ON source.nid = edges.source_nid
                     JOIN nodes target ON target.nid = edges.target_nid
                     ORDER BY source.id, target.id, edges.kind",
                )
                .unwrap();
            let edges = statement
                .query_map([], |row| {
                    Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
                })
                .unwrap()
                .map(Result::unwrap)
                .collect();
            let raw_count = conn
                .query_row("SELECT COUNT(*) FROM raw_calls", [], |row| row.get(0))
                .unwrap();
            (edges, raw_count)
        };
        let (first, first_raw_count) = snapshot(&workspace);
        assert!(first
            .iter()
            .any(|(_, _, kind, resolution)| kind == "route_handler" && *resolution == 6));
        assert!(first.iter().any(|(source, target, kind, resolution)| source
            .ends_with("Dependency")
            && target.ends_with("Controller")
            && kind == "injected_into"
            && *resolution == 7));

        fs::write(
            &source,
            format!("{base}\n@ConfigurationProperties(\"billing\") class Billing {{}}\n"),
        )
        .unwrap();
        run_init(&workspace, false).unwrap();
        let (second, second_raw_count) = snapshot(&workspace);
        assert!(second.iter().any(|(_, _, kind, _)| kind == "route_handler"));
        assert!(second.iter().any(|(_, _, kind, _)| kind == "injected_into"));
        assert!(second
            .iter()
            .any(|(_, _, kind, _)| kind == "configuration_binds"));
        assert!(second_raw_count > first_raw_count);
        run_init(&workspace, false).unwrap();
        assert_eq!(snapshot(&workspace), (second, second_raw_count));

        fs::write(&source, "@RestController class Controller { @GetMapping(\"/items\") String items() { return \"ok\"; } }\n").unwrap();
        run_init(&workspace, false).unwrap();
        let (removed, _) = snapshot(&workspace);
        assert!(removed
            .iter()
            .all(|(_, _, kind, _)| kind != "injected_into" && kind != "configuration_binds"));
        fs::remove_dir_all(workspace).unwrap();
    }
}