meta-ast 0.7.0

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
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
//! Client-call resolution: map `metacall('fn', ...)` invocations to symbol nodes.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::deploy::scanner::{CallSite, CallSiteVariant};
use crate::error::{Diagnostic, Severity};
use crate::graph::edge::{
    CONFIDENCE_CLIENT_MULTI_GLOBAL, CONFIDENCE_CLIENT_MULTI_LOAD, CONFIDENCE_CLIENT_UNIQUE_GLOBAL,
    CONFIDENCE_CLIENT_UNIQUE_LOAD,
};
use crate::graph::{CodeGraph, NodeData};
use crate::language::LangId;
use crate::model::{FileExtraction, FileId, SymbolId};
use petgraph::graph::NodeIndex;

/// Resolve a load script to a file node, trying the same strategies as
/// add_metacall_edge (root-relative, source-file-relative, filename match,
/// component-stripping). Returns None when no file node matches.
pub(crate) fn resolve_script_to_file(
    root: &Path,
    script: &str,
    source_file: &Path,
    path_to_idx: &HashMap<PathBuf, NodeIndex>,
) -> Option<NodeIndex> {
    if let Some(idx) = resolve_script_candidate(root, script, source_file, path_to_idx) {
        return Some(idx);
    }
    // A script written on Windows uses backslashes, which are not separators on
    // Unix, so the normalized form is a second candidate.
    let normalized = script.replace('\\', "/");
    if normalized != script {
        return resolve_script_candidate(root, &normalized, source_file, path_to_idx);
    }
    None
}

fn resolve_script_candidate(
    root: &Path,
    script: &str,
    source_file: &Path,
    path_to_idx: &HashMap<PathBuf, NodeIndex>,
) -> Option<NodeIndex> {
    // Strategy 1: root-relative.
    let candidate = root.join(script);
    if let Some(&idx) = path_to_idx.get(&candidate) {
        return Some(idx);
    }

    // Strategy 2: source-file-relative.
    let source_dir = source_file.parent().unwrap_or(Path::new("."));
    let candidate = source_dir.join(script);
    if let Some(&idx) = path_to_idx.get(&candidate) {
        return Some(idx);
    }

    // Strategy 3: strip leading path components until the filename matches.
    // Collect every match and pick the lexicographically smallest path so the
    // result is deterministic even with duplicate basenames.
    let script_path = Path::new(script);
    let target_filename = script_path.file_name().unwrap_or(std::ffi::OsStr::new(""));
    let mut filename_matches: Vec<(PathBuf, NodeIndex)> = path_to_idx
        .iter()
        .filter(|(path, _)| {
            path.file_name() == Some(target_filename) || path.ends_with(script_path)
        })
        .map(|(path, &idx)| (path.clone(), idx))
        .collect();
    filename_matches.sort_by(|a, b| a.0.cmp(&b.0));
    if let Some((_, idx)) = filename_matches.first() {
        return Some(*idx);
    }

    // Strategy 4: pop path prefixes from the script until one matches.
    let mut components: Vec<_> = script_path.components().collect();
    while components.len() > 1 {
        components.remove(0);
        let stripped: PathBuf = components.iter().collect();
        if let Some(&idx) = path_to_idx.get(&stripped) {
            return Some(idx);
        }
    }

    None
}

