depyler 4.1.1

A Python-to-Rust transpiler focusing on energy-efficient, safe code generation with progressive verification
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
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
//! Error Dependency Graph Analysis (GH-209 Phase 4)
//!
//! Builds a graph of error co-occurrences to identify:
//! - "Super-spreader" errors (high centrality)
//! - Error communities (clustered failure patterns)
//! - Root cause relationships

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

use super::analysis::{ExtendedAnalysisResult, SemanticDomain};

/// Node in the error graph (GH-209)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorNode {
    /// Node ID (unique)
    pub id: usize,
    /// Error code (e.g., "E0308")
    pub error_code: String,
    /// Files affected by this error
    pub files: Vec<String>,
    /// PageRank-style centrality score
    pub centrality: f64,
    /// Dominant semantic domain for this error
    pub domain: SemanticDomain,
}

impl ErrorNode {
    /// Get number of affected files
    pub fn file_count(&self) -> usize {
        self.files.len()
    }
}

/// Edge in the error graph (co-occurrence relationship)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorEdge {
    /// Source node ID
    pub from: usize,
    /// Target node ID
    pub to: usize,
    /// Co-occurrence weight (number of files with both errors)
    pub weight: f64,
}

/// Error community (connected component or cluster)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorCommunity {
    /// Community ID
    pub id: usize,
    /// Auto-generated name (e.g., "The AsyncIO Cluster")
    pub name: String,
    /// Error codes in this community
    pub error_codes: Vec<String>,
    /// Sum of centrality scores
    pub centrality_sum: f64,
    /// Number of files affected
    pub total_files: usize,
}

/// Error dependency graph (GH-209 Phase 4)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorGraph {
    /// Nodes (error types)
    pub nodes: Vec<ErrorNode>,
    /// Edges (co-occurrences)
    pub edges: Vec<ErrorEdge>,
    /// Node lookup by error code
    #[serde(skip)]
    node_map: HashMap<String, usize>,
    /// Adjacency list for graph traversal
    #[serde(skip)]
    adjacency: HashMap<usize, Vec<(usize, f64)>>,
}

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

impl ErrorGraph {
    /// Create empty graph
    pub fn new() -> Self {
        Self {
            nodes: Vec::new(),
            edges: Vec::new(),
            node_map: HashMap::new(),
            adjacency: HashMap::new(),
        }
    }

    /// Build graph from analysis results (GH-209)
    pub fn from_results(results: &[ExtendedAnalysisResult]) -> Self {
        let mut graph = Self::new();

        // Group files by error code
        let mut error_files: HashMap<String, Vec<String>> = HashMap::new();
        let mut error_domains: HashMap<String, Vec<SemanticDomain>> = HashMap::new();

        for result in results {
            if !result.base.success {
                if let Some(code) = &result.base.error_code {
                    error_files
                        .entry(code.clone())
                        .or_default()
                        .push(result.base.name.clone());
                    error_domains
                        .entry(code.clone())
                        .or_default()
                        .push(result.semantic_domain);
                }
            }
        }

        // Create nodes
        for (code, files) in &error_files {
            let domains = match error_domains.get(code) {
                Some(d) => d,
                None => continue,
            };
            let dominant_domain = find_dominant_domain(domains);

            let node = ErrorNode {
                id: graph.nodes.len(),
                error_code: code.clone(),
                files: files.clone(),
                centrality: 0.0, // Will be calculated later
                domain: dominant_domain,
            };

            graph.node_map.insert(code.clone(), node.id);
            graph.nodes.push(node);
        }

        // Build co-occurrence map
        let mut cooccur: HashMap<(String, String), usize> = HashMap::new();

        // Group errors by file
        let mut file_errors: HashMap<String, Vec<String>> = HashMap::new();
        for result in results {
            if !result.base.success {
                if let Some(code) = &result.base.error_code {
                    file_errors
                        .entry(result.base.name.clone())
                        .or_default()
                        .push(code.clone());
                }
            }
        }

        // Count co-occurrences
        for errors in file_errors.values() {
            let unique: Vec<_> = errors.iter().collect::<HashSet<_>>().into_iter().collect();
            for (i, &e1) in unique.iter().enumerate() {
                for &e2 in unique.iter().skip(i + 1) {
                    let key = if e1 < e2 {
                        (e1.clone(), e2.clone())
                    } else {
                        (e2.clone(), e1.clone())
                    };
                    *cooccur.entry(key).or_insert(0) += 1;
                }
            }
        }

        // Create edges
        for ((e1, e2), count) in cooccur {
            if let (Some(&from), Some(&to)) = (graph.node_map.get(&e1), graph.node_map.get(&e2)) {
                let weight = count as f64;

                graph.edges.push(ErrorEdge { from, to, weight });

                graph.adjacency.entry(from).or_default().push((to, weight));
                graph.adjacency.entry(to).or_default().push((from, weight));
            }
        }

        // Calculate centrality
        graph.calculate_centrality();

        graph
    }

