codenexus 0.4.0-rc.1

A queryable code knowledge graph tool built on LadybugDB and tree-sitter
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! `dead-code` service: detect unreferenced functions in a project.

use serde::Serialize;

#[cfg(feature = "analysis")]
use crate::analysis::dead_code::{DeadCodeConfig, DeadCodeDetector, DeadCodeEntry};
#[cfg(feature = "analysis")]
use crate::diagnostics::{Diagnostic, Severity};
#[cfg(feature = "analysis")]
use crate::kit::{AsyncKit, AsyncReady, StorageModule};
#[cfg(all(test, feature = "cli", feature = "analysis"))]
use crate::model::EdgeType;
#[cfg(all(any(feature = "cli", feature = "mcp"), feature = "analysis"))]
use crate::service::error::kit_not_initialized;
#[cfg(all(any(feature = "cli", feature = "mcp"), feature = "analysis"))]
use crate::service::error::to_api_error;
#[cfg(feature = "analysis")]
use crate::service::error::CodeNexusError;
#[cfg(feature = "analysis")]
use crate::service::project::resolve_project_id;
#[cfg(all(any(feature = "cli", feature = "mcp"), feature = "analysis"))]
use crate::service::runtime::kit;
#[cfg(feature = "analysis")]
use crate::service::status::{git_head_commit, is_stale, resolve_project_root};
#[cfg(feature = "analysis")]
use crate::storage::StorageConfig;

#[cfg(all(any(feature = "cli", feature = "mcp"), feature = "analysis"))]
use sdforge::forge;
#[cfg(all(any(feature = "cli", feature = "mcp"), feature = "analysis"))]
use sdforge::prelude::ApiError;

/// JSON-serializable dead-code output.
#[cfg(feature = "analysis")]
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct DeadCodeOutput {
    pub project: String,
    pub dead_code: Vec<DeadCodeEntry>,
    /// Git commit hash captured at index time (Project.lastCommit).
    /// Empty when the project was indexed from a non-git root.
    pub indexed_commit: String,
    /// Current `HEAD` of the project root at query time (empty if not a git
    /// repo or git is unavailable).
    pub current_head: String,
    /// `true` iff both commits are non-empty and differ.
    pub is_stale: bool,
    /// Archify-style repair receipts (e.g. `index/stale` when the analysis
    /// ran against an outdated index).
    pub diagnostics: Vec<Diagnostic>,
}

/// Builds the `index/stale` repair receipt for a stale index.
///
/// Returns an empty vector when the index is fresh (commits equal, or either
/// side unknown — non-git roots never report staleness).
#[cfg(feature = "analysis")]
fn stale_index_diagnostics(
    project: &str,
    root: &std::path::Path,
    indexed_commit: &str,
    current_head: &str,
) -> Vec<Diagnostic> {
    if !is_stale(indexed_commit, current_head) {
        return Vec::new();
    }
    vec![Diagnostic {
        code: "index/stale".to_string(),
        severity: Severity::Warning,
        subject: project.to_string(),
        message: format!(
            "index was taken at {indexed_commit} but HEAD is now {current_head}; results may not reflect current source"
        ),
        evidence: serde_json::json!({
            "indexed_commit": indexed_commit,
            "current_head": current_head,
        }),
        supported_fixes: vec![format!(
            "Re-run: codenexus index --path {} --force true",
            root.display()
        )],
    }]
}

/// Parameters for dead-code detection.
///
/// Bundles the analysis flags so [`run_dead_code`] takes only two arguments
/// (`kit` + `params`) instead of eight positional parameters.
#[cfg(feature = "analysis")]
#[derive(Debug, Clone)]
pub struct DeadCodeParams {
    /// Project name (as registered in the index).
    pub project: String,
    /// Comma-separated extra entry-point patterns (empty = defaults only).
    pub entry: String,
    /// Treat `pub` functions as entry points.
    pub check_exported: bool,
    /// Treat FFI exports as entry points.
    pub check_ffi: bool,
    /// Treat dynamically-dispatched calls as live.
    pub check_dynamic_dispatch: bool,
    /// Treat reflection / derive-macro entry points as live.
    pub check_reflection: bool,
    /// Comma-separated uppercase edge type list (empty = defaults).
    pub edge_types: String,
}

