codenexus 0.3.11

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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
// Copyright (c) 2026 Kirky.X. All rights reserved.
// SPDX-License-Identifier: MIT

//! Typed [`Phase`] implementations for the indexing pipeline (Task 2.5).
//!
//! Refactors the 9-step sequence in [`super::pipeline`] into 6 typed phases
//! executed by the [`DagPipeline`](super::pipeline_dag::Pipeline) runner:
//!
//! 1. [`ScanPhase`] — discover files, lookup/create project, diff hashes.
//! 2. [`ParsePhase`] — parallel-parse changed+added files.
//! 3. [`ScopeResolutionPhase`] — build in-memory graph (nodes + per-file edges).
//! 4. [`ResolvePhase`] — resolve calls/dataflow/FFI edges.
//! 5. [`ConfidencePhase`] — pass-through (Task 2.8 adds real confidence scoring).
//! 6. [`LoadPhase`] — persist nodes/edges to the database, build [`IndexResult`].
//!
//! # Input wiring
//!
//! [`ScanPhase`] is the root phase: its typed [`ScanInput`] is inserted into
//! [`PipelineCtx`] externally. All other phases use `Input = ()` and read dep
//! outputs from the context via [`PipelineCtx::get`].

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use tracing::{info, warn};

use crate::discover::{FileInfo, Walker};
use crate::index::error::IndexError;
use crate::index::incremental::{diff_files, FileDiff};
use crate::index::pipeline::{build_file_nodes, now_unix_seconds, with_retry, DEFAULT_MAX_RETRIES};
use crate::ir::ExtractResult;
use crate::model::{
    new_project_id, ConfidenceTier, Edge, EdgeType, Graph, Language, Node, NodeLabel,
};
use crate::parse::parallel::{parallel_parse, parallel_parse_ram_first, RamFirstSources};
use crate::resolve::{build_symbol_table, resolve_all, resolve_include, IncludesGraph};
use crate::storage::Repository;

use super::pipeline::IndexResult;
use super::pipeline_dag::{Phase, PhaseError, PipelineCtx};

/// Confidence for an INCLUDES edge (structural, explicit in syntax).
/// Matches the lower bound of `EdgeType::Includes::confidence_range()` = (0.95, 1.0).
const CONFIDENCE_INCLUDES: f32 = 0.95;

// ---------------------------------------------------------------------------
// Phase I/O structs
// ---------------------------------------------------------------------------

/// Typed input for [`ScanPhase`] (root phase, externally provided).
pub struct ScanInput {
    /// Repository root to index.
    pub path: PathBuf,
    /// Project display name (also used as DB project key).
    pub project_name: String,
    /// When `true`, every disk file is re-parsed regardless of hash.
    pub force: bool,
    /// Pipeline start time (for duration calculation in [`LoadPhase`]).
    pub start: Instant,
}

/// Typed output of [`ScanPhase`], consumed by [`ParsePhase`] and [`LoadPhase`].
pub struct ScanOutput {
    /// The project id (existing or newly generated).
    pub project_id: String,
    /// The project display name.
    pub project_name: String,
    /// The repository root path.
    pub root_path: PathBuf,
    /// All files discovered on disk.
    pub disk_files: Vec<FileInfo>,
    /// The diff of changed/added/deleted/unchanged files.
    pub diff: FileDiff,
    /// Pipeline start time (passed through to [`LoadPhase`]).
    pub start: Instant,
}

/// Typed output of [`ParsePhase`], consumed by [`ScopeResolutionPhase`] and
/// [`ResolvePhase`].
pub struct ParseOutput {
    /// Per-file extraction results.
    pub results: Vec<ExtractResult>,
    /// Per-file parse errors (file path, error message).
    pub errors: Vec<(String, String)>,
    /// Number of files successfully parsed.
    pub files_parsed: usize,
    /// The files that were parsed (changed + added).
    pub to_parse: Vec<FileInfo>,
}

/// Typed output of [`ScopeResolutionPhase`], consumed by [`ResolvePhase`].
pub struct ScopeOutput {
    /// The in-memory graph — single source of truth for nodes + edges
    /// (L3 memory-overflow fix: removed `all_nodes`/`all_edges` duplicates).
    pub graph: Graph,
    /// Mapping from absolute file path → relative path (for normalizing
    /// filePath fields on Parameter/Variable nodes in [`ResolvePhase`]).
    pub path_to_rel: HashMap<String, String>,
}

/// Typed output of [`ResolvePhase`], consumed by [`LoadPhase`].
pub struct ResolveOutput {
    /// The in-memory graph — single source of truth for nodes + edges
    /// (L3 memory-overflow fix: removed `all_nodes`/`all_edges` duplicates;
    /// `graph` is the only copy, with resolved edges added and dangling
    /// type edges pruned in place by `resolve_all`).
    pub graph: Graph,
    /// Number of files parsed (for IndexResult).
    pub files_parsed: usize,
    /// Number of files skipped (for IndexResult).
    pub files_skipped: usize,
    /// C++ `#include` graph for scope-aware call resolution (BUG-C4 fix).
    /// Populated by `build_includes_edges`; consumed by `CallResolver`.
    pub includes_graph: IncludesGraph,
}

/// Typed output of [`LoadPhase`], extracted by [`Pipeline::run`].
pub struct LoadOutput {
    /// The final indexing result.
    pub index_result: IndexResult,
}

// ---------------------------------------------------------------------------
// Helper: convert IndexError to PhaseError
// ---------------------------------------------------------------------------

/// Boxes an [`IndexError`] into a [`PhaseError::ExecutionFailed`] so the
/// pipeline runner can carry it to the caller, which downcasts it back
/// (preserving the exact variant and exit code, Rule 12).
fn phase_err(phase: &'static str, e: IndexError) -> PhaseError {
    PhaseError::ExecutionFailed {
        phase,
        inner: Box::new(e),
    }
}

// ---------------------------------------------------------------------------
// Phase 1: ScanPhase
// ---------------------------------------------------------------------------

/// Phase 1: discover files, lookup/create project id, diff hashes.
///
/// Replaces original steps 1–3 of the pipeline.
pub struct ScanPhase {
    /// Shared repository handle (Arc-cloned from Pipeline).
    pub repo: Arc<Repository>,
}

