meta-ast 0.6.1

Polyglot static-analysis engine: extract symbols and cross-language dependency graphs from 9 supported source languages, with optional MetaCall deployment manifest generation.
Documentation
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
//! Graph builder for incremental construction from extraction results.
//!
//! Construction proceeds in stages:
//! 1. Ownership graph: files and their symbols
//! 2. Dataflow nodes and edges (requires `--features dataflow`)
//! 3. Dependency graph: imports and cross-file references
//!
//! The builder maintains index mappings from domain IDs (FileId, SymbolId)
//! to petgraph `NodeIndex` for efficient lookups.

use std::collections::HashMap;
use std::path::PathBuf;

use petgraph::graph::{DiGraph, EdgeIndex, NodeIndex};
use petgraph::visit::EdgeRef;

use crate::graph::CodeGraph;
use crate::graph::edge::{EdgeData, EdgeKind};
#[cfg(feature = "dataflow")]
use crate::graph::node::DataGraphNode;
use crate::graph::node::{ExternalNode, FileNode, NodeData, SymbolNode};
use crate::language::LangId;
#[cfg(feature = "dataflow")]
use crate::model::DataNodeId;
use crate::model::{FileId, IdGenerator, SnapshotId, Symbol, SymbolId};

/// Builder for incremental graph construction from extraction results.
#[derive(Debug)]
pub struct GraphBuilder {
    /// Underlying graph being constructed
    graph: DiGraph<NodeData, EdgeData>,

    /// Map from FileId to graph node index
    file_to_index: HashMap<FileId, NodeIndex>,

    /// Map from SymbolId to graph node index
    symbol_to_index: HashMap<SymbolId, NodeIndex>,

    /// Map from file path to FileId (for resolving import targets)
    path_to_file: HashMap<PathBuf, FileId>,

    /// ID generator for FileIds
    file_id_gen: IdGenerator<FileId>,

    /// Snapshot ID for this analysis
    snapshot_id: SnapshotId,

    /// O(1) dedup index mirroring `CodeGraph::edge_index`.
    edge_index: HashMap<(NodeIndex, NodeIndex, EdgeKind), EdgeIndex>,

    /// Map from external raw path to graph node index
    external_index: HashMap<String, NodeIndex>,

    /// Map from DataNodeId to graph node index
    #[cfg(feature = "dataflow")]
    data_to_index: HashMap<DataNodeId, NodeIndex>,
}

impl GraphBuilder {
    /// Creates a new GraphBuilder for the given snapshot.
    pub fn new(snapshot_id: SnapshotId) -> Self {
        Self {
            graph: DiGraph::new(),
            file_to_index: HashMap::new(),
            symbol_to_index: HashMap::new(),
            path_to_file: HashMap::new(),
            file_id_gen: IdGenerator::new(),
            snapshot_id,
            edge_index: HashMap::new(),
            external_index: HashMap::new(),
            #[cfg(feature = "dataflow")]
            data_to_index: HashMap::new(),
        }
    }

    /// Adds a file node to the graph.
    ///
    /// If the file already exists (determined by path), returns the existing FileId.
    pub fn add_file(&mut self, path: PathBuf, language: LangId) -> FileId {
        // Check if file already exists
        if let Some(&existing_id) = self.path_to_file.get(&path) {
            return existing_id;
        }

        let id = self.file_id_gen.next();

        let node = FileNode {
            id,
            path: path.clone(),
            language,
            snapshot_id: self.snapshot_id,
        };

        let idx = self.graph.add_node(NodeData::File(node));

        self.file_to_index.insert(id, idx);
        self.path_to_file.insert(path, id);

        id
    }