#[cfg(feature = "analysis")]
impl Default for DeadCodeParams {
    fn default() -> Self {
        Self {
            project: String::new(),
            entry: String::new(),
            check_exported: true,
            check_ffi: false,
            check_dynamic_dispatch: false,
            check_reflection: false,
            edge_types: String::new(),
        }
    }
}

/// Builds a [`DeadCodeConfig`] from CLI parameters.
///
/// `edge_types` is a comma-separated list of UPPERCASE DDL edge type strings
/// (e.g. `"CALLS,USAGE,TESTS"`). An empty string means "use the default edge
/// types" from [`DeadCodeConfig::default`].
#[cfg(feature = "analysis")]
fn build_dead_code_config(params: &DeadCodeParams) -> DeadCodeConfig {
    let default = DeadCodeConfig::default();
    let final_edge_types =
        crate::model::edge_type::parse_edge_type_list(&params.edge_types, &default.edge_types);
    DeadCodeConfig {
        check_exported: params.check_exported,
        check_ffi: params.check_ffi,
        check_dynamic_dispatch: params.check_dynamic_dispatch,
        check_reflection: params.check_reflection,
        edge_types: final_edge_types,
        ..default
    }
}

/// Runs dead-code detection with config and returns the output (testable core).
///
/// `entry` is a comma-separated list of extra entry-point patterns;
/// empty string means no extra patterns (defaults to `main`, `Main`, `__main__`).
#[cfg(feature = "analysis")]
pub fn run_dead_code(
    kit: &AsyncKit<AsyncReady>,
    params: &DeadCodeParams,
) -> Result<DeadCodeOutput, CodeNexusError> {
    let storage = kit.require::<StorageModule>()?;
    let project_id = resolve_project_id(&*storage, &params.project)?;
    // Fetch the full Project record to read `lastCommit` (indexed_commit)
    // and `rootPath` (for `git rev-parse HEAD` at query time). Use the O(1)
    // `get_project` lookup instead of `list_projects + find`
    // (previous code triggered a second full scan even though
    // `resolve_project_id` already did one internally).
    let project_record = storage
        .get_project(&project_id)
        .map_err(CodeNexusError::from)?
        .ok_or_else(|| CodeNexusError::ProjectNotFound(params.project.clone()))?;
    let indexed_commit = project_record.last_commit.clone();
    // Resolve rootPath with fallback for legacy relative paths so
    // `git rev-parse HEAD` runs against the actual project root, not the
    // process CWD. See `status::resolve_project_root` for the heuristic.
    let storage_config = kit.config::<StorageConfig>()?;
    let root = resolve_project_root(&project_record.root_path, &storage_config.db_path);
    let current_head = git_head_commit(&root);
    let stale = is_stale(&indexed_commit, &current_head);
    let config = build_dead_code_config(params);
    let detector = DeadCodeDetector::with_config(&*storage, config);
    let mut entry_patterns: Vec<&str> = vec!["main", "Main", "__main__"];
    let extras: Vec<String> = if params.entry.is_empty() {
        Vec::new()
    } else {
        params
            .entry
            .split(',')
            .map(|s| s.trim().to_string())
            .collect()
    };
    for e in &extras {
        entry_patterns.push(e.as_str());
    }
    let entries = detector.detect(&project_id, &entry_patterns)?;
    let diagnostics =
        stale_index_diagnostics(&params.project, &root, &indexed_commit, &current_head);
    Ok(DeadCodeOutput {
        project: params.project.clone(),
        dead_code: entries,
        indexed_commit,
        current_head,
        is_stale: stale,
        diagnostics,
    })
}