impl Phase for ScanPhase {
    type Input = ScanInput;
    type Output = ScanOutput;
    const NAME: &'static str = "scan";
    fn deps() -> &'static [&'static str] {
        &[]
    }

    fn run(&self, input: Self::Input, _ctx: &mut PipelineCtx) -> Result<Self::Output, PhaseError> {
        let ScanInput {
            path,
            project_name,
            force,
            start,
        } = input;

        // Step 1: discover files on disk.
        let disk_files = Walker::new(&path)
            .discover()
            .map_err(|e| phase_err(Self::NAME, IndexError::from(e)))?;

        // Assign a project id — reuse existing or generate new.
        let project_id = lookup_or_create_project_id(&self.repo, &project_name)
            .map_err(|e| phase_err(Self::NAME, e))?;

        // Step 2: query existing hashes from the DB (with retry on lock).
        let db_hashes = with_retry(DEFAULT_MAX_RETRIES, || {
            self.repo
                .get_all_file_hashes(&project_id)
                .map_err(IndexError::from)
        })
        .unwrap_or_default();

        // Step 3: diff hashes → changed/added/deleted/unchanged.
        let diff = diff_files(&disk_files, &db_hashes, force)
            .map_err(|e| phase_err(Self::NAME, IndexError::Io(e)))?;

        Ok(ScanOutput {
            project_id,
            project_name,
            root_path: path,
            disk_files,
            diff,
            start,
        })
    }
}

// ---------------------------------------------------------------------------
// Phase 2: ParsePhase
// ---------------------------------------------------------------------------

/// Phase 2: parallel-parse changed + added files.
///
/// Replaces original step 4 of the pipeline. Parse failures are logged and
/// skipped (PRD §4.1.6) — they do not abort the pipeline.
///
/// # RAM-first mode (H15)
///
/// When the caller ([`IndexFacade::index_ram_first`]) provides LZ4-compressed
/// source bytes via [`PipelineCtx`], files are decompressed from in-memory
/// buffers instead of read from disk. The buffers are built by
/// [`IndexFacade::index_ram_first`] before the DAG runs and inserted into the
/// context under [`ParsePhase::RAM_FIRST_KEY`].
///
/// # L7-1 memory-overflow fix
///
/// The compressed buffers are NO LONGER held as a `ParsePhase` struct field.
/// Previously `ram_first_compressed: Option<RamFirstSources>` was moved into
/// `ParsePhase` at registration time and held until `dag.run()` returned (i.e.
/// until LoadPhase finished). For a 10k-file repository this kept ~30-40 GB
/// of LZ4-compressed source bytes alive long after ParsePhase::run had
/// finished using them.
///
/// The buffers now live in [`PipelineCtx`] under [`ParsePhase::RAM_FIRST_KEY`]
/// and are removed via `ctx.remove` at the END of `ParsePhase::run`, so they
/// are dropped immediately after parsing — before ScopeResolutionPhase,
/// ResolvePhase, and LoadPhase run. This cuts peak RSS by ~30-40 GB for
/// large repositories.
///
/// [`IndexFacade::index_ram_first`]: super::pipeline::IndexFacade::index_ram_first
#[derive(Default)]
pub struct ParsePhase;

impl ParsePhase {
    /// [`PipelineCtx`] key under which the caller stores the optional
    /// LZ4-compressed source buffers (`Option<RamFirstSources>`) for RAM-first
    /// mode. [`ParsePhase::run`] removes this entry when it finishes so the
    /// buffers are dropped before subsequent phases run (L7-1).
    pub const RAM_FIRST_KEY: &'static str = "ram_first_compressed";
}

impl Phase for ParsePhase {
    type Input = ();
    type Output = ParseOutput;
    const NAME: &'static str = "parse";
    fn deps() -> &'static [&'static str] {
        &["scan"]
    }

    fn run(&self, _: Self::Input, ctx: &mut PipelineCtx) -> Result<Self::Output, PhaseError> {
        // L7-1 memory-overflow fix: take ownership of the compressed buffers
        // via `ctx.remove` (NOT `ctx.get`) so they are dropped at the end of
        // this `run` call. Previously the buffers were a `ParsePhase` struct
        // field held until `dag.run()` returned (i.e. until LoadPhase
        // finished), keeping ~30-40 GB of LZ4-compressed source bytes alive
        // for 4 phases longer than necessary.
        //
        // `flatten()` turns `Option<Option<RamFirstSources>>` (outer from
        // `remove`, inner from the stored `Option`) into `Option<RamFirstSources>`.
        // When the key is absent (non-RAM-first mode never inserts it) or the
        // stored value is `None`, `compressed` is `None` → streaming disk-read
        // path is used.
        //
        // Order: `remove` MUST precede the immutable `get` of `scan` below —
        // mixing a mutable borrow (`remove`) with an active immutable borrow
        // (`get`) triggers E0502. This mirrors the borrow-ordering established
        // by ResolvePhase::run (L6-1).
        let compressed = ctx
            .remove::<Option<RamFirstSources>>(Self::RAM_FIRST_KEY)
            .flatten();

        let scan = ctx
            .get::<ScanOutput>("scan")
            .ok_or(PhaseError::MissingInput("scan"))?;

        // Build the list of files to parse: changed + added.
        let mut to_parse: Vec<FileInfo> = scan.diff.changed.clone();
        to_parse.extend(scan.diff.added.iter().cloned());

        // H15: RAM-first path uses LZ4-compressed in-memory buffers; the
        // streaming path reads from disk.
        let parse_result = match compressed {
            Some(c) => parallel_parse_ram_first(&to_parse, &c, &scan.project_id),
            None => parallel_parse(&to_parse, &scan.project_id),
        };
        // `c` (the RamFirstSources) is dropped here at the end of `match`,
        // freeing ~30-40 GB for large repos before ScopeResolutionPhase runs.

        // PRD §4.1.6: parse failures are logged and skipped.
        for (file_path, error_msg) in &parse_result.errors {
            warn!(file = %file_path, error = %error_msg, "parse failed, skipping file");
        }

        Ok(ParseOutput {
            results: parse_result.results,
            errors: parse_result.errors,
            files_parsed: parse_result.files_parsed,
            to_parse,
        })
    }
}

// ---------------------------------------------------------------------------
// Phase 3: ScopeResolutionPhase
// ---------------------------------------------------------------------------

/// Phase 3: build the in-memory graph (definition nodes + per-file edges).
///
/// Replaces original step 5 of the pipeline. Merges per-file extraction
/// results into a single [`Graph`], normalizing node ids to FQNs and
/// rewriting edge endpoints to match stored node ids (DQ-004).
pub struct ScopeResolutionPhase;