    /// Calculate PageRank-style centrality for all nodes
    pub fn calculate_centrality(&mut self) {
        let n = self.nodes.len();
        if n == 0 {
            return;
        }

        let damping = 0.85;
        let iterations = 100;
        let tolerance = 1e-6;

        // Initialize scores
        let mut scores = vec![1.0 / n as f64; n];
        let mut new_scores = vec![0.0; n];

        for _ in 0..iterations {
            let mut max_diff: f64 = 0.0;

            for i in 0..n {
                let mut sum = 0.0;

                // Sum contributions from neighbors
                if let Some(neighbors) = self.adjacency.get(&i) {
                    for &(j, weight) in neighbors {
                        let out_degree =
                            self.adjacency.get(&j).map(|n| n.len()).unwrap_or(1) as f64;
                        sum += scores[j] * weight / out_degree;
                    }
                }

                new_scores[i] = (1.0 - damping) / n as f64 + damping * sum;
                max_diff = max_diff.max((new_scores[i] - scores[i]).abs());
            }

            std::mem::swap(&mut scores, &mut new_scores);

            if max_diff < tolerance {
                break;
            }
        }

        // Normalize and assign
        let total: f64 = scores.iter().sum();
        for (i, node) in self.nodes.iter_mut().enumerate() {
            node.centrality = if total > 0.0 {
                scores[i] / total
            } else {
                1.0 / n as f64
            };
        }
    }