/// CLI wrapper — prints result to stdout as JSON.
#[cfg(all(feature = "cli", feature = "analysis"))]
#[forge(
    name = "dead_code",
    version = "0.3.5",
    description = "Detect unreferenced (dead) functions in a project.",
    cli = true
)]
async fn dead_code(
    project: String,
    entry: String,
    check_exported: bool,
    check_ffi: bool,
    check_dynamic_dispatch: bool,
    check_reflection: bool,
    edge_types: String,
) -> Result<(), ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    let params = DeadCodeParams {
        project,
        entry,
        check_exported,
        check_ffi,
        check_dynamic_dispatch,
        check_reflection,
        edge_types,
    };
    let output = run_dead_code(&kit, &params).map_err(|e| to_api_error(e, "dead_code_error"))?;
    let json = serde_json::to_string(&output)
        .map_err(|e| to_api_error(CodeNexusError::from(e), "dead_code_error"))?;
    println!("{json}");
    Ok(())
}

/// MCP wrapper — returns result for MCP protocol.
#[cfg(all(feature = "mcp", feature = "analysis"))]
#[forge(
    name = "dead_code",
    version = "0.3.5",
    tool_name = "dead_code",
    description = "Detect unreferenced (dead) functions with confidence levels and entry-point analysis. Params: project — name or id (required); entry — comma-separated extra entry-point patterns; check_exported — treat pub functions as live; check_ffi — treat FFI exports as live; check_dynamic_dispatch — treat trait-dispatch calls as live; check_reflection — treat reflection/derive-macro entry points as live; edge_types — comma-separated uppercase edge types (empty = defaults)."
)]
#[allow(clippy::too_many_arguments)]
async fn dead_code_mcp(
    project: String,
    entry: String,
    check_exported: bool,
    check_ffi: bool,
    check_dynamic_dispatch: bool,
    check_reflection: bool,
    edge_types: String,
) -> Result<DeadCodeOutput, ApiError> {
    let kit = kit().ok_or_else(kit_not_initialized)?;
    let params = DeadCodeParams {
        project,
        entry,
        check_exported,
        check_ffi,
        check_dynamic_dispatch,
        check_reflection,
        edge_types,
    };
    run_dead_code(&kit, &params).map_err(|e| to_api_error(e, "dead_code_error"))
}

#[cfg(all(test, feature = "cli", feature = "analysis"))]
mod tests {
    use super::*;
    use crate::analysis::dead_code::Confidence;
    use crate::kit::{build_kit, AsyncKit, AsyncReady, KitBootstrapConfig, StorageModule};
    use crate::storage::capability::Storage;
    use tempfile::TempDir;

    fn fresh_db_path() -> (TempDir, std::path::PathBuf) {
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("svc_dead_code_testdb");
        (dir, path)
    }

    fn build_kit_for_db(db: &std::path::Path) -> AsyncKit<AsyncReady> {
        let config = KitBootstrapConfig::new(db.to_path_buf());
        tokio::runtime::Runtime::new()
            .unwrap()
            .block_on(build_kit(&config))
            .expect("build_kit")
    }

    fn seed_project(storage: &dyn Storage, id: &str, name: &str) {
        storage
            .execute(&format!(
                "CREATE (:Project {{id: '{id}', name: '{name}', rootPath: '/demo', language: 'rust', fileCount: 1, indexedAt: 1000, lastCommit: 'abc'}});"
            ))
            .expect("create project");
    }

    /// Default test params: project="demo", all checks on except reflection.
    fn test_params() -> DeadCodeParams {
        DeadCodeParams {
            project: "demo".to_string(),
            entry: String::new(),
            check_exported: true,
            check_ffi: true,
            check_dynamic_dispatch: true,
            check_reflection: false,
            edge_types: String::new(),
        }
    }

    /// Build a `DeadCodeParams` for `build_dead_code_config` tests.
    fn cfg_params(
        exported: bool,
        ffi: bool,
        dynamic: bool,
        reflection: bool,
        edges: &str,
    ) -> DeadCodeParams {
        DeadCodeParams {
            project: "demo".to_string(),
            check_exported: exported,
            check_ffi: ffi,
            check_dynamic_dispatch: dynamic,
            check_reflection: reflection,
            edge_types: edges.to_string(),
            ..DeadCodeParams::default()
        }
    }