/// Resolve ClientCall sites to target symbol nodes.
///
/// Phase A (load-aware): resolves against symbols loaded by the source file (unique = 1.0, multiple = 0.8).
/// Phase B (global fallback): searches all project symbols (unique = 0.6, multiple = 0.5).
/// Computed function names cap confidence at 0.4. Unresolved names emit a Warning diagnostic.
fn resolve_sites<F>(
    graph: &CodeGraph,
    extractions: &[F],
    call_sites: &[CallSite],
    root: &Path,
) -> (Vec<ResolvedClientCall>, Vec<Diagnostic>)
where
    F: std::borrow::Borrow<FileExtraction> + Sync,
{
    // Path -> node index for file nodes (paths are project-root relative).
    let mut path_to_idx: HashMap<PathBuf, NodeIndex> = HashMap::new();
    // Path -> FileId, used to filter Phase A candidates by loaded file.
    let mut path_to_file_id: HashMap<PathBuf, FileId> = HashMap::new();
    for (&fid, &idx) in &graph.file_to_index {
        if let NodeData::File(f) = &graph.graph()[idx] {
            path_to_idx.insert(f.path.clone(), idx);
            path_to_file_id.insert(f.path.clone(), fid);
        }
    }

    // Name -> (symbol id, extraction path), pushed in extraction order.
    let mut name_index: HashMap<String, Vec<(SymbolId, PathBuf)>> = HashMap::new();
    for extraction in extractions {
        let extraction = extraction.borrow();
        for symbol in &extraction.symbols {
            name_index
                .entry(symbol.name.clone())
                .or_default()
                .push((symbol.id, extraction.path.clone()));
        }
    }

    let mut resolved: Vec<ResolvedClientCall> = Vec::new();
    let mut diagnostics: Vec<Diagnostic> = Vec::new();

    // Files each source file loads, in load-site order (deduplicated). The
    // tag (when present) constrains Phase A candidates to that language.
    let mut loaded_by_source: HashMap<PathBuf, Vec<(FileId, Option<LangId>)>> = HashMap::new();
    for site in call_sites {
        let (scripts, tag, base): (Vec<String>, Option<LangId>, PathBuf) = match site.variant {
            CallSiteVariant::LoadFromFile => (
                site.scripts.clone(),
                site.target_lang
                    .as_deref()
                    .and_then(crate::deploy::tags::from_metacall_tag),
                root.to_path_buf(),
            ),
            CallSiteVariant::LoadFromConfiguration => {
                let Some(config_script) = site.scripts.first() else {
                    continue;
                };
                let config_file = root.join(config_script);
                let bytes = match std::fs::read(&config_file) {
                    Ok(bytes) => bytes,
                    Err(error) => {
                        diagnostics.push(super::config::config_diagnostic(
                            &config_file,
                            site.source_range.as_ref(),
                            format!("unreadable MetaCall configuration: {error}"),
                        ));
                        continue;
                    }
                };
                let parsed = match super::config::parse_load_configuration(&bytes) {
                    Ok(parsed) => parsed,
                    Err(message) => {
                        diagnostics.push(super::config::config_diagnostic(
                            &config_file,
                            site.source_range.as_ref(),
                            message,
                        ));
                        continue;
                    }
                };
                let tag = parsed
                    .language_id
                    .as_deref()
                    .and_then(crate::deploy::tags::from_metacall_tag);
                let base = super::config::script_base(&config_file, &parsed, root);
                (parsed.scripts.clone(), tag, base)
            }
            _ => continue,
        };
        let loaded = loaded_by_source
            .entry(site.source_file.clone())
            .or_default();
        for script in scripts {
            let Some(file_idx) =
                resolve_script_to_file(&base, &script, &site.source_file, &path_to_idx)
            else {
                continue;
            };
            if let NodeData::File(f) = &graph.graph()[file_idx]
                && !loaded.iter().any(|(fid, _)| *fid == f.id)
            {
                loaded.push((f.id, tag));
            }
        }
    }

    for site in call_sites {
        if site.variant != CallSiteVariant::ClientCall {
            continue;
        }
        let Some(fn_name) = site.function_name.as_deref() else {
            continue;
        };
        if !path_to_idx.contains_key(&site.source_file) {
            continue;
        }

        // Phase A: symbols in files this source file loads.
        let mut candidates: Vec<SymbolId> = Vec::new();
        if let Some(loaded) = loaded_by_source.get(&site.source_file)
            && let Some(entries) = name_index.get(fn_name)
        {
            candidates.extend(
                entries
                    .iter()
                    .filter(|(_, path)| {
                        let Some(&fid) = path_to_file_id.get(path) else {
                            return false;
                        };
                        loaded.iter().any(|&(loaded_fid, tag)| {
                            loaded_fid == fid
                                && match tag {
                                    // Untagged load: path membership is the signal.
                                    None => true,
                                    // Tagged load: the file must be loaded under its
                                    // own language, so a 'node' tag never matches a py
                                    // file with the same name.
                                    Some(tag_lang) => {
                                        graph.file_node(fid).is_some_and(|f| f.language == tag_lang)
                                    }
                                }
                        })
                    })
                    .map(|(sid, _)| *sid),
            );
        }

        // Phase B: global fallback when no loaded file defines the name.
        let global = candidates.is_empty();
        if global && let Some(entries) = name_index.get(fn_name) {
            candidates.extend(entries.iter().map(|(sid, _)| *sid));
        }

        if candidates.is_empty() {
            diagnostics.push(unresolved_diagnostic(site, fn_name));
            continue;
        }

        let base: f32 = if global {
            if candidates.len() == 1 {
                CONFIDENCE_CLIENT_UNIQUE_GLOBAL
            } else {
                CONFIDENCE_CLIENT_MULTI_GLOBAL
            }
        } else if candidates.len() == 1 {
            CONFIDENCE_CLIENT_UNIQUE_LOAD
        } else {
            CONFIDENCE_CLIENT_MULTI_LOAD
        };
        let confidence = base.min(site.confidence);

        let mut emitted = 0;
        for sid in candidates {
            if graph.symbol_node_index(sid).is_some() {
                resolved.push(ResolvedClientCall {
                    source_file: site.source_file.clone(),
                    source_range: site.source_range.clone(),
                    target: sid,
                    confidence,
                });
                emitted += 1;
            }
        }
        if emitted == 0 {
            diagnostics.push(unresolved_diagnostic(site, fn_name));
        }
    }

    (resolved, diagnostics)
}