    /// Find connected components (communities)
    pub fn find_communities(&self) -> Vec<ErrorCommunity> {
        let n = self.nodes.len();
        let mut visited = vec![false; n];
        let mut communities = Vec::new();

        for start in 0..n {
            if visited[start] {
                continue;
            }

            // BFS to find connected component
            let mut component = Vec::new();
            let mut queue = vec![start];

            while let Some(node) = queue.pop() {
                if visited[node] {
                    continue;
                }
                visited[node] = true;
                component.push(node);

                if let Some(neighbors) = self.adjacency.get(&node) {
                    for &(neighbor, _) in neighbors {
                        if !visited[neighbor] {
                            queue.push(neighbor);
                        }
                    }
                }
            }

            // Build community
            let error_codes: Vec<String> = component
                .iter()
                .map(|&i| self.nodes[i].error_code.clone())
                .collect();

            let centrality_sum: f64 = component.iter().map(|&i| self.nodes[i].centrality).sum();

            let total_files: usize = component.iter().map(|&i| self.nodes[i].files.len()).sum();

            let name = generate_community_name(&error_codes, &self.nodes, &component);

            communities.push(ErrorCommunity {
                id: communities.len(),
                name,
                error_codes,
                centrality_sum,
                total_files,
            });
        }

        // Sort by centrality descending
        communities.sort_by(|a, b| {
            b.centrality_sum
                .partial_cmp(&a.centrality_sum)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        communities
    }

    /// Get top N central nodes
    pub fn top_central(&self, n: usize) -> Vec<&ErrorNode> {
        let mut sorted: Vec<_> = self.nodes.iter().collect();
        sorted.sort_by(|a, b| {
            b.centrality
                .partial_cmp(&a.centrality)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        sorted.into_iter().take(n).collect()
    }

    /// Get node count
    pub fn node_count(&self) -> usize {
        self.nodes.len()
    }

    /// Get edge count
    pub fn edge_count(&self) -> usize {
        self.edges.len()
    }
}

/// Find dominant semantic domain from list
fn find_dominant_domain(domains: &[SemanticDomain]) -> SemanticDomain {
    let mut counts: HashMap<SemanticDomain, usize> = HashMap::new();
    for &domain in domains {
        *counts.entry(domain).or_insert(0) += 1;
    }
    counts
        .into_iter()
        .max_by_key(|(_, count)| *count)
        .map(|(domain, _)| domain)
        .unwrap_or(SemanticDomain::Unknown)
}

/// Generate community name based on error types
fn generate_community_name(
    error_codes: &[String],
    nodes: &[ErrorNode],
    component: &[usize],
) -> String {
    // Find the most central error in the component
    let top_error = component
        .iter()
        .max_by(|&&a, &&b| {
            nodes[a]
                .centrality
                .partial_cmp(&nodes[b].centrality)
                .unwrap()
        })
        .map(|&i| &nodes[i].error_code)
        .unwrap_or(&error_codes[0]);

    let theme = match top_error.as_str() {
        "E0308" => "Type Mismatch",
        "E0425" => "Scope Resolution",
        "E0433" => "Module Import",
        "E0277" => "Trait Bounds",
        "E0599" => "Method Resolution",
        "E0382" => "Ownership",
        "E0502" | "E0499" => "Borrowing",
        "E0106" | "E0495" | "E0621" => "Lifetime",
        _ => "Compilation",
    };

    let size = component.len();
    if size == 1 {
        format!("Isolated {} Error", theme)
    } else {
        format!("The {} Cluster ({} errors)", theme, size)
    }
}

/// Graph analysis results (GH-209)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GraphAnalysis {
    /// The error graph
    pub graph: ErrorGraph,
    /// Discovered communities
    pub communities: Vec<ErrorCommunity>,
    /// Top central errors
    pub top_central: Vec<String>,
    /// Graph density (edges / possible edges)
    pub density: f64,
}

impl GraphAnalysis {
    /// Build full analysis from results
    pub fn from_results(results: &[ExtendedAnalysisResult]) -> Self {
        let graph = ErrorGraph::from_results(results);
        let communities = graph.find_communities();

        let top_central: Vec<String> = graph
            .top_central(5)
            .iter()
            .map(|n| n.error_code.clone())
            .collect();

        let n = graph.node_count();
        let density = if n > 1 {
            let possible_edges = n * (n - 1) / 2;
            graph.edge_count() as f64 / possible_edges as f64
        } else {
            0.0
        };

        Self {
            graph,
            communities,
            top_central,
            density,
        }
    }

    /// Get community count
    pub fn community_count(&self) -> usize {
        self.communities.len()
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::report_cmd::analysis::{AnalysisResult, AstFeatures};

    fn make_result(name: &str, success: bool, error_code: Option<&str>) -> ExtendedAnalysisResult {
        ExtendedAnalysisResult {
            base: AnalysisResult {
                name: name.to_string(),
                success,
                error_code: error_code.map(String::from),
                error_message: None,
            },
            semantic_domain: SemanticDomain::CoreLanguage,
            ast_features: AstFeatures::default(),
            imports: vec![],
        }
    }

    #[test]
    fn test_error_graph_new() {
        let graph = ErrorGraph::new();
        assert!(graph.nodes.is_empty());
        assert!(graph.edges.is_empty());
    }

    #[test]
    fn test_error_graph_default() {
        let graph = ErrorGraph::default();
        assert_eq!(graph.node_count(), 0);
        assert_eq!(graph.edge_count(), 0);
    }

    #[test]
    fn test_error_graph_from_empty() {
        let results: Vec<ExtendedAnalysisResult> = vec![];
        let graph = ErrorGraph::from_results(&results);
        assert!(graph.nodes.is_empty());
    }

    #[test]
    fn test_error_graph_from_all_pass() {
        let results = vec![
            make_result("a.py", true, None),
            make_result("b.py", true, None),
        ];
        let graph = ErrorGraph::from_results(&results);
        assert!(graph.nodes.is_empty());
    }

    #[test]
    fn test_error_graph_single_error() {
        let results = vec![make_result("a.py", false, Some("E0308"))];
        let graph = ErrorGraph::from_results(&results);

        assert_eq!(graph.node_count(), 1);
        assert_eq!(graph.edge_count(), 0);
        assert_eq!(graph.nodes[0].error_code, "E0308");
    }

    #[test]
    fn test_error_graph_multiple_errors() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0425")),
            make_result("c.py", false, Some("E0308")),
        ];
        let graph = ErrorGraph::from_results(&results);

        assert_eq!(graph.node_count(), 2);
        assert!(graph.nodes.iter().any(|n| n.error_code == "E0308"));
        assert!(graph.nodes.iter().any(|n| n.error_code == "E0425"));
    }

    #[test]
    fn test_error_graph_file_count() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0308")),
            make_result("c.py", false, Some("E0308")),
        ];
        let graph = ErrorGraph::from_results(&results);

        let e0308_node = graph
            .nodes
            .iter()
            .find(|n| n.error_code == "E0308")
            .unwrap();
        assert_eq!(e0308_node.file_count(), 3);
    }