    /// Adds a symbol node and its ownership edge to the containing file.
    ///
    /// The containing file must already exist in the builder. The symbol's
    /// file path is resolved against registered files.
    ///
    /// Returns the NodeIndex for the symbol node.
    pub fn add_symbol(&mut self, symbol: &Symbol) -> Result<NodeIndex, crate::Error> {
        // Check if symbol already exists
        if let Some(&existing) = self.symbol_to_index.get(&symbol.id) {
            return Ok(existing);
        }

        // Look up the file by path
        let file_id = *self
            .path_to_file
            .get(&symbol.file_path)
            .ok_or_else(|| crate::Error::Graph("file must be added before its symbols".into()))?;

        let file_idx = *self
            .file_to_index
            .get(&file_id)
            .ok_or_else(|| crate::Error::Graph("file index must exist".into()))?;

        let node = SymbolNode {
            id: symbol.id,
            name: symbol.name.clone(),
            kind: symbol.kind,
            file_id,
            visibility: symbol.visibility,
            source_range: symbol.source_range.clone(),
        };

        let sym_idx = self.graph.add_node(NodeData::Symbol(node));
        self.symbol_to_index.insert(symbol.id, sym_idx);

        // Add ownership edge: file -> symbol (always full confidence)
        self.add_edge_internal(file_idx, sym_idx, EdgeKind::Ownership, 1.0);

        Ok(sym_idx)
    }

    /// Adds a data-bearing node to the graph.
    ///
    /// Returns the NodeIndex for the data node. Idempotent: returns
    /// the existing index if a data node with the same DataNodeId exists.
    ///
    /// When the data node has a `symbol_id` that resolves to an existing
    /// SymbolNode in the graph, an Ownership edge is created from the
    /// symbol to the data node.
    #[cfg(feature = "dataflow")]
    pub fn add_data_node(&mut self, data_node: &crate::model::DataNode) -> NodeIndex {
        if let Some(&existing) = self.data_to_index.get(&data_node.id) {
            return existing;
        }
        let node = DataGraphNode {
            id: data_node.id,
            symbol_id: data_node.symbol_id,
            name: data_node.name.clone(),
            scope: data_node.scope,
            type_hint: data_node.type_hint.clone(),
            source_range: data_node.source_range.clone(),
        };
        let idx = self.graph.add_node(NodeData::Data(node));
        self.data_to_index.insert(data_node.id, idx);

        if let Some(symbol_id) = data_node.symbol_id
            && let Some(&sym_idx) = self.symbol_to_index.get(&symbol_id)
        {
            self.add_edge_internal(sym_idx, idx, EdgeKind::Ownership, 1.0);
        }

        idx
    }

    /// Adds a flow edge between two data nodes.
    #[cfg(feature = "dataflow")]
    pub fn add_flow_edge(
        &mut self,
        source: crate::model::DataNodeId,
        target: crate::model::DataNodeId,
        kind: crate::model::FlowKind,
        confidence: f32,
    ) {
        let Some(&src_idx) = self.data_to_index.get(&source) else {
            return;
        };
        let Some(&tgt_idx) = self.data_to_index.get(&target) else {
            return;
        };
        self.add_edge_internal_with_flow(src_idx, tgt_idx, EdgeKind::Flow, confidence, Some(kind));
    }

    /// Adds an import edge from one file to another.
    ///
    /// If the target file exists in the project, creates an import edge.
    /// If the target is external (not in the project), creates an ExternalNode
    /// placeholder and an import edge to it.
    pub fn add_import(&mut self, from: FileId, to: PathBuf) {
        let Some(&from_idx) = self.file_to_index.get(&from) else {
            return; // Source not in graph
        };

        // Resolve target path to file ID if it exists in our graph
        if let Some(&to_id) = self.path_to_file.get(&to) {
            if let Some(&to_idx) = self.file_to_index.get(&to_id) {
                self.add_edge_internal(from_idx, to_idx, EdgeKind::Import, 1.0);
            }
            return;
        }

        // External dependency: create or reuse external node
        let raw_path = to.to_string_lossy().to_string();
        let to_idx = if let Some(&idx) = self.external_index.get(&raw_path) {
            idx
        } else {
            // Determine language from source file
            let language = self
                .path_to_file
                .iter()
                .find(|(_, id)| **id == from)
                .map(|(p, _)| {
                    crate::input::detect_language(p).unwrap_or(crate::language::LangId::Python)
                })
                .unwrap_or(crate::language::LangId::Python);

            let node = ExternalNode {
                raw_path: raw_path.clone(),
                language,
                classification: None,
            };
            let idx = self.graph.add_node(NodeData::External(node));
            self.external_index.insert(raw_path, idx);
            idx
        };

        self.add_edge_internal(from_idx, to_idx, EdgeKind::Import, 1.0);
    }