/// One resolved invocation target, with the call site that produced it.
///
/// The caller projections name the calling file and the enclosing symbol; this
/// record keeps the call-site range too, so a consumer can point at the
/// invocation instead of re-deriving it from the graph.
#[derive(Debug, Clone, PartialEq)]
pub struct ResolvedClientCall {
    /// File that contains the call site, as extracted.
    pub source_file: PathBuf,
    /// Range of the call site, when the source spelled one.
    pub source_range: Option<crate::model::SourceRange>,
    /// Symbol the invocation resolves to.
    pub target: SymbolId,
    /// Ladder confidence: 1.0 unique load-confirmed, 0.8 multiple
    /// load-confirmed, 0.6 unique global, 0.5 multiple global, 0.4 computed.
    pub confidence: f32,
}

/// Both call-edge projections of one resolution pass.
#[derive(Debug)]
pub struct ClientCallProjections {
    /// File node to symbol node. Deployment needs the calling file, because a
    /// top-level call has no enclosing symbol.
    pub file_edges: Vec<(NodeIndex, NodeIndex, f32)>,
    /// Symbol node to symbol node. Navigation keys on the caller symbol.
    pub symbol_edges: Vec<(SymbolId, SymbolId, f32)>,
    /// One entry per resolved target, in resolution order.
    pub resolved: Vec<ResolvedClientCall>,
    pub diagnostics: Vec<Diagnostic>,
}

/// Resolve ClientCall sites once and emit both projections.
pub fn resolve_client_call_projections<F>(
    graph: &CodeGraph,
    extractions: &[F],
    call_sites: &[CallSite],
    root: &Path,
) -> ClientCallProjections
where
    F: std::borrow::Borrow<FileExtraction> + Sync,
{
    let (resolved, diagnostics) = resolve_sites(graph, extractions, call_sites, root);
    let mut path_to_idx: HashMap<PathBuf, NodeIndex> = HashMap::new();
    for &idx in graph.file_to_index.values() {
        if let NodeData::File(file) = &graph.graph()[idx] {
            path_to_idx.insert(file.path.clone(), idx);
        }
    }

    // One extraction lookup per path, instead of a scan per resolved site.
    let path_to_extraction: HashMap<&Path, &FileExtraction> = extractions
        .iter()
        .map(std::borrow::Borrow::borrow)
        .map(|extraction| (extraction.path.as_path(), extraction))
        .collect();

    let mut file_edges = Vec::with_capacity(resolved.len());
    let mut symbol_edges = Vec::with_capacity(resolved.len());
    for call in &resolved {
        if let (Some(&caller_idx), Some(target_idx)) = (
            path_to_idx.get(&call.source_file),
            graph.symbol_node_index(call.target),
        ) {
            file_edges.push((caller_idx, target_idx, call.confidence));
        }
        if let Some(caller) = enclosing_symbol(
            &path_to_extraction,
            &call.source_file,
            call.source_range.as_ref(),
        ) {
            symbol_edges.push((caller, call.target, call.confidence));
        }
    }

    ClientCallProjections {
        file_edges,
        symbol_edges,
        resolved,
        diagnostics,
    }
}