impl Phase for ScopeResolutionPhase {
    type Input = ();
    type Output = ScopeOutput;
    const NAME: &'static str = "scope";
    fn deps() -> &'static [&'static str] {
        &["scan", "parse"]
    }

    fn run(&self, _: Self::Input, ctx: &mut PipelineCtx) -> Result<Self::Output, PhaseError> {
        // L7-2 memory-overflow fix: take ownership of `ParseOutput` via
        // `ctx.remove` (instead of `ctx.get`) so we can clear the per-file
        // `edges` Vec after cloning them into the graph. The edges are never
        // read by any subsequent phase — `ResolvePhase` and its sub-resolvers
        // use `graph.edges`, `result.nodes`, and the intermediate records
        // (calls/imports/assignments/reads/writes), but NEVER `result.edges`
        // (verified via `grep -rn 'result\.edges\|r\.edges' src/resolve`).
        // For large repos (5 M edges × ~200 bytes) this frees ~1 GB of
        // duplicated edge data before ResolvePhase runs.
        //
        // Order: `remove` (mutable borrow) MUST precede `get` (immutable
        // borrow) to satisfy E0502 — same pattern as ResolvePhase::run (L6-1)
        // and ParsePhase::run (L7-1).
        let mut parse = ctx
            .remove::<ParseOutput>("parse")
            .ok_or(PhaseError::MissingInput("parse"))?;
        let scan = ctx
            .get::<ScanOutput>("scan")
            .ok_or(PhaseError::MissingInput("scan"))?;

        // Clone project_id so the immutable borrow of `scan` ends before the
        // `ctx.insert("parse", ...)` mutable borrow below. Pre-L7-2 used
        // `let project_id = &scan.project_id;` which kept `scan` (and thus
        // `ctx`) borrowed for the entire function, preventing `ctx.insert`.
        let project_id = scan.project_id.clone();
        let mut graph = Graph::new();

        // Add File nodes for every parsed file (used by incremental indexing).
        let file_nodes = build_file_nodes(&scan.diff, &project_id);
        for file_node in &file_nodes {
            graph.add_node(file_node.clone());
        }
        // `scan` is no longer used after this point — NLL releases the
        // immutable borrow of `ctx`, allowing `ctx.insert` later.

        // Build mapping from absolute file path → File node id (file_<uuid>).
        let mut path_to_file_id: HashMap<&str, &str> = HashMap::new();
        for file in parse.to_parse.iter() {
            if let Some(abs) = file.path.to_str() {
                let rel = file.relative_path.as_str();
                for fn_node in &file_nodes {
                    if fn_node.name == rel {
                        path_to_file_id.insert(abs, &fn_node.id);
                        break;
                    }
                }
            }
        }

        // Build mapping from absolute file path → relative path.
        let path_to_rel: HashMap<String, String> = parse
            .to_parse
            .iter()
            .filter_map(|f| {
                f.path
                    .to_str()
                    .map(|p| (p.to_string(), f.relative_path.clone()))
            })
            .collect();

        // Merge per-file extraction results into the graph.
        // L3 memory-overflow fix: graph is the single source of truth; no
        // parallel `all_nodes`/`all_edges` Vecs are built. Nodes/edges are
        // moved into the graph (not cloned twice).
        for result in &parse.results {
            let rel_path = path_to_rel
                .get(result.file_path.as_str())
                .map(|s| s.as_str())
                .unwrap_or(result.file_path.as_str());

            // Build per-file remap: old node id (UUID) → new id (FQN).
            let mut id_remap: HashMap<String, String> = HashMap::new();
            for node in &result.nodes {
                let mut g = node.clone();
                if !matches!(
                    g.label,
                    NodeLabel::Project | NodeLabel::File | NodeLabel::Folder
                ) {
                    let old_id = g.id.clone();
                    g.id = node.qualified_name.clone();
                    if old_id != g.id {
                        id_remap.insert(old_id, g.id.clone());
                    }
                }
                if let Some(fp) = g.file_path.as_mut() {
                    *fp = rel_path.to_string();
                }
                if g.project.is_empty() {
                    g.project = project_id.clone();
                }
                graph.add_node(g);
            }
            for edge in &result.edges {
                let mut e = edge.clone();
                if let Some(file_id) = path_to_file_id.get(e.source.as_str()) {
                    e.source = (*file_id).to_string();
                }
                if let Some(new_target) = id_remap.get(&e.target) {
                    e.target = new_target.clone();
                }
                graph.add_edge(e);
            }
        }
        // `path_to_file_id` (which held `&str` borrows into `parse.to_parse`)
        // is no longer used — NLL releases the immutable borrow of
        // `parse.to_parse`, allowing `&mut parse.results` below.

        // L7-2: clear per-file edges and seen_qns from parse.results. The
        // edges have been cloned into `graph`; `seen_qns` was used only by
        // `push_node` during extraction. No subsequent phase reads either.
        // `clear()` + `shrink_to_fit()` releases the backing allocation,
        // not just the length — important for large repos where the Vec was
        // grown to capacity during extraction.
        for result in &mut parse.results {
            result.edges.clear();
            result.edges.shrink_to_fit();
            result.seen_qns.clear();
            result.seen_qns.shrink_to_fit();
        }

        // Put parse back into ctx for ResolvePhase (which removes it again
        // via `ctx.remove::<ParseOutput>("parse")` — L6-4).
        ctx.insert("parse", parse);

        Ok(ScopeOutput { graph, path_to_rel })
    }
}

// ---------------------------------------------------------------------------
// Helper: build INCLUDES edges for C++ #include (scheme C, v0.3.0)
// ---------------------------------------------------------------------------