    #[test]
    fn test_error_graph_centrality() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0425")),
        ];
        let graph = ErrorGraph::from_results(&results);

        // Centrality should be non-negative and sum to ~1
        let total: f64 = graph.nodes.iter().map(|n| n.centrality).sum();
        assert!((total - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_error_graph_top_central() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0308")),
            make_result("c.py", false, Some("E0425")),
        ];
        let graph = ErrorGraph::from_results(&results);
        let top = graph.top_central(1);

        assert_eq!(top.len(), 1);
    }

    #[test]
    fn test_find_communities_isolated() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0425")),
        ];
        let graph = ErrorGraph::from_results(&results);
        let communities = graph.find_communities();

        // Two isolated nodes = two communities
        assert_eq!(communities.len(), 2);
    }

    #[test]
    fn test_find_dominant_domain() {
        let domains = vec![
            SemanticDomain::External,
            SemanticDomain::External,
            SemanticDomain::CoreLanguage,
        ];
        assert_eq!(find_dominant_domain(&domains), SemanticDomain::External);
    }

    #[test]
    fn test_find_dominant_domain_empty() {
        let domains: Vec<SemanticDomain> = vec![];
        assert_eq!(find_dominant_domain(&domains), SemanticDomain::Unknown);
    }

    #[test]
    fn test_generate_community_name_isolated() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0308".to_string(),
            files: vec!["a.py".to_string()],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0308".to_string()], &nodes, &[0]);
        assert!(name.contains("Type Mismatch"));
        assert!(name.contains("Isolated"));
    }

    #[test]
    fn test_generate_community_name_cluster() {
        let nodes = vec![
            ErrorNode {
                id: 0,
                error_code: "E0308".to_string(),
                files: vec![],
                centrality: 0.6,
                domain: SemanticDomain::CoreLanguage,
            },
            ErrorNode {
                id: 1,
                error_code: "E0425".to_string(),
                files: vec![],
                centrality: 0.4,
                domain: SemanticDomain::CoreLanguage,
            },
        ];
        let name =
            generate_community_name(&["E0308".to_string(), "E0425".to_string()], &nodes, &[0, 1]);
        assert!(name.contains("Cluster"));
        assert!(name.contains("2 errors"));
    }

    #[test]
    fn test_graph_analysis_from_results() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0425")),
            make_result("c.py", false, Some("E0308")),
        ];
        let analysis = GraphAnalysis::from_results(&results);

        assert_eq!(analysis.graph.node_count(), 2);
        assert!(analysis.community_count() >= 1);
        assert!(!analysis.top_central.is_empty());
    }

    #[test]
    fn test_graph_analysis_density_empty() {
        let results: Vec<ExtendedAnalysisResult> = vec![];
        let analysis = GraphAnalysis::from_results(&results);
        assert_eq!(analysis.density, 0.0);
    }

    #[test]
    fn test_graph_analysis_density_single() {
        let results = vec![make_result("a.py", false, Some("E0308"))];
        let analysis = GraphAnalysis::from_results(&results);
        assert_eq!(analysis.density, 0.0); // Single node, no edges possible
    }

    #[test]
    fn test_error_community_fields() {
        let community = ErrorCommunity {
            id: 0,
            name: "Test".to_string(),
            error_codes: vec!["E0308".to_string()],
            centrality_sum: 0.5,
            total_files: 10,
        };
        assert_eq!(community.id, 0);
        assert_eq!(community.total_files, 10);
    }

    #[test]
    fn test_error_edge_fields() {
        let edge = ErrorEdge {
            from: 0,
            to: 1,
            weight: 2.5,
        };
        assert_eq!(edge.from, 0);
        assert_eq!(edge.to, 1);
        assert!((edge.weight - 2.5).abs() < 1e-6);
    }

    #[test]
    fn test_error_node_fields() {
        let node = ErrorNode {
            id: 0,
            error_code: "E0308".to_string(),
            files: vec!["a.py".to_string(), "b.py".to_string()],
            centrality: 0.75,
            domain: SemanticDomain::External,
        };
        assert_eq!(node.file_count(), 2);
        assert_eq!(node.domain, SemanticDomain::External);
    }

    // ===== Session 11: Coverage for untested code paths =====

    #[test]
    fn test_s11_co_occurrence_edges() {
        // Two different errors in the same file should create an edge
        let results = vec![
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "shared.py".to_string(),
                    success: false,
                    error_code: Some("E0308".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "shared.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
        ];
        let graph = ErrorGraph::from_results(&results);
        assert_eq!(graph.node_count(), 2);
        assert_eq!(graph.edge_count(), 1);
    }

    #[test]
    fn test_s11_co_occurrence_weight() {
        // Same error pair in multiple files = higher weight
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "a.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            make_result("b.py", false, Some("E0308")),
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "b.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
        ];
        let graph = ErrorGraph::from_results(&results);
        assert_eq!(graph.edge_count(), 1);
        assert!((graph.edges[0].weight - 2.0).abs() < 0.01);
    }

    #[test]
    fn test_s11_three_errors_same_file() {
        // Three errors in same file should produce 3 co-occurrence edges
        let results = vec![
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "complex.py".to_string(),
                    success: false,
                    error_code: Some("E0308".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "complex.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "complex.py".to_string(),
                    success: false,
                    error_code: Some("E0277".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
        ];
        let graph = ErrorGraph::from_results(&results);
        assert_eq!(graph.node_count(), 3);
        assert_eq!(graph.edge_count(), 3); // C(3,2) = 3 pairs
    }

    #[test]
    fn test_s11_connected_community() {
        // Errors co-occurring should form a single community
        let results = vec![
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "file.py".to_string(),
                    success: false,
                    error_code: Some("E0308".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "file.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
        ];
        let graph = ErrorGraph::from_results(&results);
        let communities = graph.find_communities();
        assert_eq!(communities.len(), 1);
        assert_eq!(communities[0].error_codes.len(), 2);
    }

    #[test]
    fn test_s11_disconnected_communities() {
        // Errors in separate files with no co-occurrence = separate communities
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0425")),
            make_result("c.py", false, Some("E0277")),
        ];
        let graph = ErrorGraph::from_results(&results);
        let communities = graph.find_communities();
        assert_eq!(communities.len(), 3);
    }

    #[test]
    fn test_s11_community_name_trait_bounds() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0277".to_string(),
            files: vec!["a.py".to_string()],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0277".to_string()], &nodes, &[0]);
        assert!(name.contains("Trait Bounds"));
    }

    #[test]
    fn test_s11_community_name_ownership() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0382".to_string(),
            files: vec![],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0382".to_string()], &nodes, &[0]);
        assert!(name.contains("Ownership"));
    }

    #[test]
    fn test_s11_community_name_borrowing() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0502".to_string(),
            files: vec![],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0502".to_string()], &nodes, &[0]);
        assert!(name.contains("Borrowing"));
    }

    #[test]
    fn test_s11_community_name_lifetime() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0106".to_string(),
            files: vec![],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0106".to_string()], &nodes, &[0]);
        assert!(name.contains("Lifetime"));
    }

    #[test]
    fn test_s11_community_name_method_resolution() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0599".to_string(),
            files: vec![],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0599".to_string()], &nodes, &[0]);
        assert!(name.contains("Method Resolution"));
    }

    #[test]
    fn test_s11_community_name_module_import() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E0433".to_string(),
            files: vec![],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E0433".to_string()], &nodes, &[0]);
        assert!(name.contains("Module Import"));
    }

    #[test]
    fn test_s11_community_name_unknown() {
        let nodes = vec![ErrorNode {
            id: 0,
            error_code: "E9999".to_string(),
            files: vec![],
            centrality: 1.0,
            domain: SemanticDomain::CoreLanguage,
        }];
        let name = generate_community_name(&["E9999".to_string()], &nodes, &[0]);
        assert!(name.contains("Compilation"));
    }

    #[test]
    fn test_s11_centrality_convergence() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0308")),
            make_result("c.py", false, Some("E0308")),
            make_result("d.py", false, Some("E0425")),
        ];
        let graph = ErrorGraph::from_results(&results);
        // All centrality values should be >= 0
        for node in &graph.nodes {
            assert!(node.centrality >= 0.0);
        }
        // Sum should be close to 1.0
        let total: f64 = graph.nodes.iter().map(|n| n.centrality).sum();
        assert!((total - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_s11_graph_analysis_with_edges() {
        let results = vec![
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "same.py".to_string(),
                    success: false,
                    error_code: Some("E0308".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "same.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
        ];
        let analysis = GraphAnalysis::from_results(&results);
        assert!(analysis.density > 0.0);
        assert_eq!(analysis.community_count(), 1);
    }

    #[test]
    fn test_s11_top_central_more_than_nodes() {
        let results = vec![make_result("a.py", false, Some("E0308"))];
        let graph = ErrorGraph::from_results(&results);
        let top = graph.top_central(10);
        assert_eq!(top.len(), 1);
    }

    #[test]
    fn test_s11_community_total_files() {
        let results = vec![
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "file.py".to_string(),
                    success: false,
                    error_code: Some("E0308".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
            ExtendedAnalysisResult {
                base: AnalysisResult {
                    name: "file.py".to_string(),
                    success: false,
                    error_code: Some("E0425".to_string()),
                    error_message: None,
                },
                semantic_domain: SemanticDomain::CoreLanguage,
                ast_features: AstFeatures::default(),
                imports: vec![],
            },
        ];
        let graph = ErrorGraph::from_results(&results);
        let communities = graph.find_communities();
        assert_eq!(communities.len(), 1);
        assert_eq!(communities[0].total_files, 2); // 1 file per node
    }

    #[test]
    fn test_s11_community_centrality_sum() {
        let results = vec![
            make_result("a.py", false, Some("E0308")),
            make_result("b.py", false, Some("E0425")),
        ];
        let graph = ErrorGraph::from_results(&results);
        let communities = graph.find_communities();
        let total_centrality: f64 = communities.iter().map(|c| c.centrality_sum).sum();
        assert!((total_centrality - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_s11_serialization_roundtrip() {
        let results = vec![make_result("a.py", false, Some("E0308"))];
        let analysis = GraphAnalysis::from_results(&results);
        let json = serde_json::to_string(&analysis).unwrap();
        let deserialized: GraphAnalysis = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.graph.node_count(), 1);
    }
}