fn enclosing_symbol(
    path_to_extraction: &HashMap<&Path, &FileExtraction>,
    path: &Path,
    range: Option<&crate::model::SourceRange>,
) -> Option<SymbolId> {
    let range = range?;
    let file = path_to_extraction.get(path)?;
    file.symbols
        .iter()
        .filter(|symbol| {
            symbol.source_range.byte_start <= range.byte_start
                && range.byte_end <= symbol.source_range.byte_end
        })
        .min_by_key(|symbol| symbol.source_range.byte_end - symbol.source_range.byte_start)
        .map(|symbol| symbol.id)
}

/// Build the Warning diagnostic for an invocation whose target could not be
/// resolved to any symbol.
fn unresolved_diagnostic(site: &CallSite, fn_name: &str) -> Diagnostic {
    Diagnostic {
        path: site.source_file.clone(),
        severity: Severity::Warning,
        message: format!("unresolved MetaCall invocation target: '{fn_name}'"),
        source_range: site.source_range.clone(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::node::{FileNode, SymbolNode};
    use crate::language::LangId;
    use crate::model::{LineColumn, SnapshotId, SourceRange, Symbol, SymbolKind, Visibility};
    use std::path::PathBuf;
    use std::sync::Arc;

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

    fn symbol(id: u32, name: &str, path: &str, lang: LangId) -> Symbol {
        Symbol {
            id: SymbolId::new(id).unwrap(),
            name: name.to_string(),
            kind: SymbolKind::Function,
            language: lang,
            file_path: PathBuf::from(path),
            source_range: test_range(),
            name_range: None,
            visibility: Some(Visibility::Public),
            signature: None,
            docstring: None,
            is_async: false,
        }
    }

    fn extraction(path: &str, lang: LangId, symbols: Vec<Symbol>) -> Arc<FileExtraction> {
        let mut out = FileExtraction::empty(PathBuf::from(path), lang);
        out.symbols = symbols;
        Arc::new(out)
    }

    fn load_from_file(source: &str, scripts: Vec<&str>) -> CallSite {
        CallSite {
            source_file: PathBuf::from(source),
            caller_lang: LangId::Python,
            variant: CallSiteVariant::LoadFromFile,
            target_lang: Some("node".to_string()),
            scripts: scripts.into_iter().map(str::to_string).collect(),
            function_name: None,
            is_async: false,
            source_range: None,
            confidence: 1.0,
        }
    }

    fn client_call(source: &str, fn_name: &str, confidence: f32) -> CallSite {
        CallSite {
            source_file: PathBuf::from(source),
            caller_lang: LangId::Python,
            variant: CallSiteVariant::ClientCall,
            target_lang: None,
            scripts: vec![],
            function_name: Some(fn_name.to_string()),
            is_async: false,
            source_range: None,
            confidence,
        }
    }

    /// Synthetic graph plus extractions for resolution tests.
    struct Fixture {
        graph: CodeGraph,
        extractions: Vec<Arc<FileExtraction>>,
    }

    impl Fixture {
        fn new() -> Self {
            Self {
                graph: CodeGraph::new(SnapshotId::new(1).unwrap()),
                extractions: Vec::new(),
            }
        }

        fn add_file(&mut self, path: &str, lang: LangId) -> (FileId, NodeIndex) {
            let id = FileId::new(self.graph.file_to_index.len() as u32 + 1).unwrap();
            let idx = self.graph.add_node(NodeData::File(FileNode::new(
                id,
                PathBuf::from(path),
                lang,
                SnapshotId::new(1).unwrap(),
            )));
            self.graph.file_to_index.insert(id, idx);
            (id, idx)
        }

        fn add_symbol(
            &mut self,
            sym: &Symbol,
            file_id: FileId,
            path: &str,
            lang: LangId,
        ) -> NodeIndex {
            let idx = self
                .graph
                .add_node(NodeData::Symbol(SymbolNode::from_symbol(sym, file_id)));
            self.graph.symbol_to_index.insert(sym.id, idx);
            self.extractions
                .push(extraction(path, lang, vec![sym.clone()]));
            idx
        }
    }

    impl Default for Fixture {
        fn default() -> Self {
            Self::new()
        }
    }

    #[test]
    fn load_aware_unique_match() {
        let mut fx = Fixture::new();
        let (py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("math.js", LangId::JavaScript);
        let multiply = symbol(1, "multiply", "math.js", LangId::JavaScript);
        let sym_idx = fx.add_symbol(&multiply, js_id, "math.js", LangId::JavaScript);

        let call_sites = vec![
            load_from_file("orchestrator.py", vec!["math.js"]),
            client_call("orchestrator.py", "multiply", 1.0),
        ];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert_eq!(resolution.file_edges.len(), 1);
        let (from, to, confidence) = resolution.file_edges[0];
        let py_idx = *fx.graph.file_to_index.get(&py_id).unwrap();
        assert_eq!(from, py_idx);
        assert_eq!(to, sym_idx);
        assert_eq!(confidence, 1.0);
        assert!(resolution.diagnostics.is_empty());
    }

    #[test]
    fn resolved_targets_keep_the_call_site_range() {
        let mut fx = Fixture::new();
        let (py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("math.js", LangId::JavaScript);
        let multiply = symbol(1, "multiply", "math.js", LangId::JavaScript);
        fx.add_symbol(&multiply, js_id, "math.js", LangId::JavaScript);
        let run = symbol(2, "run", "orchestrator.py", LangId::Python);
        fx.add_symbol(&run, py_id, "orchestrator.py", LangId::Python);
        let mut call = client_call("orchestrator.py", "multiply", 1.0);
        call.source_range = Some(test_range());

        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &[load_from_file("orchestrator.py", vec!["math.js"]), call],
            Path::new("."),
        );

        assert_eq!(resolution.resolved.len(), 1);
        let record = &resolution.resolved[0];
        assert_eq!(record.target, SymbolId::new(1).unwrap());
        assert_eq!(record.source_range, Some(test_range()));
        assert_eq!(record.confidence, 1.0);
        assert_eq!(
            resolution.symbol_edges,
            vec![(SymbolId::new(2).unwrap(), SymbolId::new(1).unwrap(), 1.0)],
            "the symbol projection keys on the enclosing caller"
        );
    }

    #[test]
    fn phase_a_language_tag_filter_excludes_mistagged_files() {
        // math.js is loaded under its own 'node' tag; weird.py defines the
        // same name but is loaded under a mismatched 'node' tag, so its
        // symbols must not become Phase A candidates.
        let mut fx = Fixture::new();
        let (_py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("math.js", LangId::JavaScript);
        let (weird_id, _) = fx.add_file("weird.py", LangId::Python);
        let js_multiply = symbol(1, "multiply", "math.js", LangId::JavaScript);
        let py_multiply = symbol(2, "multiply", "weird.py", LangId::Python);
        let js_sym = fx.add_symbol(&js_multiply, js_id, "math.js", LangId::JavaScript);
        let _py_sym = fx.add_symbol(&py_multiply, weird_id, "weird.py", LangId::Python);

        let mistagged_load = CallSite {
            source_file: PathBuf::from("orchestrator.py"),
            caller_lang: LangId::Python,
            variant: CallSiteVariant::LoadFromFile,
            target_lang: Some("node".to_string()),
            scripts: vec!["weird.py".to_string()],
            function_name: None,
            is_async: false,
            source_range: None,
            confidence: 1.0,
        };
        let call_sites = vec![
            load_from_file("orchestrator.py", vec!["math.js"]),
            mistagged_load,
            client_call("orchestrator.py", "multiply", 1.0),
        ];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert_eq!(resolution.file_edges.len(), 1);
        assert_eq!(resolution.file_edges[0].1, js_sym);
        assert_eq!(resolution.file_edges[0].2, 1.0);
        assert!(resolution.diagnostics.is_empty());
    }

    #[test]
    fn phase_a_ambiguous_across_languages_stays_ambiguous() {
        // Both math.js (node) and math.py (py) are loaded under their own
        // tags and both define 'multiply'. The call does not name a language,
        // so both candidates remain, at 0.8 each.
        let mut fx = Fixture::new();
        let (_orchestrator_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("math.js", LangId::JavaScript);
        let (py_math_id, _) = fx.add_file("math.py", LangId::Python);
        let js_multiply = symbol(1, "multiply", "math.js", LangId::JavaScript);
        let py_multiply = symbol(2, "multiply", "math.py", LangId::Python);
        let js_sym = fx.add_symbol(&js_multiply, js_id, "math.js", LangId::JavaScript);
        let py_sym = fx.add_symbol(&py_multiply, py_math_id, "math.py", LangId::Python);

        let py_load = CallSite {
            target_lang: Some("py".to_string()),
            scripts: vec!["math.py".to_string()],
            ..load_from_file("orchestrator.py", vec![])
        };
        let call_sites = vec![
            load_from_file("orchestrator.py", vec!["math.js"]),
            py_load,
            client_call("orchestrator.py", "multiply", 1.0),
        ];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        let mut targets: Vec<_> = resolution.file_edges.iter().map(|(_, to, _)| *to).collect();
        targets.sort();
        let mut expected = vec![js_sym, py_sym];
        expected.sort();
        assert_eq!(targets, expected);
        assert!(resolution.file_edges.iter().all(|(_, _, c)| *c == 0.8));
    }

    #[test]
    fn resolve_script_to_file_basename_collision_is_deterministic() {
        // Two files share the basename; the lexicographically smallest path
        // must win so the result is stable across runs.
        let mut path_to_idx: HashMap<PathBuf, NodeIndex> = HashMap::new();
        path_to_idx.insert(PathBuf::from("b/math.js"), NodeIndex::new(1));
        path_to_idx.insert(PathBuf::from("a/math.js"), NodeIndex::new(0));

        let resolved = resolve_script_to_file(
            Path::new("."),
            "math.js",
            Path::new("orchestrator.py"),
            &path_to_idx,
        );
        assert_eq!(resolved, Some(NodeIndex::new(0)));
    }

    #[test]
    fn config_parse_failure_emits_diagnostic() {
        let mut fx = Fixture::new();
        fx.add_file("orchestrator.py", LangId::Python);
        let config_site = CallSite {
            source_file: PathBuf::from("orchestrator.py"),
            caller_lang: LangId::Python,
            variant: CallSiteVariant::LoadFromConfiguration,
            target_lang: None,
            scripts: vec!["missing.conf.json".to_string()],
            function_name: None,
            is_async: false,
            source_range: None,
            confidence: 1.0,
        };
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &[config_site],
            Path::new("."),
        );
        assert!(resolution.file_edges.is_empty());
        assert_eq!(resolution.diagnostics.len(), 1);
        assert_eq!(resolution.diagnostics[0].severity, Severity::Warning);
        assert_eq!(
            resolution.diagnostics[0].path,
            PathBuf::from(".").join("missing.conf.json")
        );
    }

    #[test]
    fn load_aware_multiple_matches() {
        let mut fx = Fixture::new();
        let (py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("math.js", LangId::JavaScript);
        let (utils_id, _) = fx.add_file("utils.js", LangId::JavaScript);
        let m1 = symbol(1, "multiply", "math.js", LangId::JavaScript);
        let m2 = symbol(2, "multiply", "utils.js", LangId::JavaScript);
        let s1 = fx.add_symbol(&m1, js_id, "math.js", LangId::JavaScript);
        let s2 = fx.add_symbol(&m2, utils_id, "utils.js", LangId::JavaScript);

        let call_sites = vec![
            load_from_file("orchestrator.py", vec!["math.js", "utils.js"]),
            client_call("orchestrator.py", "multiply", 1.0),
        ];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert_eq!(resolution.file_edges.len(), 2);
        let py_idx = *fx.graph.file_to_index.get(&py_id).unwrap();
        let mut targets: Vec<NodeIndex> =
            resolution.file_edges.iter().map(|(_, to, _)| *to).collect();
        targets.sort();
        let mut expected = vec![s1, s2];
        expected.sort();
        assert_eq!(targets, expected);
        for (from, _, confidence) in &resolution.file_edges {
            assert_eq!(*from, py_idx);
            assert_eq!(*confidence, 0.8);
        }
        assert!(resolution.diagnostics.is_empty());
    }

    #[test]
    fn global_fallback_unique() {
        let mut fx = Fixture::new();
        let (py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("helpers.js", LangId::JavaScript);
        let helper = symbol(1, "helper", "helpers.js", LangId::JavaScript);
        let sym_idx = fx.add_symbol(&helper, js_id, "helpers.js", LangId::JavaScript);

        let call_sites = vec![client_call("orchestrator.py", "helper", 1.0)];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert_eq!(resolution.file_edges.len(), 1);
        let (from, to, confidence) = resolution.file_edges[0];
        let py_idx = *fx.graph.file_to_index.get(&py_id).unwrap();
        assert_eq!(from, py_idx);
        assert_eq!(to, sym_idx);
        assert_eq!(confidence, 0.6);
        assert!(resolution.diagnostics.is_empty());
    }

    #[test]
    fn global_fallback_ambiguous() {
        let mut fx = Fixture::new();
        let (py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (a_id, _) = fx.add_file("helpers.js", LangId::JavaScript);
        let (b_id, _) = fx.add_file("utils.js", LangId::JavaScript);
        let h1 = symbol(1, "helper", "helpers.js", LangId::JavaScript);
        let h2 = symbol(2, "helper", "utils.js", LangId::JavaScript);
        let s1 = fx.add_symbol(&h1, a_id, "helpers.js", LangId::JavaScript);
        let s2 = fx.add_symbol(&h2, b_id, "utils.js", LangId::JavaScript);

        let call_sites = vec![client_call("orchestrator.py", "helper", 1.0)];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert_eq!(resolution.file_edges.len(), 2);
        let py_idx = *fx.graph.file_to_index.get(&py_id).unwrap();
        let mut targets: Vec<NodeIndex> =
            resolution.file_edges.iter().map(|(_, to, _)| *to).collect();
        targets.sort();
        let mut expected = vec![s1, s2];
        expected.sort();
        assert_eq!(targets, expected);
        for (from, _, confidence) in &resolution.file_edges {
            assert_eq!(*from, py_idx);
            assert_eq!(*confidence, 0.5);
        }
        assert!(resolution.diagnostics.is_empty());
    }

    #[test]
    fn computed_name_cap() {
        let mut fx = Fixture::new();
        let (py_id, _) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("lib.js", LangId::JavaScript);
        let target = symbol(1, "fn_var", "lib.js", LangId::JavaScript);
        let sym_idx = fx.add_symbol(&target, js_id, "lib.js", LangId::JavaScript);

        // A computed first argument keeps the source text as function_name and
        // drops the site confidence to 0.4 (scanner convention).
        let call_sites = vec![client_call("orchestrator.py", "fn_var", 0.4)];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert_eq!(resolution.file_edges.len(), 1);
        let (from, to, confidence) = resolution.file_edges[0];
        let py_idx = *fx.graph.file_to_index.get(&py_id).unwrap();
        assert_eq!(from, py_idx);
        assert_eq!(to, sym_idx);
        assert_eq!(confidence, 0.4);
        assert!(resolution.diagnostics.is_empty());
    }

    #[test]
    fn unresolved_emits_diagnostic() {
        let mut fx = Fixture::new();
        let _ = fx.add_file("orchestrator.py", LangId::Python);

        let call_sites = vec![client_call("orchestrator.py", "no_such_fn", 1.0)];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );

        assert!(resolution.file_edges.is_empty());
        assert_eq!(resolution.diagnostics.len(), 1);
        let diag = &resolution.diagnostics[0];
        assert_eq!(diag.path, PathBuf::from("orchestrator.py"));
        assert_eq!(diag.severity, Severity::Warning);
        assert_eq!(
            diag.message,
            "unresolved MetaCall invocation target: 'no_such_fn'"
        );
        assert!(diag.source_range.is_none());
    }

    #[test]
    fn resolve_script_to_file_strategies() {
        let mut path_to_idx: HashMap<PathBuf, NodeIndex> = HashMap::new();
        let root_relative = NodeIndex::new(1);
        let source_relative = NodeIndex::new(2);
        let filename_fallback = NodeIndex::new(3);
        path_to_idx.insert(PathBuf::from("proj/lib/math.js"), root_relative);
        path_to_idx.insert(PathBuf::from("proj/src/util.js"), source_relative);
        path_to_idx.insert(
            PathBuf::from("vendor/third_party/legacy.js"),
            filename_fallback,
        );

        let root = Path::new("proj");
        let source_file = Path::new("proj/src/main.py");

        // Strategy 1: script relative to the project root.
        assert_eq!(
            resolve_script_to_file(root, "lib/math.js", source_file, &path_to_idx),
            Some(root_relative)
        );
        // Strategy 2: script relative to the source file's directory.
        assert_eq!(
            resolve_script_to_file(root, "util.js", source_file, &path_to_idx),
            Some(source_relative)
        );
        // Strategy 3: filename match after stripping path components.
        assert_eq!(
            resolve_script_to_file(root, "deep/path/legacy.js", source_file, &path_to_idx),
            Some(filename_fallback)
        );
        // No strategy matches.
        assert_eq!(
            resolve_script_to_file(root, "missing.js", source_file, &path_to_idx),
            None
        );
    }

    /// Characterization: a file-to-symbol client-call edge can never be
    /// absorbed by a scope-resolved symbol-to-symbol reference (endpoint node
    /// types differ, so `(src, dst, kind)` triples never collide).
    #[test]
    fn computed_name_client_call_survives_alongside_scope_reference() {
        use crate::graph::edge::EdgeKind;

        let mut fx = Fixture::new();
        let (py_id, py_idx) = fx.add_file("orchestrator.py", LangId::Python);
        let (js_id, _) = fx.add_file("math.js", LangId::JavaScript);
        let multiply = symbol(1, "multiply", "math.js", LangId::JavaScript);
        let sym_idx = fx.add_symbol(&multiply, js_id, "math.js", LangId::JavaScript);
        let caller = symbol(2, "caller", "orchestrator.py", LangId::Python);
        let caller_idx = fx.add_symbol(&caller, py_id, "orchestrator.py", LangId::Python);

        // Scope-resolved reference (what GraphBuilder produces): sym -> sym @ 1.0.
        fx.graph
            .add_edge_normalized(caller_idx, sym_idx, EdgeKind::Reference, 1.0);

        // Computed-name client call: file -> sym @ 0.4.
        let call_sites = vec![client_call("orchestrator.py", "multiply", 0.4)];
        let resolution = resolve_client_call_projections(
            &fx.graph,
            &fx.extractions,
            &call_sites,
            Path::new("."),
        );
        assert_eq!(resolution.file_edges.len(), 1);
        let (from, to, confidence) = resolution.file_edges[0];
        assert_eq!((from, to, confidence), (py_idx, sym_idx, 0.4));
        fx.graph
            .add_edge_normalized(from, to, EdgeKind::Reference, confidence);

        // Both edges coexist with their own confidences.
        let client_edge = fx.graph.graph().find_edge(py_idx, sym_idx).unwrap();
        let scope_edge = fx.graph.graph().find_edge(caller_idx, sym_idx).unwrap();
        assert_ne!(client_edge, scope_edge);
        assert_eq!(
            fx.graph
                .graph()
                .edge_weight(client_edge)
                .unwrap()
                .confidence,
            0.4
        );
        assert_eq!(
            fx.graph.graph().edge_weight(scope_edge).unwrap().confidence,
            1.0
        );
        assert!(resolution.diagnostics.is_empty());
    }

    /// A script path written with Windows separators must resolve on Unix.
    #[test]
    fn windows_script_separators_resolve_on_unix() {
        let dir = std::env::temp_dir().join("meta_ast_script_separator");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(dir.join("sub")).unwrap();
        let util = dir.join("sub").join("util.js");
        std::fs::write(&util, "export const x = 1;\n").unwrap();

        let path_to_idx =
            std::collections::HashMap::from([(util.clone(), petgraph::graph::NodeIndex::new(0))]);
        let source = dir.join("app.py");

        let resolved = resolve_script_to_file(&dir, "sub\\util.js", &source, &path_to_idx);
        assert!(
            resolved.is_some(),
            "a Windows-authored script path must resolve on Unix"
        );
        let _ = std::fs::remove_dir_all(&dir);
    }
}