    /// Internal edge addition with flow kind, respecting normalization.
    #[cfg(feature = "dataflow")]
    fn add_edge_internal_with_flow(
        &mut self,
        source: NodeIndex,
        target: NodeIndex,
        kind: EdgeKind,
        confidence: f32,
        flow_kind: Option<crate::model::FlowKind>,
    ) {
        let confidence = confidence.clamp(0.0, 1.0);
        let key = (source, target, kind);
        if let Some(&edge_idx) = self.edge_index.get(&key) {
            let edge = &mut self.graph[edge_idx];
            edge.confidence = edge.confidence.max(confidence);
            if edge.flow_kind.is_none() {
                edge.flow_kind = flow_kind;
            }
            return;
        }
        let edge_idx = self.graph.add_edge(
            source,
            target,
            EdgeData {
                kind,
                confidence,
                flow_kind,
            },
        );
        self.edge_index.insert(key, edge_idx);
    }

    /// Adds a reference edge between two symbols with a confidence score.
    ///
    /// Both symbols must exist in the builder. If a duplicate edge
    /// already exists, the confidence is merged via max (the stronger
    /// signal is preserved).
    pub fn add_reference(&mut self, from: SymbolId, to: SymbolId, confidence: f32) {
        let Some(&from_idx) = self.symbol_to_index.get(&from) else {
            return;
        };
        let Some(&to_idx) = self.symbol_to_index.get(&to) else {
            return;
        };

        self.add_edge_internal(from_idx, to_idx, EdgeKind::Reference, confidence);
    }

    /// Internal method to add an edge with deduplication and confidence.
    ///
    /// If a duplicate `(source, target, kind)` already exists, the existing
    /// edge's confidence is bumped to `max(existing, new)` - never reduced.
    fn add_edge_internal(
        &mut self,
        source: NodeIndex,
        target: NodeIndex,
        kind: EdgeKind,
        confidence: f32,
    ) {
        let confidence = confidence.clamp(0.0, 1.0);
        let key = (source, target, kind);
        if let Some(&edge_idx) = self.edge_index.get(&key) {
            let existing = &mut self.graph[edge_idx];
            existing.confidence = existing.confidence.max(confidence);
            return;
        }

        let edge_data = EdgeData::with_confidence(kind, confidence);

        let edge_idx = self.graph.add_edge(source, target, edge_data);
        self.edge_index.insert(key, edge_idx);
    }

    /// Returns the FileId for a given file path, if registered.
    pub fn file_id_for_path(&self, path: &std::path::PathBuf) -> Option<FileId> {
        self.path_to_file.get(path).copied()
    }

    /// Builds and returns an adjacency map from FileId to the FileIds it imports.
    ///
    /// Walks all Import edges in the graph to produce the relationship.
    pub fn import_adjacency(&self) -> HashMap<FileId, Vec<FileId>> {
        let mut adjacency: HashMap<FileId, Vec<FileId>> = HashMap::new();
        let mut index_to_file: HashMap<NodeIndex, FileId> = HashMap::new();
        for (&file_id, &idx) in &self.file_to_index {
            index_to_file.insert(idx, file_id);
        }
        for edge in self.graph.edge_references() {
            if edge.weight().kind == EdgeKind::Import
                && let (Some(&from_id), Some(&to_id)) = (
                    index_to_file.get(&edge.source()),
                    index_to_file.get(&edge.target()),
                )
            {
                adjacency.entry(from_id).or_default().push(to_id);
            }
        }
        adjacency
    }

    /// Finalizes the graph and returns the constructed CodeGraph.
    pub fn build(self) -> CodeGraph {
        CodeGraph::from_parts(
            self.graph,
            self.edge_index,
            self.file_to_index,
            self.symbol_to_index,
            self.external_index,
            self.snapshot_id,
        )
    }