/// Builds `EdgeType::Includes` edges for C++ `#include` directives and
/// populates an [`IncludesGraph`] for downstream scope-aware resolution.
///
/// Scheme C (v0.3.0): C++ `#include` is handled separately from other
/// languages' import statements. [`ImportResolver`] skips C++ results (no
/// IMPORTS edges for C++); this function builds INCLUDES edges instead.
/// Other languages (TS/Rust/Python/Go/Java) are unaffected — they continue
/// to produce IMPORTS edges via `ImportResolver`.
///
/// # Arguments
///
/// * `results` - Parse results (only C++ results are processed; others skipped).
/// * `graph` - The graph to add INCLUDES edges to (must contain File nodes
///   created by [`ScopeResolutionPhase`]).
/// * `path_to_rel` - Absolute→relative path mapping (from [`ScopeOutput`]).
/// * `project_id` - The project id for edge construction.
///
/// # Returns
///
/// An [`IncludesGraph`] populated for `lookup_exported_in_scope`. INCLUDES
/// edges are added directly to `graph` (moved, not cloned — L6 fix).
fn build_includes_edges(
    results: &[ExtractResult],
    graph: &mut Graph,
    path_to_rel: &HashMap<String, String>,
    project_id: &str,
) -> IncludesGraph {
    let mut includes_graph = IncludesGraph::new();

    #[cfg(feature = "lang-cpp")]
    {
        // Build file_path → node_id index from File nodes (file_path is relative,
        // normalized by ScopeResolutionPhase). Used for both source and target
        // File node id lookup.
        let mut file_index: HashMap<String, String> = HashMap::new();
        for node in graph.nodes_by_label(NodeLabel::File) {
            if let Some(fp) = &node.file_path {
                file_index
                    .entry(fp.clone())
                    .or_insert_with(|| node.id.clone());
            }
        }

        // All relative file paths — used by resolve_include for suffix matching.
        // resolve_include matches #include paths as suffixes of these paths.
        let all_files: Vec<String> = file_index.keys().cloned().collect();

        // Build rel→abs reverse map for IncludesGraph keys. IncludesGraph stores
        // ABSOLUTE paths (matching SymbolEntry.file_path and CallResolver's
        // caller_file, both from result.file_path) so that lookup_exported_in_scope
        // can filter entries by file_path without format conversion.
        let mut rel_to_abs: HashMap<&String, &String> = HashMap::new();
        for (abs, rel) in path_to_rel {
            rel_to_abs.insert(rel, abs);
        }

        for result in results {
            // Only C++ #include produces INCLUDES edges (scheme C).
            // C and other languages are handled by ImportResolver as IMPORTS.
            if result.language != Language::Cpp {
                continue;
            }

            // Convert absolute file_path to relative for File node lookup.
            // In tests, file_path may already be relative (path_to_rel won't
            // have it as a key, so fall back to the original).
            let source_rel = path_to_rel
                .get(&result.file_path)
                .cloned()
                .unwrap_or_else(|| result.file_path.clone());

            let Some(source_file_id) = file_index.get(&source_rel).cloned() else {
                warn!(
                    file = %result.file_path,
                    "INCLUDES source File node not found; skipping #include edges for this file"
                );
                continue;
            };

            // IncludesGraph source key: absolute path (result.file_path).
            // In tests where path_to_rel is empty, result.file_path is already
            // the "absolute" path (relative path used as-is).
            let source_abs = &result.file_path;

            for import in &result.imports {
                if import.source_file.is_empty() {
                    continue;
                }

                // resolve_include does suffix matching on all_files (relative
                // paths). Returns a relative path that exists in all_files.
                let Some(target_rel) =
                    resolve_include(&import.source_file, &source_rel, &all_files)
                else {
                    // System header (<iostream>) or external lib — no match.
                    // Not warned: system headers are common and expected.
                    continue;
                };

                // target_rel came from all_files (file_index keys), so this
                // lookup is guaranteed to succeed. The guard is defensive only.
                let Some(target_file_id) = file_index.get(&target_rel).cloned() else {
                    continue;
                };

                let edge = Edge::builder(
                    source_file_id.clone(),
                    target_file_id.clone(),
                    EdgeType::Includes,
                    project_id,
                )
                .confidence(CONFIDENCE_INCLUDES)
                .confidence_tier(ConfidenceTier::ImportScoped)
                .start_line(import.line)
                .build();
                // L6 memory-overflow fix: move `edge` into the graph (no
                // clone). The previous `graph.add_edge(edge.clone()); edges.push(edge);`
                // double-allocated every INCLUDES edge — the returned Vec was
                // immediately discarded by ResolvePhase. Now `build_includes_edges`
                // returns only `IncludesGraph`, so the edge is moved directly.
                graph.add_edge(edge);

                // IncludesGraph target key: convert target_rel back to absolute
                // via rel_to_abs map. In tests (path_to_rel empty), fallback to
                // target_rel (which is already the "absolute" path in test context).
                let target_abs = rel_to_abs
                    .get(&target_rel)
                    .map(|s| s.to_string())
                    .unwrap_or(target_rel.clone());
                includes_graph.add_include(source_abs, &target_abs);
            }
        }
    } // end #[cfg(feature = "lang-cpp")]

    #[cfg(not(feature = "lang-cpp"))]
    {
        let _ = (results, graph, path_to_rel, project_id);
    }

    includes_graph
}

// ---------------------------------------------------------------------------
// Phase 4: ResolvePhase
// ---------------------------------------------------------------------------

/// Phase 4: resolve symbols (calls + dataflow + FFI edges).
///
/// Replaces original step 6 of the pipeline. Clones the graph from
/// [`ScopeResolutionPhase`] (the context is immutable during `run`, so
/// mutation requires ownership) and runs the resolvers on it.
pub struct ResolvePhase;