    #[test]
    fn run_succeeds_on_empty_db() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let result = run_dead_code(&kit, &test_params());
        assert!(result.is_ok(), "run should succeed: {:?}", result.err());
    }

    #[test]
    fn run_returns_dead_function() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_foo', project: 'demo', name: 'foo', qualifiedName: 'demo.foo', filePath: '/src/lib.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create foo");
        let result = run_dead_code(&kit, &test_params());
        assert!(result.is_ok(), "run should succeed: {:?}", result.err());
    }

    #[test]
    fn run_with_custom_entry_patterns() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_main', project: 'demo', name: 'main', qualifiedName: 'demo.main', filePath: '/src/main.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create main");
        let result = run_dead_code(&kit, &{
            let mut p = test_params();
            p.entry = "custom_entry,other_entry".to_string();
            p
        });
        assert!(result.is_ok(), "run should succeed: {:?}", result.err());
    }

    #[test]
    fn output_serializes_to_json() {
        let out = DeadCodeOutput {
            project: "demo".into(),
            dead_code: vec![DeadCodeEntry {
                name: "foo".into(),
                qualified_name: "demo.foo".into(),
                file_path: "/src/lib.rs".into(),
                start_line: 1,
                language: "rust".into(),
                reason: "zero incoming CALLS edges".into(),
                confidence: Confidence::High,
            }],
            indexed_commit: "abc123".into(),
            current_head: "def456".into(),
            is_stale: true,
            diagnostics: vec![],
        };
        let json = serde_json::to_string(&out).unwrap();
        assert!(json.contains("\"project\":\"demo\""));
        assert!(json.contains("\"dead_code\""));
        assert!(json.contains("\"foo\""));
        assert!(json.contains("\"indexed_commit\":\"abc123\""));
        assert!(json.contains("\"current_head\":\"def456\""));
        assert!(json.contains("\"is_stale\":true"));
        assert!(json.contains("\"diagnostics\":[]"));
    }

    #[test]
    fn stale_index_diagnostics_emit_on_stale_commit() {
        let diags =
            stale_index_diagnostics("demo", std::path::Path::new("/repo"), "abc123", "def456");
        assert_eq!(diags.len(), 1);
        assert_eq!(diags[0].code, "index/stale");
        assert_eq!(diags[0].severity, Severity::Warning);
        assert_eq!(diags[0].subject, "demo");
        assert_eq!(diags[0].evidence["indexed_commit"], "abc123");
        assert_eq!(diags[0].evidence["current_head"], "def456");
        assert!(diags[0].supported_fixes[0].contains("--force true"));
    }

    #[test]
    fn stale_index_diagnostics_empty_when_fresh_or_unknown() {
        assert!(
            stale_index_diagnostics("demo", std::path::Path::new("/repo"), "abc", "abc").is_empty()
        );
        assert!(stale_index_diagnostics("demo", std::path::Path::new("/repo"), "", "").is_empty());
        assert!(
            stale_index_diagnostics("demo", std::path::Path::new("/repo"), "abc", "").is_empty()
        );
    }

    // ===== run_dead_code with config parameters =====

    #[test]
    fn run_dead_code_with_check_exported_excludes_exported() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_pub', project: 'demo', name: 'pub_fn', qualifiedName: 'demo.pub_fn', filePath: '/src/lib.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: true, docstring: '', content: '', parentQn: ''});").expect("create exported");
        storage.execute("CREATE (:Function {id: 'f_priv', project: 'demo', name: 'priv_fn', qualifiedName: 'demo.priv_fn', filePath: '/src/lib.rs', startLine: 6, endLine: 10, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create private");

        let output = run_dead_code(&kit, &test_params()).expect("run should succeed");
        let names: Vec<&str> = output.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            !names.contains(&"pub_fn"),
            "exported fn should be excluded with check_exported=true"
        );
        assert!(names.contains(&"priv_fn"), "private fn should be dead");

        let output2 = run_dead_code(&kit, &{
            let mut p = test_params();
            p.check_exported = false;
            p
        })
        .expect("run should succeed");
        let names2: Vec<&str> = output2.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names2.contains(&"pub_fn"),
            "exported fn should be dead with check_exported=false"
        );
        assert!(
            names2.contains(&"priv_fn"),
            "private fn should still be dead"
        );
    }

    #[test]
    fn run_dead_code_with_check_ffi_excludes_ffi() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_ffi', project: 'demo', name: 'ffi_fn', qualifiedName: 'demo.ffi_fn', filePath: '/src/lib.rs', startLine: 1, endLine: 5, signature: 'extern \"C\" fn ffi_fn()', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create ffi");
        storage.execute("CREATE (:Function {id: 'f_plain', project: 'demo', name: 'plain', qualifiedName: 'demo.plain', filePath: '/src/lib.rs', startLine: 6, endLine: 10, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create plain");

        let output = run_dead_code(&kit, &test_params()).expect("run should succeed");
        let names: Vec<&str> = output.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            !names.contains(&"ffi_fn"),
            "FFI fn should be excluded with check_ffi=true"
        );
        assert!(names.contains(&"plain"), "plain fn should be dead");

        let output2 = run_dead_code(&kit, &{
            let mut p = test_params();
            p.check_ffi = false;
            p
        })
        .expect("run should succeed");
        let names2: Vec<&str> = output2.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names2.contains(&"ffi_fn"),
            "FFI fn should be dead with check_ffi=false"
        );
    }

    #[test]
    fn run_dead_code_with_custom_edge_types() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        storage.execute("CREATE (:Function {id: 'f_a', project: 'demo', name: 'a', qualifiedName: 'demo.a', filePath: '/src/a.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create a");
        storage.execute("CREATE (:Function {id: 'f_b', project: 'demo', name: 'b', qualifiedName: 'demo.b', filePath: '/src/b.rs', startLine: 1, endLine: 5, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create b");
        storage.execute("CREATE (:CodeRelation {id: 'e1', source: 'f_a', target: 'f_b', type: 'USAGE', confidence: 1.0, confidenceTier: 'High', reason: '', startLine: 1, project: 'demo'});").expect("create edge");

        // `a` is passed as an entry-pattern seed; `b` is reachable from
        // `a` via USAGE (in default config) → both alive.
        let output = run_dead_code(&kit, &{
            let mut p = test_params();
            p.entry = "a".to_string();
            p
        })
        .expect("run should succeed");
        let names: Vec<&str> = output.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            !names.contains(&"b"),
            "b should NOT be dead (reachable from seed a via USAGE)"
        );
        assert!(
            !names.contains(&"a"),
            "a should be alive (entry pattern seed)"
        );

        // With CALLS-only config, USAGE edge is not traversed → b unreachable
        // → b dead. `a` is still a seed → alive.
        let output2 = run_dead_code(&kit, &{
            let mut p = test_params();
            p.entry = "a".to_string();
            p.edge_types = "CALLS".to_string();
            p
        })
        .expect("run should succeed");
        let names2: Vec<&str> = output2.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names2.contains(&"b"),
            "b should be dead when only CALLS is checked (USAGE not traversed)"
        );
        assert!(
            !names2.contains(&"a"),
            "a should still be alive (entry pattern seed)"
        );
    }

    #[test]
    fn run_dead_code_returns_output_struct() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        let output = run_dead_code(&kit, &test_params()).expect("run should succeed");
        assert_eq!(output.project, "demo");
        assert!(
            output.dead_code.is_empty(),
            "empty DB should yield empty dead_code"
        );
    }

    // ===== build_dead_code_config unit tests =====

    #[test]
    fn build_dead_code_config_parses_edge_types() {
        let config =
            build_dead_code_config(&cfg_params(true, true, true, false, "CALLS,USAGE,TESTS"));
        assert!(config.check_exported);
        assert!(config.check_ffi);
        assert!(config.check_dynamic_dispatch);
        assert_eq!(config.edge_types.len(), 3);
        assert!(config.edge_types.contains(&EdgeType::Calls));
        assert!(config.edge_types.contains(&EdgeType::Usage));
        assert!(config.edge_types.contains(&EdgeType::Tests));
    }

    #[test]
    fn build_dead_code_config_empty_edge_types_uses_defaults() {
        let config = build_dead_code_config(&cfg_params(true, true, true, false, ""));
        assert!(config.check_exported);
        assert!(config.check_ffi);
        let default = DeadCodeConfig::default();
        assert_eq!(config.edge_types, default.edge_types);
    }

    #[test]
    fn build_dead_code_config_skips_invalid_edge_types() {
        let config = build_dead_code_config(&cfg_params(
            false,
            false,
            false,
            false,
            "CALLS,INVALID,TESTS",
        ));
        assert!(!config.check_exported);
        assert!(!config.check_ffi);
        assert!(!config.check_dynamic_dispatch);
        assert_eq!(config.edge_types.len(), 2);
        assert!(config.edge_types.contains(&EdgeType::Calls));
        assert!(config.edge_types.contains(&EdgeType::Tests));
    }

    #[test]
    fn build_dead_code_config_all_invalid_keeps_defaults() {
        let config =
            build_dead_code_config(&cfg_params(true, true, true, false, "INVALID1,INVALID2"));
        let default = DeadCodeConfig::default();
        assert_eq!(
            config.edge_types, default.edge_types,
            "all-invalid should keep defaults"
        );
    }

    #[test]
    fn build_dead_code_config_trims_whitespace() {
        let config =
            build_dead_code_config(&cfg_params(true, true, true, false, "  CALLS ,  USAGE  "));
        assert_eq!(config.edge_types.len(), 2);
        assert!(config.edge_types.contains(&EdgeType::Calls));
        assert!(config.edge_types.contains(&EdgeType::Usage));
    }

    // ===== check_dynamic_dispatch propagation tests =====

    #[test]
    fn build_dead_code_config_passes_check_dynamic_dispatch_true() {
        let config = build_dead_code_config(&cfg_params(true, true, true, false, ""));
        assert!(
            config.check_dynamic_dispatch,
            "check_dynamic_dispatch=true should propagate"
        );
    }

    #[test]
    fn build_dead_code_config_passes_check_dynamic_dispatch_false() {
        let config = build_dead_code_config(&cfg_params(true, true, false, false, ""));
        assert!(
            !config.check_dynamic_dispatch,
            "check_dynamic_dispatch=false should propagate"
        );
    }

    #[test]
    fn run_dead_code_with_check_dynamic_dispatch_excludes_trait_impl() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("require_storage");
        seed_project(&*storage, "demo", "demo");
        // Trait impl method (e.g. `impl Display for X { fn fmt() {} }`)
        storage.execute("CREATE (:Method {id: 'm_fmt', project: 'demo', name: 'fmt', qualifiedName: 'demo.src.lib.rs.fmt#Display', filePath: '/src/lib.rs', startLine: 5, endLine: 10, signature: '', returnType: '', isExported: false, docstring: '', content: '', parentQn: ''});").expect("create trait impl");

        // With check_dynamic_dispatch=true(default), trait impl is NOT dead
        let output = run_dead_code(&kit, &test_params()).expect("run should succeed");
        let names: Vec<&str> = output.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            !names.contains(&"fmt"),
            "trait impl fmt#Display should NOT be dead with check_dynamic_dispatch=true"
        );

        // With check_dynamic_dispatch=false (opt-out), trait impl IS dead
        let output2 = run_dead_code(&kit, &{
            let mut p = test_params();
            p.check_dynamic_dispatch = false;
            p
        })
        .expect("run should succeed");
        let names2: Vec<&str> = output2.dead_code.iter().map(|e| e.name.as_str()).collect();
        assert!(
            names2.contains(&"fmt"),
            "trait impl fmt#Display IS dead with check_dynamic_dispatch=false"
        );
    }

    // ===== #[forge] wrapper tests via init_kit =====

    #[serial_test::serial(kit_init)]
    #[test]
    fn dead_code_wrapper_succeeds_via_init_kit() {
        use crate::service::runtime::{init_kit, reset_kit_for_testing};

        reset_kit_for_testing();
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        seed_project(&*storage, "demo", "demo");
        init_kit(kit).expect("init_kit");

        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(dead_code(
            "demo".to_string(),
            "".to_string(),
            false,
            false,
            false,
            false,
            "".to_string(),
        ));
        assert!(result.is_ok(), "wrapper should succeed: {:?}", result.err());

        reset_kit_for_testing();
    }

    #[serial_test::serial(kit_init)]
    #[test]
    fn dead_code_wrapper_fails_when_kit_not_initialized() {
        use crate::service::runtime::reset_kit_for_testing;

        reset_kit_for_testing();
        let rt = tokio::runtime::Runtime::new().expect("runtime");
        let result = rt.block_on(dead_code(
            "demo".to_string(),
            "".to_string(),
            false,
            false,
            false,
            false,
            "".to_string(),
        ));
        assert!(result.is_err(), "wrapper should fail without kit");
        reset_kit_for_testing();
    }

    // --- index freshness (indexed_commit / current_head / is_stale) ---

    /// Helper: create a project row with custom `rootPath` and `lastCommit`.
    fn seed_project_with(
        storage: &dyn Storage,
        id: &str,
        name: &str,
        root_path: &str,
        last_commit: &str,
    ) {
        use crate::storage::schema::escape_cypher_string;
        storage
            .execute(&format!(
                "CREATE (:Project {{id: '{}', name: '{}', rootPath: '{}', language: 'rust', fileCount: 0, indexedAt: 1000, lastCommit: '{}'}});",
                escape_cypher_string(id),
                escape_cypher_string(name),
                escape_cypher_string(root_path),
                escape_cypher_string(last_commit),
            ))
            .expect("create project");
    }

    #[test]
    fn test_dead_code_output_includes_indexed_commit_when_set() {
        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        // rootPath points to a non-git directory → current_head empty.
        seed_project_with(&*storage, "demo", "demo", "/nonexistent/path", "abc123");
        let output = run_dead_code(&kit, &test_params()).expect("run");
        assert_eq!(output.indexed_commit, "abc123");
        assert_eq!(output.current_head, "", "non-git root → empty current_head");
        assert!(!output.is_stale, "current_head empty → not stale");
    }

    #[test]
    fn test_is_stale_true_when_commit_differs() {
        let tmp = TempDir::new().unwrap();
        let status = std::process::Command::new("git")
            .arg("init")
            .arg(tmp.path())
            .status();
        if status.is_err() || !status.unwrap().success() {
            eprintln!("skipping test: git init failed");
            return;
        }
        let git = |args: &[&str]| {
            std::process::Command::new("git")
                .arg("-C")
                .arg(tmp.path())
                .args(args)
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        };
        std::fs::write(tmp.path().join("README.md"), "init\n").unwrap();
        if !git(&["add", "."])
            || !git(&[
                "-c",
                "user.email=t@t.com",
                "-c",
                "user.name=t",
                "commit",
                "-m",
                "init",
            ])
        {
            eprintln!("skipping test: git commit failed");
            return;
        }
        let head = std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();
        if head.is_empty() {
            eprintln!("skipping test: could not determine HEAD");
            return;
        }

        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        let root = tmp.path().to_string_lossy().into_owned();
        // indexed_commit deliberately differs from current HEAD.
        seed_project_with(&*storage, "demo", "demo", &root, "abc123");
        let output = run_dead_code(&kit, &test_params()).expect("run");
        assert_eq!(output.indexed_commit, "abc123");
        assert_eq!(output.current_head, head);
        assert!(output.is_stale, "commits differ → stale");
    }

    #[test]
    fn test_is_stale_false_when_commits_match() {
        let tmp = TempDir::new().unwrap();
        let status = std::process::Command::new("git")
            .arg("init")
            .arg(tmp.path())
            .status();
        if status.is_err() || !status.unwrap().success() {
            eprintln!("skipping test: git init failed");
            return;
        }
        let git = |args: &[&str]| {
            std::process::Command::new("git")
                .arg("-C")
                .arg(tmp.path())
                .args(args)
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        };
        std::fs::write(tmp.path().join("README.md"), "init\n").unwrap();
        if !git(&["add", "."])
            || !git(&[
                "-c",
                "user.email=t@t.com",
                "-c",
                "user.name=t",
                "commit",
                "-m",
                "init",
            ])
        {
            eprintln!("skipping test: git commit failed");
            return;
        }
        let head = std::process::Command::new("git")
            .arg("-C")
            .arg(tmp.path())
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();
        if head.is_empty() {
            eprintln!("skipping test: could not determine HEAD");
            return;
        }

        let (_dir, db) = fresh_db_path();
        let kit = build_kit_for_db(&db);
        let storage = kit.require::<StorageModule>().expect("storage");
        let root = tmp.path().to_string_lossy().into_owned();
        // indexed_commit == current HEAD → fresh.
        seed_project_with(&*storage, "demo", "demo", &root, &head);
        let output = run_dead_code(&kit, &test_params()).expect("run");
        assert_eq!(output.indexed_commit, head);
        assert_eq!(output.current_head, head);
        assert!(!output.is_stale, "commits match → fresh");
    }

    /// Legacy indexes stored `rootPath = "."`. Without
    /// [`resolve_project_root`], `git rev-parse HEAD` would run in the
    /// process CWD (which might be a different git repo) and return the
    /// wrong commit, causing false `is_stale=true`. This test verifies the
    /// `db_path`-based fallback resolves the actual project root.
    #[test]
    fn test_dead_code_resolves_relative_rootpath_via_db_path() {
        let project_root = TempDir::new().unwrap();
        let project_root_path = project_root.path().canonicalize().unwrap();

        let status = std::process::Command::new("git")
            .arg("init")
            .arg(&project_root_path)
            .status();
        if status.is_err() || !status.unwrap().success() {
            eprintln!("skipping test: git init failed");
            return;
        }
        let git = |args: &[&str]| {
            std::process::Command::new("git")
                .arg("-C")
                .arg(&project_root_path)
                .args(args)
                .status()
                .map(|s| s.success())
                .unwrap_or(false)
        };
        std::fs::write(project_root_path.join("README.md"), "init\n").unwrap();
        if !git(&["add", "."])
            || !git(&[
                "-c",
                "user.email=t@t.com",
                "-c",
                "user.name=t",
                "commit",
                "-m",
                "init",
            ])
        {
            eprintln!("skipping test: git commit failed");
            return;
        }
        let head = std::process::Command::new("git")
            .arg("-C")
            .arg(&project_root_path)
            .arg("rev-parse")
            .arg("HEAD")
            .output()
            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
            .unwrap_or_default();
        if head.is_empty() {
            eprintln!("skipping test: could not determine HEAD");
            return;
        }

        // Create DB at <project_root>/.codenexus/test.lbug — the layout
        // `resolve_project_root`'s fallback expects (db_path → parent →
        // parent = project_root).
        let db_dir = project_root_path.join(".codenexus");
        std::fs::create_dir_all(&db_dir).unwrap();
        let db_path = db_dir.join("test.lbug");

        let kit = build_kit_for_db(&db_path);
        let storage = kit.require::<StorageModule>().expect("storage");
        // rootPath deliberately set to "." (legacy). lastCommit = current HEAD
        // so is_stale should be false once the fallback resolves the root.
        seed_project_with(&*storage, "demo", "demo", ".", &head);
        let output = run_dead_code(&kit, &test_params()).expect("run");
        assert_eq!(
            output.current_head, head,
            "current_head must be the project's actual HEAD, not the CWD's HEAD"
        );
        assert!(
            !output.is_stale,
            "should not be stale: indexed_commit == current_head after fallback resolution"
        );
    }
}