    /// Returns the number of nodes in the graph so far.
    pub fn node_count(&self) -> usize {
        self.graph.node_count()
    }

    /// Returns the number of edges in the graph so far.
    pub fn edge_count(&self) -> usize {
        self.graph.edge_count()
    }

    /// Returns the number of external dependency nodes.
    pub fn external_count(&self) -> usize {
        self.external_index.len()
    }

    /// Assemble a complete CodeGraph + SCC from parallel extraction results.
    ///
    /// Replaces the manual multi-step wiring in pipeline.rs. Handles:
    /// - File and symbol node registration
    /// - Import edge resolution (via language-specific resolvers)
    /// - Cross-file reference resolution via FlattenedScopeCache
    /// - SCC analysis
    ///
    /// Errors during symbol addition are non-fatal and appended to `diagnostics`.
    pub fn from_extractions<F>(
        extractions: &[F],
        root: &std::path::Path,
        snapshot_id: crate::model::SnapshotId,
        diagnostics: &mut Vec<crate::error::Diagnostic>,
    ) -> (CodeGraph, crate::graph::SccAnalysis)
    where
        F: std::borrow::Borrow<crate::model::FileExtraction> + Sync,
    {
        let (graph, scc, _) =
            Self::from_extractions_with_scope(extractions, root, snapshot_id, diagnostics);
        (graph, scc)
    }