impl Phase for ResolvePhase {
    type Input = ();
    type Output = ResolveOutput;
    const NAME: &'static str = "resolve";
    fn deps() -> &'static [&'static str] {
        &["scan", "parse", "scope"]
    }

    fn run(&self, _: Self::Input, ctx: &mut PipelineCtx) -> Result<Self::Output, PhaseError> {
        // L6 memory-overflow fix: take ownership of `ScopeOutput` via
        // `ctx.remove` instead of `ctx.get` + `graph.clone()`.
        //
        // `ResolvePhase` is the sole consumer of `scope` (LoadPhase deps are
        // `["scan", "resolve"]` — it does NOT read `scope`). The previous
        // `let mut graph = scope.graph.clone();` deep-cloned the entire
        // `Graph` (nodes HashMap + edges Vec), which for large repos is
        // multi-GB and was the dominant memory-pressure point after L1–L5.
        //
        // Removing `scope` from the ctx also frees `ScopeOutput.path_to_rel`
        // and the (now-moved) `Graph` for the remainder of the pipeline,
        // cutting peak RSS by roughly one full Graph worth of memory.
        //
        // Safety of `remove`: if a future phase adds `scope` to its `deps()`,
        // `topo_sort` will still order it after `resolve`, but the
        // `ctx.get::<ScopeOutput>("scope")` call in that phase will return
        // `None` → `MissingInput`. This is fail-loud (Rule 12) and will be
        // caught the first time the new phase is exercised.
        //
        // Order: `remove` first so the mutable borrow ends before the
        // immutable `get` borrows below. Borrowing `scan`/`parse` first would
        // conflict with `remove`'s mutable borrow (E0502).
        let scope = ctx
            .remove::<ScopeOutput>("scope")
            .ok_or(PhaseError::MissingInput("scope"))?;
        // L6 memory-overflow fix: take ownership of `ParseOutput` via
        // `ctx.remove` so its `results: Vec<ExtractResult>` is freed when
        // `ResolvePhase` returns. `LoadPhase` deps are
        // `["scan", "resolve", "confidence"]` — it does NOT read `parse`, so
        // removing it here is safe. Keeping `parse` alive until pipeline end
        // holds every `ExtractResult` (AST snapshots, per-file node/edge
        // lists) in memory alongside the resolved `Graph`, doubling peak RSS
        // for large repos.
        //
        // Order: both `remove`s go first (mutable borrow), then `get` for
        // `scan` (immutable borrow) — mixing them triggers E0502.
        let parse = ctx
            .remove::<ParseOutput>("parse")
            .ok_or(PhaseError::MissingInput("parse"))?;

        let scan = ctx
            .get::<ScanOutput>("scan")
            .ok_or(PhaseError::MissingInput("scan"))?;

        let project_id = &scan.project_id;

        // L3 memory-overflow fix: graph is the single source of truth — no
        // parallel `all_nodes`/`all_edges` Vecs are cloned. Resolved edges
        // are added directly to `graph` by `build_includes_edges` and
        // `resolve_all`; dangling type edges are pruned in place by
        // `resolve_all`'s internal `prune_dangling_type_edges(graph)` call.
        //
        // L6 fix: `graph` is MOVED out of `scope` (no clone). The previous
        // `scope.graph.clone()` was the largest single allocation in the
        // pipeline for large repos.
        let mut graph = scope.graph;

        // Scheme C (v0.3.0): Build INCLUDES edges for C++ #include directives.
        // C++ #include is handled separately from IMPORTS (which is for
        // TS/Rust/Python/Go/Java) because #include establishes a scope-visible
        // relationship that CallResolver uses for cross-file call resolution
        // (BUG-C4 fix). ImportResolver skips C++ results, so no IMPORTS edges
        // are created for C++ — only INCLUDES edges here.
        //
        // MUST run before resolve_all so the IncludesGraph is available to
        // CallResolver for scope-aware lookup_exported_in_scope.
        //
        // L3 fix: `build_includes_edges` adds edges to `graph` directly; the
        // returned Vec is ignored (previously extended into `all_edges`).
        // L6 fix: `build_includes_edges` now returns only `IncludesGraph`
        // (the Vec was always discarded — pure waste).
        let includes_graph =
            build_includes_edges(&parse.results, &mut graph, &scope.path_to_rel, project_id);

        // Resolve calls + dataflow + FFI edges. `TypeResolver::resolve_types`
        // internally builds a path mapping between `result.file_path` (absolute
        // in production) and graph nodes' `file_path` (relative, normalized by
        // ScopeResolutionPhase) so that `imports_map` and `lookup_in_file`
        // lookups succeed despite the path-format difference. See
        // TypeResolver::resolve_types for details.
        //
        // v0.3.0: includes_graph is passed to CallResolver for scope-aware
        // call resolution (BUG-C4 fix). Files with #include edges use
        // lookup_exported_in_scope; others use lookup_exported (backward compat).
        //
        // L3 fix: `resolve_all` adds resolved edges to `graph` directly and
        // prunes dangling type edges via `prune_dangling_type_edges(graph)`.
        // L6 fix: `resolve_all` now returns `()` — no master Vec<Edge> is
        // built. Each sub-resolver's Vec is dropped immediately after its
        // edges are cloned into `graph`.
        let symbol_table = build_symbol_table(&parse.results, project_id);
        resolve_all(
            &parse.results,
            &symbol_table,
            project_id,
            &mut graph,
            &includes_graph,
        );

        // L3 fix: Parameter and Variable nodes created during dataflow
        // resolution (DQ-004) are already in `graph.nodes`. Rewrite their
        // `file_path` in place (absolute → relative) instead of cloning them
        // into a separate `all_nodes` Vec. This eliminates the second copy
        // of Parameter/Variable nodes that previously existed in `all_nodes`.
        for label in [NodeLabel::Parameter, NodeLabel::Variable] {
            let path_to_rel = &scope.path_to_rel;
            graph.for_each_node_with_label_mut(label, |n| {
                if let Some(fp) = n.file_path.as_mut() {
                    if let Some(rel) = path_to_rel.get(fp) {
                        *fp = rel.clone();
                    }
                }
            });
        }

        Ok(ResolveOutput {
            graph,
            files_parsed: parse.files_parsed,
            files_skipped: scan.diff.unchanged.len(),
            includes_graph,
        })
    }
}

// ---------------------------------------------------------------------------
// Phase 5: ConfidencePhase (pass-through, Task 2.8 adds real impl)
// ---------------------------------------------------------------------------

/// Phase 5: confidence scoring (pass-through placeholder).
///
/// Task 2.8 will add real confidence tier assignment to edges. For now this
/// phase is a no-op that ensures LoadPhase runs after ResolvePhase.
pub struct ConfidencePhase;