    /// Build the graph, SCC, and the flattened scope cache.
    pub fn from_extractions_with_scope<F>(
        extractions: &[F],
        root: &std::path::Path,
        snapshot_id: crate::model::SnapshotId,
        diagnostics: &mut Vec<crate::error::Diagnostic>,
    ) -> (
        CodeGraph,
        crate::graph::SccAnalysis,
        crate::graph::resolver::FlattenedScopeCache,
    )
    where
        F: std::borrow::Borrow<crate::model::FileExtraction> + Sync,
    {
        let mut builder = Self::new(snapshot_id);

        // Register all files
        for file in extractions {
            let file = file.borrow();
            builder.add_file(file.path.clone(), file.lang);
        }

        // Register all symbols; symbol errors are non-fatal
        for file in extractions {
            let file = file.borrow();
            for symbol in &file.symbols {
                if let Err(e) = builder.add_symbol(symbol) {
                    diagnostics.push(crate::error::Diagnostic {
                        path: file.path.clone(),
                        severity: crate::error::Severity::Warning,
                        message: format!("failed to add symbol to graph: {e}"),
                        source_range: None,
                    });
                }
            }
        }

        // Register data nodes and flow edges from dataflow extraction
        #[cfg(feature = "dataflow")]
        {
            for file in extractions {
                let file = file.borrow();
                for data_node in &file.data_nodes {
                    builder.add_data_node(data_node);
                }
            }
            for file in extractions {
                let file = file.borrow();
                for flow_edge in &file.flow_edges {
                    builder.add_flow_edge(
                        flow_edge.source,
                        flow_edge.target,
                        flow_edge.kind,
                        flow_edge.confidence,
                    );
                }
            }
        }

        // Build path -> FileId map needed by the resolver
        let path_to_file_id: HashMap<std::path::PathBuf, crate::model::FileId> = extractions
            .iter()
            .filter_map(|f| {
                let f = f.borrow();
                builder
                    .file_id_for_path(&f.path)
                    .map(|fid| (f.path.clone(), fid))
            })
            .collect();

        // Resolve language-specific import paths and add import edges
        let mut resolvers = HashMap::new();
        for lang in crate::language::LangId::all() {
            resolvers.insert(lang, crate::language::import_resolver::make_resolver(lang));
        }

        for file in extractions {
            let file = file.borrow();
            let Some(&source_fid) = path_to_file_id.get(&file.path) else {
                continue;
            };
            let source_dir = file.path.parent().unwrap_or(std::path::Path::new("."));
            if let Some(resolver) = resolvers.get(&file.lang) {
                for import in &file.imports {
                    if let Some(target) =
                        resolver.resolve(&import.import_specifier, source_dir, root)
                    {
                        builder.add_import(source_fid, target);
                    }
                }
            }
        }

        // Cross-file reference resolution via FlattenedScopeCache
        let import_adjacency = builder.import_adjacency();
        let ctx = crate::graph::resolver::ResolutionContext::from_extractions(
            extractions,
            &path_to_file_id,
            import_adjacency,
        );
        let scope_cache = crate::graph::resolver::FlattenedScopeCache::build(&ctx, diagnostics);
        let ref_edges = crate::graph::resolver::resolve_all_references(
            extractions,
            &path_to_file_id,
            &scope_cache,
            diagnostics,
        );
        for (from, to, confidence) in ref_edges {
            builder.add_reference(from, to, confidence);
        }

        // Finalize and compute SCC
        let graph = builder.build();
        #[cfg(feature = "metacall-deploy")]
        let mut graph = graph;

        // Client-call edges are resolved after the graph exists, because
        // resolution needs file and symbol nodes. They are ordinary Reference
        // edges, so navigation and SCC see them.
        #[cfg(feature = "metacall-deploy")]
        {
            let call_sites: Vec<crate::deploy::scanner::CallSite> = extractions
                .iter()
                .flat_map(|file| file.borrow().call_sites.iter().cloned())
                .collect();
            if !call_sites.is_empty() {
                let (call_edges, call_diagnostics) =
                    crate::deploy::client_call::resolve_client_call_edges(
                        &graph,
                        extractions,
                        &call_sites,
                        root,
                    );
                diagnostics.extend(call_diagnostics);
                for (from, to, confidence) in call_edges {
                    if let (Some(from_idx), Some(to_idx)) =
                        (graph.symbol_node_index(from), graph.symbol_node_index(to))
                    {
                        graph.add_edge_normalized(
                            from_idx,
                            to_idx,
                            EdgeKind::Reference,
                            confidence,
                        );
                    }
                }
            }
        }

        let scc = crate::graph::SccAnalysis::analyze(graph.graph());

        (graph, scc, scope_cache)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{LineColumn, SourceRange, SymbolKind, Visibility};

    fn test_source_range() -> SourceRange {
        SourceRange {
            byte_start: 0,
            byte_end: 10,
            start: LineColumn { line: 0, column: 0 },
            end: LineColumn {
                line: 0,
                column: 10,
            },
        }
    }

    fn test_symbol(id: u32, name: &str, _file_id: u32) -> Symbol {
        Symbol {
            id: SymbolId::new(id).unwrap(),
            name: name.to_string(),
            kind: SymbolKind::Function,
            language: LangId::Python,
            file_path: PathBuf::from("test.py"),
            source_range: test_source_range(),
            visibility: Some(Visibility::Public),
            signature: None,
            docstring: None,
            is_async: false,
        }
    }

    #[test]
    fn builder_creates_file_nodes() {
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        let path = PathBuf::from("src/main.py");

        let id1 = builder.add_file(path.clone(), LangId::Python);
        let id2 = builder.add_file(path, LangId::Python);

        assert_eq!(id1, id2, "same path should return same FileId");
        assert_eq!(builder.node_count(), 1);
    }

    #[test]
    fn builder_creates_symbol_with_ownership() {
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        let path = PathBuf::from("test.py");

        let file_id = builder.add_file(path.clone(), LangId::Python);
        let symbol = test_symbol(1, "hello", file_id.to_raw());

        let _sym_idx = builder.add_symbol(&symbol).unwrap();

        assert_eq!(builder.node_count(), 2); // file + symbol
        assert_eq!(builder.edge_count(), 1); // ownership edge
    }

    #[test]
    fn builder_deduplicates_edges() {
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        let path1 = PathBuf::from("a.py");
        let path2 = PathBuf::from("b.py");

        let file1 = builder.add_file(path1, LangId::Python);
        let _file2 = builder.add_file(path2, LangId::Python);

        // Add same import twice
        builder.add_import(file1, PathBuf::from("b.py"));
        builder.add_import(file1, PathBuf::from("b.py"));

        assert_eq!(
            builder.edge_count(),
            1,
            "duplicate edges should be deduplicated"
        );
    }

    #[test]
    fn builder_reference_max_merges_confidence() {
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        builder.add_file(PathBuf::from("test.py"), LangId::Python);
        let low = test_symbol(10, "low_fn", 0);
        let high = test_symbol(11, "high_fn", 0);
        builder.add_symbol(&low).unwrap();
        builder.add_symbol(&high).unwrap();

        builder.add_reference(low.id, high.id, 0.5);
        builder.add_reference(low.id, high.id, 0.9);
        assert_eq!(builder.edge_count(), 3);

        let graph = builder.build();
        assert_eq!(graph.edge_count(), 3);
        let refs: Vec<_> = graph.edges_of_kind(EdgeKind::Reference).collect();
        assert_eq!(refs.len(), 1);
        let (src, dst) = refs[0];
        let edge = graph.graph().edges_connecting(src, dst).next().unwrap();
        assert_eq!(edge.weight().confidence, 0.9);
    }

    #[test]
    fn builder_creates_external_node_for_unknown_import() {
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        let path = PathBuf::from("main.py");

        let file_id = builder.add_file(path, LangId::Python);

        // Import of external module not in our project
        builder.add_import(file_id, PathBuf::from("external_module.py"));

        // Should create an external node and import edge
        assert_eq!(
            builder.edge_count(),
            1,
            "external import should create an edge"
        );
        assert_eq!(builder.external_count(), 1, "should have one external node");
    }

    #[test]
    fn builder_tracks_node_mappings() {
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        let path = PathBuf::from("test.py");

        let file_id = builder.add_file(path, LangId::Python);
        let symbol = test_symbol(42, "func", file_id.to_raw());

        builder.add_symbol(&symbol).unwrap();

        // Verify mappings exist
        assert!(builder.file_to_index.contains_key(&file_id));
        assert!(
            builder
                .symbol_to_index
                .contains_key(&SymbolId::new(42).unwrap())
        );
    }

    #[test]
    fn from_extractions_builds_graph_with_correct_node_count() {
        use crate::model::{FileExtraction, LineColumn, SourceRange, Symbol, SymbolId, SymbolKind};
        use std::path::PathBuf;
        let sym = Symbol {
            id: SymbolId::new(1).unwrap(),
            name: "foo".into(),
            kind: SymbolKind::Function,
            language: LangId::Python,
            file_path: PathBuf::from("/proj/a.py"),
            source_range: SourceRange {
                byte_start: 0,
                byte_end: 10,
                start: LineColumn { line: 0, column: 0 },
                end: LineColumn {
                    line: 0,
                    column: 10,
                },
            },
            visibility: None,
            signature: None,
            docstring: None,
            is_async: false,
        };
        let mut base = FileExtraction::empty(PathBuf::from("/proj/a.py"), LangId::Python);
        base.symbols = vec![sym];
        let extractions = vec![base];
        let mut diags = Vec::new();
        let (graph, _scc) = GraphBuilder::from_extractions(
            &extractions,
            std::path::Path::new("/proj"),
            SnapshotId::new(1).unwrap(),
            &mut diags,
        );
        assert_eq!(graph.file_count(), 1);
        assert_eq!(graph.symbol_count(), 1);
        assert!(diags.is_empty());
    }

    #[test]
    fn from_extractions_populates_scc_analysis() {
        use crate::model::FileExtraction;
        let extractions: Vec<FileExtraction> = vec![];
        let mut diags = Vec::new();
        let (graph, scc) = GraphBuilder::from_extractions(
            &extractions,
            std::path::Path::new("/proj"),
            SnapshotId::new(1).unwrap(),
            &mut diags,
        );
        assert_eq!(graph.node_count(), 0);
        assert!(!scc.components.iter().any(|c| c.is_cyclic));
    }

    #[test]
    fn from_extractions_accumulates_diagnostics_on_symbol_error() {
        use crate::model::{FileExtraction, LineColumn, SourceRange, Symbol, SymbolId, SymbolKind};
        use std::path::PathBuf;
        let sym = Symbol {
            id: SymbolId::new(99).unwrap(),
            name: "orphan".into(),
            kind: SymbolKind::Function,
            language: LangId::Python,
            file_path: PathBuf::from("/proj/missing.py"),
            source_range: SourceRange {
                byte_start: 0,
                byte_end: 5,
                start: LineColumn { line: 0, column: 0 },
                end: LineColumn { line: 0, column: 5 },
            },
            visibility: None,
            signature: None,
            docstring: None,
            is_async: false,
        };
        let mut base = FileExtraction::empty(PathBuf::from("/proj/a.py"), LangId::Python);
        base.symbols = vec![sym];
        let extractions = vec![base];
        let mut diags = Vec::new();
        let (_graph, _scc) = GraphBuilder::from_extractions(
            &extractions,
            std::path::Path::new("/proj"),
            SnapshotId::new(1).unwrap(),
            &mut diags,
        );
        assert!(!diags.is_empty(), "expected diagnostic for orphan symbol");
    }

    #[test]
    fn from_extractions_resolves_cross_file_imports() {
        use crate::model::{FileExtraction, LineColumn, SourceRange, UnresolvedImport};
        use std::path::PathBuf;
        let mut first = FileExtraction::empty(PathBuf::from("/proj/a.py"), LangId::Python);
        first.imports = vec![UnresolvedImport {
            import_specifier: "b".into(),
            alias: None,
            symbol: None,
            star: false,
            range: SourceRange {
                byte_start: 0,
                byte_end: 1,
                start: LineColumn { line: 0, column: 0 },
                end: LineColumn { line: 0, column: 1 },
            },
        }];
        let second = FileExtraction::empty(PathBuf::from("/proj/b.py"), LangId::Python);
        let extractions = vec![first, second];
        let mut diags = Vec::new();
        let (graph, _scc) = GraphBuilder::from_extractions(
            &extractions,
            std::path::Path::new("/proj"),
            SnapshotId::new(1).unwrap(),
            &mut diags,
        );
        assert_eq!(graph.file_count(), 2);
        let import_edges: Vec<_> = graph
            .edges_of_kind(crate::graph::EdgeKind::Import)
            .collect();
        assert_eq!(
            import_edges.len(),
            1,
            "expected import edge from a.py to b.py"
        );
    }

    #[cfg(feature = "dataflow")]
    #[test]
    fn add_data_node_creates_ownership_edge_to_symbol() {
        use crate::model::{DataNode, DataNodeId, DataScope};
        let mut builder = GraphBuilder::new(SnapshotId::new(1).unwrap());
        let file_path = PathBuf::from("test.rs");
        let _file_id = builder.add_file(file_path.clone(), LangId::Rust);
        let sym = Symbol {
            id: SymbolId::new(1).unwrap(),
            name: "my_fn".into(),
            kind: SymbolKind::Function,
            language: LangId::Rust,
            file_path,
            source_range: test_source_range(),
            visibility: Some(Visibility::Public),
            signature: None,
            docstring: None,
            is_async: false,
        };
        let sym_idx = builder.add_symbol(&sym).unwrap();

        let data = DataNode {
            id: DataNodeId::new(1).unwrap(),
            symbol_id: Some(SymbolId::new(1).unwrap()),
            name: Some("x".into()),
            scope: DataScope::Local,
            type_hint: Some("i32".into()),
            source_range: test_source_range(),
        };
        builder.add_data_node(&data);

        let graph = builder.build();
        let ownership_edges: Vec<_> = graph.edges_of_kind(EdgeKind::Ownership).collect();
        assert_eq!(
            ownership_edges.len(),
            2,
            "expected file→symbol and symbol→data ownership edges"
        );

        let data_ownership_edges: Vec<_> = ownership_edges
            .into_iter()
            .filter(|(src, _)| *src == sym_idx)
            .collect();
        assert!(
            !data_ownership_edges.is_empty(),
            "expected symbol→data ownership edge"
        );
    }
}