impl Phase for ConfidencePhase {
    type Input = ();
    type Output = ();
    const NAME: &'static str = "confidence";
    fn deps() -> &'static [&'static str] {
        &["resolve"]
    }

    fn run(&self, _: Self::Input, _ctx: &mut PipelineCtx) -> Result<Self::Output, PhaseError> {
        // Pass-through — real confidence scoring added in Task 2.8.
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Phase 6: LoadPhase
// ---------------------------------------------------------------------------

/// Phase 6: persist nodes and edges to the database, build [`IndexResult`].
///
/// Replaces original steps 7–9 of the pipeline.
pub struct LoadPhase {
    /// Shared repository handle (Arc-cloned from Pipeline).
    pub repo: Arc<Repository>,
}

impl Phase for LoadPhase {
    type Input = ();
    type Output = LoadOutput;
    const NAME: &'static str = "load";
    fn deps() -> &'static [&'static str] {
        &["scan", "resolve", "confidence"]
    }

    fn run(&self, _: Self::Input, ctx: &mut PipelineCtx) -> Result<Self::Output, PhaseError> {
        // L7-3 memory-overflow fix: remove scan and resolve from ctx (instead
        // of get) so they are freed when LoadPhase returns, not when the
        // caller drops `ctx`. LoadPhase is the last phase in the DAG — no
        // subsequent phase reads `scan` or `resolve`. Keeping them in ctx
        // after LoadPhase finishes holds `disk_files: Vec<FileInfo>` (10k+
        // entries × ~100 bytes) and the resolved `Graph` alive until the
        // caller extracts `LoadOutput` and drops ctx, which for large repos
        // adds ~1-2 GB of needless post-pipeline RSS.
        //
        // Order: both `remove`s go first (mutable borrow of ctx), then the
        // owned values are used via shared references for the rest of the
        // function — same borrow pattern as ResolvePhase::run (L6-1) and
        // ScopeResolutionPhase::run (L7-2).
        let scan = ctx
            .remove::<ScanOutput>("scan")
            .ok_or(PhaseError::MissingInput("scan"))?;
        let resolve = ctx
            .remove::<ResolveOutput>("resolve")
            .ok_or(PhaseError::MissingInput("resolve"))?;

        let project_id = &scan.project_id;
        let project_name = &scan.project_name;
        let root = &scan.root_path;
        let disk_files = &scan.disk_files;
        // L3 memory-overflow fix: graph is the single source of truth — no
        // `all_nodes`/`all_edges` Vecs are borrowed from ResolveOutput. The
        // graph's node/edge counts are used for IndexResult reporting.
        let graph = &resolve.graph;
        let edges_created = graph.edge_count();

        // Step 7: batch-delete old nodes for deleted + changed files.
        //
        // The batch path collapses N per-file passes (each ~21 Cypher queries
        // over the node-label set) into a single `WHERE n.filePath IN [...]`
        // pass, keeping the query count fixed regardless of how many files
        // changed. This fixes the `incremental_500_of_1000` SLO regression
        // (33 files/s → target ≥100 files/s) — the per-file delete loop was
        // the dominant cost on incremental re-index.
        let mut paths_to_delete: Vec<String> = scan.diff.deleted.clone();
        paths_to_delete.extend(scan.diff.changed.iter().map(|f| f.relative_path.clone()));
        if !paths_to_delete.is_empty() {
            if let Err(err) = self
                .repo
                .delete_file_nodes_batch(&paths_to_delete, project_id)
            {
                warn!(
                    file_count = paths_to_delete.len(),
                    error = %err,
                    "failed to batch delete file nodes for deleted+changed files"
                );
            }
        }

        // Step 8: persist project node, definition nodes, and edges.
        // L3 fix: stream nodes from `graph.nodes_view()` instead of borrowing
        // a separate `all_nodes: Vec<Node>`.
        // L6 fix: stream edges from `graph.edges_view()` directly into
        // `save_edges` (which now accepts `impl IntoIterator<Item = &Edge>`),
        // eliminating the `let all_edges: Vec<Edge> = ...collect()` that
        // previously deep-cloned every edge. For large repos (100k+ edges)
        // this avoids ~10 MB of peak RSS. Each `with_retry` attempt re-creates
        // the iterator (cheap — `edges_view` returns an iterator over `&Edge`).
        save_project_node(&self.repo, project_id, project_name, root, disk_files)
            .map_err(|e| phase_err(Self::NAME, e))?;
        save_nodes_by_label(&self.repo, graph.nodes_view())
            .map_err(|e| phase_err(Self::NAME, e))?;
        if edges_created > 0 {
            with_retry(DEFAULT_MAX_RETRIES, || {
                self.repo
                    .save_edges(graph.edges_view())
                    .map_err(IndexError::from)
            })
            .map_err(|e| phase_err(Self::NAME, e))?;
        }

        // Step 9: build the IndexResult.
        let duration_ms = scan.start.elapsed().as_millis().min(u64::MAX as u128) as u64;
        let files_indexed = resolve.files_parsed;
        let files_skipped = resolve.files_skipped;
        let nodes_created = graph.node_count();

        info!(
            event = "index_completed",
            project = %project_name,
            path = %root.display(),
            files_indexed = files_indexed,
            files_skipped = files_skipped,
            nodes_created = nodes_created,
            edges_created = edges_created,
            duration_ms = duration_ms,
            "indexing completed"
        );

        let files_per_second = if duration_ms > 0 {
            (files_indexed as f64 * 1000.0 / duration_ms as f64).round() as u64
        } else {
            0
        };
        info!(
            event = "performance",
            files_per_second = files_per_second,
            files_indexed = files_indexed,
            duration_ms = duration_ms,
            "indexing performance metrics"
        );

        Ok(LoadOutput {
            index_result: IndexResult::new(
                project_id.clone(),
                files_indexed,
                files_skipped,
                nodes_created,
                edges_created,
                duration_ms,
            ),
        })
    }
}

// ---------------------------------------------------------------------------
// Free helper functions (converted from Pipeline methods)
// ---------------------------------------------------------------------------

/// Looks up an existing project id by name, or generates a new one.
///
/// Treats the project *name* as the stable identifier across re-indexes.
/// If a project with this name already exists in the DB, reuses its id;
/// otherwise generates a fresh `proj_<uuid>` id.
fn lookup_or_create_project_id(
    repo: &Repository,
    project_name: &str,
) -> std::result::Result<String, IndexError> {
    let projects = repo.list_projects().unwrap_or_default();
    for project in projects {
        if project.name == project_name {
            return Ok(project.id);
        }
    }
    Ok(new_project_id())
}

/// Saves (or re-saves) the project node.
///
/// Only saves the project node if it does not already exist — this preserves
/// the File nodes (and their hashes) from prior runs, which the incremental
/// indexer depends on.
///
/// T206: canonicalizes `root` to an absolute path before writing it into the
/// Project node's `rootPath` property. This prevents downstream staleness
/// checks (`status`/`dead_code`) from running `git rev-parse HEAD` against the
/// process's CWD when the caller passed a relative path like `.`. Falls back
/// to the original path on `canonicalize` failure so dry-run tests with
/// non-existent paths still work.
fn save_project_node(
    repo: &Repository,
    project_id: &str,
    project_name: &str,
    root: &Path,
    disk_files: &[FileInfo],
) -> std::result::Result<(), IndexError> {
    // If the project node already exists, delete only the Project row.
    if repo.get_project(project_id)?.is_some() {
        let cypher = format!(
            "MATCH (p:Project {{id: '{}'}}) DELETE p;",
            project_id.replace('\'', "\\'"),
        );
        let _ = repo.connection().execute(&cypher);
    }
    let canonical_root = std::fs::canonicalize(root).unwrap_or_else(|_| root.to_path_buf());
    let last_commit = git_head_commit(&canonical_root);
    let project_node = Node::builder(NodeLabel::Project, project_name, project_name)
        .id(project_id)
        .properties(serde_json::json!({
            "rootPath": canonical_root.display().to_string(),
            "fileCount": disk_files.len() as i64,
            "indexedAt": now_unix_seconds(),
            "lastCommit": last_commit,
        }))
        .build();
    repo.save_project(&project_node)?;
    Ok(())
}

/// Returns the current `HEAD` commit hash of the git repo at `root`, or an
/// empty string if `root` is not a git repo (or git is unavailable).
///
/// Used to populate the `lastCommit` field on Project nodes for staleness
/// tracking (H9).
fn git_head_commit(root: &Path) -> String {
    std::process::Command::new("git")
        .arg("-C")
        .arg(root)
        .arg("rev-parse")
        .arg("HEAD")
        .output()
        .ok()
        .filter(|o| o.status.success())
        .and_then(|o| String::from_utf8(o.stdout).ok())
        .map(|s| s.trim().to_string())
        .unwrap_or_default()
}

/// Groups nodes by label and bulk-saves each group.
///
/// Deduplicates by id within each label group (LadybugDB's COPY rejects
/// duplicate primary keys). Project nodes are skipped (saved via
/// [`save_project_node`]).
///
/// L3 memory-overflow fix: accepts `impl Iterator<Item = &Node>` instead of
/// `&[Node]`, so callers can stream from [`Graph::nodes_view`] without
/// building a separate `Vec<Node>` copy. The internal `by_label` collection is
/// built per-label (transient), not for all nodes at once.
///
/// L6-3 memory-overflow fix: dedup is now performed inside
/// [`Repository::save_nodes`] (via [`write_nodes_csv_stream`]'s HashSet by
/// node id), so this function no longer builds a `deduped: Vec<Node>` clone
/// per label group. For large repos (100k+ nodes), eliminating the per-group
/// Vec clone avoids ~10 MB of peak RSS. The `by_label: HashMap<NodeLabel,
/// Vec<&Node>>` collection is retained because each label maps to a distinct
/// CSV file (and thus a distinct `save_nodes` call) — the grouping is
/// structurally necessary, only the per-group dedup Vec was waste.
fn save_nodes_by_label<'a>(
    repo: &Repository,
    nodes: impl Iterator<Item = &'a Node>,
) -> std::result::Result<(), IndexError> {
    let mut by_label: HashMap<NodeLabel, Vec<&Node>> = HashMap::new();
    for node in nodes {
        by_label.entry(node.label).or_default().push(node);
    }
    for (label, group) in by_label {
        if group.is_empty() {
            continue;
        }
        // Project nodes are saved via save_project_node; skip them here.
        if label == NodeLabel::Project {
            continue;
        }
        // L6-3: pass `group.iter().copied()` (Iterator<Item = &Node>) directly
        // to `Repository::save_nodes` (now accepts `impl IntoIterator<Item =
        // &Node>`). Dedup is performed inside `write_nodes_csv_stream`
        // (HashSet by node id), so no `deduped: Vec<Node>` clone is needed
        // here. `with_retry` re-creates the iterator on each attempt (cheap —
        // `group.iter()` is a single pointer borrow).
        with_retry(DEFAULT_MAX_RETRIES, || {
            repo.save_nodes(group.iter().copied(), label)
                .map_err(IndexError::from)
        })?;
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Compile-time Send + Sync assertions
// ---------------------------------------------------------------------------

#[cfg(test)]
const _: () = {
    const fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<ScanPhase>();
    assert_send_sync::<ParsePhase>();
    assert_send_sync::<ScopeResolutionPhase>();
    assert_send_sync::<ResolvePhase>();
    assert_send_sync::<ConfidencePhase>();
    assert_send_sync::<LoadPhase>();
    assert_send_sync::<ScanInput>();
    assert_send_sync::<ScanOutput>();
    assert_send_sync::<ParseOutput>();
    assert_send_sync::<ScopeOutput>();
    assert_send_sync::<ResolveOutput>();
    assert_send_sync::<LoadOutput>();
};

#[cfg(all(test, feature = "lang-cpp", feature = "lang-typescript"))]
mod tests {
    use super::*;

    // --- git_head_commit ---

    #[test]
    fn git_head_commit_non_git_dir_returns_empty() {
        let tmp = tempfile::TempDir::new().unwrap();
        // A plain TempDir is not a git repo → git rev-parse fails → empty string.
        let commit = git_head_commit(tmp.path());
        assert_eq!(commit, "", "non-git dir should return empty commit hash");
    }

    #[test]
    fn git_head_commit_codenexus_repo_returns_nonempty() {
        // The CodeNexus project itself is a git repo (we're running tests in it).
        // This verifies the success path: git found → rev-parse HEAD → trim.
        let manifest_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
        let commit = git_head_commit(manifest_dir);
        // If git is not installed, this returns empty — skip the assertion.
        if let Ok(output) = std::process::Command::new("git").arg("--version").output() {
            if output.status.success() {
                assert!(
                    !commit.is_empty(),
                    "CodeNexus repo should have a HEAD commit"
                );
                // A git commit hash is 40 hex chars (SHA-1) or 64 (SHA-256).
                assert!(
                    commit.len() == 40 || commit.len() == 64,
                    "commit hash has unexpected length {}: {commit}",
                    commit.len()
                );
            }
        }
    }

    // --- phase_err helper ---

    #[test]
    fn phase_err_wraps_index_error_as_execution_failed() {
        let err = IndexError::PathNotFound("/no/such/dir".to_string());
        let phase = phase_err("scan", err);
        match phase {
            PhaseError::ExecutionFailed { phase, inner } => {
                assert_eq!(phase, "scan");
                assert!(
                    inner.to_string().contains("/no/such/dir"),
                    "inner error should carry original message: {inner}"
                );
            }
            other => panic!("expected ExecutionFailed, got {other:?}"),
        }
    }

    // --- build_includes_edges (scheme C: C++ #include → INCLUDES edges) ---

    /// Creates a File node with id = file_path = name (mirrors imports.rs tests).
    fn make_file_node(path: &str, project: &str, lang: Language) -> Node {
        Node::builder(NodeLabel::File, path, path)
            .id(path)
            .project(project)
            .file_path(path)
            .language(lang)
            .build()
    }

    #[test]
    fn build_includes_edges_for_cpp() {
        // C++ main.cpp #include "foo.h" → 1 INCLUDES edge main.cpp → foo.h.
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj", Language::Cpp));
        graph.add_node(make_file_node("src/foo.h", "proj", Language::Cpp));

        let mut main_result = ExtractResult::new("src/main.cpp", Language::Cpp);
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "foo.h".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let results = vec![main_result];

        let path_to_rel = HashMap::new();
        // L6 fix: `build_includes_edges` now returns only `IncludesGraph`
        // (edges are moved into `graph`).
        let includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert_eq!(edges.len(), 1, "should create 1 INCLUDES edge");
        assert_eq!(edges[0].edge_type, EdgeType::Includes);
        assert_eq!(edges[0].source, "src/main.cpp");
        assert_eq!(edges[0].target, "src/foo.h");
        assert_eq!(
            edges[0].confidence_tier,
            ConfidenceTier::ImportScoped,
            "INCLUDES edges use ImportScoped tier (matches IMPORTS pattern)"
        );
        assert!(
            includes_graph.contains("src/main.cpp", "src/foo.h"),
            "IncludesGraph should have direct edge main.cpp → foo.h"
        );
    }

    #[test]
    fn build_includes_edges_skips_non_cpp_languages() {
        // TypeScript import should NOT produce INCLUDES edges (only C++ does).
        // TS imports are handled by ImportResolver as IMPORTS edges.
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.ts", "proj", Language::TypeScript));
        graph.add_node(make_file_node("src/utils.ts", "proj", Language::TypeScript));

        let mut ts_result = ExtractResult::new("src/main.ts", Language::TypeScript);
        ts_result.imports.push(crate::ir::ImportInfo {
            source_file: "./utils.ts".to_string(),
            imported_names: vec!["foo".to_string()],
            line: 1,
            is_reexport: false,
        });
        let results = vec![ts_result];

        let path_to_rel = HashMap::new();
        // L6 fix: `build_includes_edges` now returns only `IncludesGraph`.
        let includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let includes_edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert!(
            includes_edges.is_empty(),
            "non-C++ languages should NOT produce INCLUDES edges"
        );
        assert!(
            includes_graph.is_empty(),
            "IncludesGraph should be empty for non-C++ results"
        );
    }

    #[test]
    fn build_includes_edges_skips_system_headers() {
        // C++ #include <iostream> — system header, no matching File node.
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj", Language::Cpp));
        // No "iostream" file in the project.

        let mut main_result = ExtractResult::new("src/main.cpp", Language::Cpp);
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "iostream".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let results = vec![main_result];

        let path_to_rel = HashMap::new();
        // L6 fix: `build_includes_edges` now returns only `IncludesGraph`.
        let includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let includes_edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert!(
            includes_edges.is_empty(),
            "system header #include <iostream> should not produce INCLUDES edge"
        );
        assert!(includes_graph.is_empty());
    }

    #[test]
    fn build_includes_edges_populates_transitive_graph() {
        // Chained #include: main.cpp → foo.h → bar.h.
        // IncludesGraph should have both edges; reachable_from("main.cpp")
        // should include foo.h and bar.h (transitive closure).
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj", Language::Cpp));
        graph.add_node(make_file_node("src/foo.h", "proj", Language::Cpp));
        graph.add_node(make_file_node("src/bar.h", "proj", Language::Cpp));

        let mut main_result = ExtractResult::new("src/main.cpp", Language::Cpp);
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "foo.h".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let mut foo_result = ExtractResult::new("src/foo.h", Language::Cpp);
        foo_result.imports.push(crate::ir::ImportInfo {
            source_file: "bar.h".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let results = vec![main_result, foo_result];

        let path_to_rel = HashMap::new();
        // L6 fix: `build_includes_edges` now returns only `IncludesGraph`.
        let includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let includes_edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert_eq!(includes_edges.len(), 2, "should create 2 INCLUDES edges");
        assert!(includes_graph.contains("src/main.cpp", "src/foo.h"));
        assert!(includes_graph.contains("src/foo.h", "src/bar.h"));

        // Transitive closure: main.cpp reaches foo.h, bar.h, and itself.
        let reachable = includes_graph.reachable_from("src/main.cpp");
        assert!(reachable.contains("src/main.cpp"));
        assert!(reachable.contains("src/foo.h"));
        assert!(reachable.contains("src/bar.h"));
    }

    #[test]
    fn build_includes_edges_with_absolute_paths() {
        // Production scenario: result.file_path is absolute, path_to_rel
        // maps it to relative, graph File nodes use relative paths.
        // IncludesGraph keys should be ABSOLUTE (matching SymbolEntry.file_path
        // and caller_file, both from result.file_path).
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj", Language::Cpp));
        graph.add_node(make_file_node("src/foo.h", "proj", Language::Cpp));

        let mut main_result = ExtractResult::new("/home/dev/proj/src/main.cpp", Language::Cpp);
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "foo.h".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let results = vec![main_result];

        let mut path_to_rel = HashMap::new();
        path_to_rel.insert(
            "/home/dev/proj/src/main.cpp".to_string(),
            "src/main.cpp".to_string(),
        );
        path_to_rel.insert(
            "/home/dev/proj/src/foo.h".to_string(),
            "src/foo.h".to_string(),
        );

        let includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let includes_edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert_eq!(
            includes_edges.len(),
            1,
            "absolute source path should resolve via path_to_rel"
        );
        assert_eq!(includes_edges[0].source, "src/main.cpp");
        assert_eq!(includes_edges[0].target, "src/foo.h");
        // IncludesGraph uses absolute paths (for SymbolEntry.file_path matching).
        assert!(
            includes_graph.contains("/home/dev/proj/src/main.cpp", "/home/dev/proj/src/foo.h"),
            "IncludesGraph keys should be absolute paths (matching SymbolEntry.file_path)"
        );
    }

    #[test]
    fn build_includes_edges_partial_path_include() {
        // C++ #include "fmt/format.h" → include/fmt/format.h (suffix match).
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/main.cpp", "proj", Language::Cpp));
        graph.add_node(make_file_node(
            "include/fmt/format.h",
            "proj",
            Language::Cpp,
        ));

        let mut main_result = ExtractResult::new("src/main.cpp", Language::Cpp);
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "fmt/format.h".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let results = vec![main_result];

        let path_to_rel = HashMap::new();
        let _includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let includes_edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert_eq!(
            includes_edges.len(),
            1,
            "partial-path #include should resolve via suffix matching"
        );
        assert_eq!(includes_edges[0].target, "include/fmt/format.h");
    }

    #[test]
    fn build_includes_edges_skips_when_source_file_not_in_graph() {
        // C++ result exists but no File node for it in the graph.
        // Should skip gracefully (no panic, no edges).
        let mut graph = Graph::new();
        graph.add_node(make_file_node("src/foo.h", "proj", Language::Cpp));
        // No File node for "src/main.cpp".

        let mut main_result = ExtractResult::new("src/main.cpp", Language::Cpp);
        main_result.imports.push(crate::ir::ImportInfo {
            source_file: "foo.h".to_string(),
            imported_names: vec![],
            line: 1,
            is_reexport: false,
        });
        let results = vec![main_result];

        let path_to_rel = HashMap::new();
        let includes_graph = build_includes_edges(&results, &mut graph, &path_to_rel, "proj");

        let includes_edges: Vec<&Edge> = graph
            .edges_view()
            .filter(|e| e.edge_type == EdgeType::Includes)
            .collect();
        assert!(
            includes_edges.is_empty(),
            "no edges when source File node not in graph"
        );
        assert!(includes_graph.is_empty());
    }
}