depyler-oracle 4.1.1

ML-powered compile error classification and auto-fixing using aprender models
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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
//! Corpus Analysis for Tarantula Fault Localization
//!
//! Processes transpilation results from the reprorusted-python-cli corpus
//! to identify which transpiler decisions cause the most compilation failures.
//!
//! # DEPYLER-0631: Strategy #1 Implementation

use crate::tarantula::{
    FixPriority, SuspiciousTranspilerDecision, TarantulaAnalyzer, TarantulaResult,
    TranspilerDecision, TranspilerDecisionRecord,
};
use crate::OracleError;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Result of a single transpilation attempt
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TranspilationResult {
    /// Python source file path
    pub python_file: String,
    /// Whether transpilation succeeded (generated valid Rust)
    pub transpiled: bool,
    /// Whether the generated Rust compiled successfully
    pub compiled: bool,
    /// Rust error codes if compilation failed
    pub error_codes: Vec<String>,
    /// Rust error messages if compilation failed
    pub error_messages: Vec<String>,
    /// Decision trace from the transpiler
    pub decisions: Vec<TranspilerDecisionRecord>,
}

impl TranspilationResult {
    /// Create a successful result
    #[must_use]
    pub fn success(
        python_file: impl Into<String>,
        decisions: Vec<TranspilerDecisionRecord>,
    ) -> Self {
        Self {
            python_file: python_file.into(),
            transpiled: true,
            compiled: true,
            error_codes: vec![],
            error_messages: vec![],
            decisions,
        }
    }

    /// Create a compile failure result
    #[must_use]
    pub fn compile_failure(
        python_file: impl Into<String>,
        decisions: Vec<TranspilerDecisionRecord>,
        error_codes: Vec<String>,
        error_messages: Vec<String>,
    ) -> Self {
        Self {
            python_file: python_file.into(),
            transpiled: true,
            compiled: false,
            error_codes,
            error_messages,
            decisions,
        }
    }

    /// Create a transpilation failure result
    #[must_use]
    pub fn transpile_failure(python_file: impl Into<String>) -> Self {
        Self {
            python_file: python_file.into(),
            transpiled: false,
            compiled: false,
            error_codes: vec![],
            error_messages: vec![],
            decisions: vec![],
        }
    }
}

/// Corpus analyzer for batch Tarantula analysis
pub struct CorpusAnalyzer {
    analyzer: TarantulaAnalyzer,
    results: Vec<TranspilationResult>,
}

impl CorpusAnalyzer {
    /// Create a new corpus analyzer
    pub fn new() -> Result<Self, OracleError> {
        Ok(Self {
            analyzer: TarantulaAnalyzer::new()?,
            results: Vec::new(),
        })
    }

    /// Add a transpilation result to the corpus
    pub fn add_result(&mut self, result: TranspilationResult) -> Result<(), OracleError> {
        if result.compiled {
            self.analyzer
                .record_success(&result.python_file, result.decisions.clone())?;
        } else if result.transpiled {
            self.analyzer.record_failure(
                &result.python_file,
                result.decisions.clone(),
                result.error_codes.clone(),
                result.error_messages.clone(),
            )?;
        }
        // Skip files that failed to transpile (no decisions to analyze)

        self.results.push(result);
        Ok(())
    }

    /// Process multiple results in batch
    pub fn add_results(&mut self, results: Vec<TranspilationResult>) -> Result<(), OracleError> {
        for result in results {
            self.add_result(result)?;
        }
        Ok(())
    }

    /// Run Tarantula analysis on the corpus
    #[must_use]
    pub fn analyze(&self) -> CorpusAnalysisReport {
        let tarantula = self.analyzer.analyze();
        let (success, failure) = self.analyzer.session_counts();

        let transpile_success = self.results.iter().filter(|r| r.transpiled).count();
        let compile_success = self.results.iter().filter(|r| r.compiled).count();

        // Compute correlation BEFORE moving suspicious_decisions
        let decision_error_correlation = self.compute_decision_error_correlation(&tarantula);

        CorpusAnalysisReport {
            total_files: self.results.len(),
            transpile_success,
            compile_success,
            transpile_rate: if self.results.is_empty() {
                0.0
            } else {
                transpile_success as f32 / self.results.len() as f32 * 100.0
            },
            single_shot_rate: if self.results.is_empty() {
                0.0
            } else {
                compile_success as f32 / self.results.len() as f32 * 100.0
            },
            tarantula_success: success,
            tarantula_failure: failure,
            suspicious_decisions: tarantula.suspicious,
            error_frequency: self.compute_error_frequency(),
            decision_error_correlation,
        }
    }

    /// Compute error code frequency
    fn compute_error_frequency(&self) -> HashMap<String, usize> {
        let mut freq: HashMap<String, usize> = HashMap::new();
        for result in &self.results {
            for code in &result.error_codes {
                *freq.entry(code.clone()).or_default() += 1;
            }
        }
        freq
    }

    /// Compute correlation between decisions and error codes
    fn compute_decision_error_correlation(
        &self,
        tarantula: &TarantulaResult,
    ) -> Vec<DecisionErrorCorrelation> {
        let mut correlations = Vec::new();

        for suspicious in &tarantula.suspicious {
            if suspicious.suspiciousness > 0.3 {
                correlations.push(DecisionErrorCorrelation {
                    decision_type: suspicious.decision_type,
                    suspiciousness: suspicious.suspiciousness,
                    associated_errors: suspicious.associated_errors.clone(),
                    priority: suspicious.priority,
                    recommended_action: recommend_action(suspicious),
                });
            }
        }

        correlations
    }

    /// Get the top N suspicious decisions (returns owned data)
    #[must_use]
    pub fn top_suspicious(&self, n: usize) -> Vec<SuspiciousTranspilerDecision> {
        let result = self.analyzer.analyze();
        result.suspicious.into_iter().take(n).collect()
    }

    /// Clear the corpus
    pub fn clear(&mut self) -> Result<(), OracleError> {
        self.results.clear();
        self.analyzer = TarantulaAnalyzer::new()?;
        Ok(())
    }
}

impl std::fmt::Debug for CorpusAnalyzer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CorpusAnalyzer")
            .field("results", &self.results.len())
            .finish()
    }
}

/// Comprehensive corpus analysis report
#[derive(Debug, Clone)]
pub struct CorpusAnalysisReport {
    /// Total files in corpus
    pub total_files: usize,
    /// Files that transpiled successfully
    pub transpile_success: usize,
    /// Files that compiled successfully (single-shot)
    pub compile_success: usize,
    /// Transpilation success rate (%)
    pub transpile_rate: f32,
    /// Single-shot compile rate (%) - the key metric
    pub single_shot_rate: f32,
    /// Successful sessions in Tarantula
    pub tarantula_success: usize,
    /// Failed sessions in Tarantula
    pub tarantula_failure: usize,
    /// Suspicious decisions sorted by score
    pub suspicious_decisions: Vec<SuspiciousTranspilerDecision>,
    /// Error code frequency
    pub error_frequency: HashMap<String, usize>,
    /// Decision-error correlations
    pub decision_error_correlation: Vec<DecisionErrorCorrelation>,
}

impl CorpusAnalysisReport {
    /// Get top N suspicious decisions
    #[must_use]
    pub fn top_suspicious(&self, n: usize) -> Vec<&SuspiciousTranspilerDecision> {
        self.suspicious_decisions.iter().take(n).collect()
    }

    /// Get top N error codes by frequency
    #[must_use]
    pub fn top_errors(&self, n: usize) -> Vec<(&String, &usize)> {
        let mut errors: Vec<_> = self.error_frequency.iter().collect();
        errors.sort_by(|a, b| b.1.cmp(a.1));
        errors.into_iter().take(n).collect()
    }

    /// Check if we've reached the 80% single-shot target
    #[must_use]
    pub fn reached_target(&self) -> bool {
        self.single_shot_rate >= 80.0
    }

    /// Format as markdown report
    #[must_use]
    pub fn to_markdown(&self) -> String {
        let mut md = String::new();

        md.push_str("# Corpus Analysis Report\n\n");
        md.push_str("## Summary\n\n");
        md.push_str("| Metric | Value |\n");
        md.push_str("|--------|-------|\n");
        md.push_str(&format!("| Total Files | {} |\n", self.total_files));
        md.push_str(&format!(
            "| Transpile Success | {} |\n",
            self.transpile_success
        ));
        md.push_str(&format!("| Compile Success | {} |\n", self.compile_success));
        md.push_str(&format!(
            "| Transpile Rate | {:.1}% |\n",
            self.transpile_rate
        ));
        md.push_str(&format!(
            "| **Single-Shot Rate** | **{:.1}%** |\n",
            self.single_shot_rate
        ));
        md.push_str(&format!(
            "| Target (80%) | {} |\n",
            if self.reached_target() { "" } else { "" }
        ));

        md.push_str("\n## Top Suspicious Decisions\n\n");
        md.push_str("| Decision | Score | Fail | Success | Priority | Errors |\n");
        md.push_str("|----------|-------|------|---------|----------|--------|\n");

        for s in self.top_suspicious(10) {
            let errors = if s.associated_errors.is_empty() {
                "-".to_string()
            } else {
                s.associated_errors.join(", ")
            };
            md.push_str(&format!(
                "| {} | {:.2} | {} | {} | {:?} | {} |\n",
                s.decision_type,
                s.suspiciousness,
                s.fail_count,
                s.success_count,
                s.priority,
                errors
            ));
        }

        md.push_str("\n## Top Error Codes\n\n");
        md.push_str("| Error Code | Count |\n");
        md.push_str("|------------|-------|\n");

        for (code, count) in self.top_errors(10) {
            md.push_str(&format!("| {} | {} |\n", code, count));
        }

        md.push_str("\n## Recommended Actions\n\n");
        for corr in &self.decision_error_correlation {
            if corr.priority == FixPriority::Critical || corr.priority == FixPriority::High {
                md.push_str(&format!(
                    "- **{:?}** ({:.2}): {}\n",
                    corr.decision_type, corr.suspiciousness, corr.recommended_action
                ));
            }
        }

        md
    }
}

/// Correlation between a decision type and error codes
#[derive(Debug, Clone)]
pub struct DecisionErrorCorrelation {
    /// The decision type
    pub decision_type: TranspilerDecision,
    /// Suspiciousness score
    pub suspiciousness: f32,
    /// Associated error codes
    pub associated_errors: Vec<String>,
    /// Fix priority
    pub priority: FixPriority,
    /// Recommended action to fix
    pub recommended_action: String,
}

/// Generate recommended action for a suspicious decision
fn recommend_action(decision: &SuspiciousTranspilerDecision) -> String {
    match decision.decision_type {
        TranspilerDecision::TypeInference => {
            "Review type inference logic for common Python types".to_string()
        }
        TranspilerDecision::ModuleMapping => {
            "Add missing module mappings or improve stdlib coverage".to_string()
        }
        TranspilerDecision::MethodTranslation => {
            "Review method-to-function translation for Python builtins".to_string()
        }
        TranspilerDecision::OwnershipInference => {
            "Improve borrow vs clone vs move inference".to_string()
        }
        TranspilerDecision::ReturnTypeInference => {
            "Fix return type inference for fallible functions".to_string()
        }
        TranspilerDecision::ErrorHandling => "Review Result/Option wrapping strategy".to_string(),
        TranspilerDecision::ContainerMapping => {
            "Review list/dict/set container type mappings".to_string()
        }
        TranspilerDecision::ImportGeneration => {
            "Fix use statement generation for external crates".to_string()
        }
        _ => format!("Review {} decisions", decision.decision_type),
    }
}

/// Simulate decisions for a Python file based on common patterns
///
/// This is used when we don't have actual decision traces from the transpiler.
#[must_use]
pub fn simulate_decisions_from_errors(
    error_codes: &[String],
    error_messages: &[String],
) -> Vec<TranspilerDecisionRecord> {
    let mut decisions = Vec::new();

    for code in error_codes {
        match code.as_str() {
            "E0308" => {
                // Type mismatch
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::TypeInference,
                    "Type mismatch detected",
                ));
            }
            "E0433" => {
                // Unresolved import
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::ModuleMapping,
                    "Unresolved module import",
                ));
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::ImportGeneration,
                    "Missing use statement",
                ));
            }
            "E0599" => {
                // Method not found
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::MethodTranslation,
                    "Method not found on type",
                ));
            }
            "E0277" => {
                // Trait bound not satisfied
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::TypeInference,
                    "Trait bound not satisfied",
                ));
            }
            "E0425" => {
                // Unresolved name
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::ImportGeneration,
                    "Unresolved identifier",
                ));
            }
            "E0382" | "E0505" | "E0507" => {
                // Borrow checker errors
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::OwnershipInference,
                    "Borrow checker violation",
                ));
            }
            "E0106" => {
                // Missing lifetime
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::LifetimeInference,
                    "Missing lifetime specifier",
                ));
            }
            _ => {
                // Generic type inference issue
                decisions.push(TranspilerDecisionRecord::new(
                    TranspilerDecision::TypeInference,
                    format!("Error {}", code),
                ));
            }
        }
    }

    // Also check error messages for patterns
    for msg in error_messages {
        let msg_lower = msg.to_lowercase();
        if msg_lower.contains("subprocess") || msg_lower.contains("command") {
            decisions.push(TranspilerDecisionRecord::new(
                TranspilerDecision::ModuleMapping,
                "subprocess module usage",
            ));
        }
        if msg_lower.contains("datetime") || msg_lower.contains("time") {
            decisions.push(TranspilerDecisionRecord::new(
                TranspilerDecision::ModuleMapping,
                "datetime module usage",
            ));
        }
        if msg_lower.contains("os.") || msg_lower.contains("os::") {
            decisions.push(TranspilerDecisionRecord::new(
                TranspilerDecision::ModuleMapping,
                "os module usage",
            ));
        }
    }

    decisions
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_transpilation_result_success() {
        let result = TranspilationResult::success("test.py", vec![]);
        assert!(result.transpiled);
        assert!(result.compiled);
    }

    #[test]
    fn test_transpilation_result_compile_failure() {
        let result = TranspilationResult::compile_failure(
            "test.py",
            vec![],
            vec!["E0308".to_string()],
            vec!["type mismatch".to_string()],
        );
        assert!(result.transpiled);
        assert!(!result.compiled);
        assert_eq!(result.error_codes, vec!["E0308"]);
    }

    #[test]
    fn test_corpus_analyzer_new() {
        let analyzer = CorpusAnalyzer::new().unwrap();
        assert_eq!(analyzer.results.len(), 0);
    }

    #[test]
    fn test_corpus_analyzer_add_success() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        let result = TranspilationResult::success(
            "test.py",
            vec![TranspilerDecisionRecord::new(
                TranspilerDecision::TypeInference,
                "i32",
            )],
        );
        analyzer.add_result(result).unwrap();
        assert_eq!(analyzer.results.len(), 1);
    }

    #[test]
    fn test_corpus_analyzer_analysis() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();

        // Add some successes
        for i in 0..3 {
            analyzer
                .add_result(TranspilationResult::success(
                    format!("good_{}.py", i),
                    vec![TranspilerDecisionRecord::new(
                        TranspilerDecision::TypeInference,
                        "good",
                    )],
                ))
                .unwrap();
        }

        // Add some failures
        for i in 0..5 {
            analyzer
                .add_result(TranspilationResult::compile_failure(
                    format!("bad_{}.py", i),
                    vec![TranspilerDecisionRecord::new(
                        TranspilerDecision::ModuleMapping,
                        "bad module",
                    )],
                    vec!["E0433".to_string()],
                    vec!["unresolved import".to_string()],
                ))
                .unwrap();
        }

        let report = analyzer.analyze();
        assert_eq!(report.total_files, 8);
        assert_eq!(report.transpile_success, 8);
        assert_eq!(report.compile_success, 3);
        assert!((report.single_shot_rate - 37.5).abs() < 0.1);
    }

    #[test]
    fn test_corpus_analysis_report_markdown() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        analyzer
            .add_result(TranspilationResult::success("test.py", vec![]))
            .unwrap();
        let report = analyzer.analyze();
        let md = report.to_markdown();
        assert!(md.contains("Corpus Analysis Report"));
        assert!(md.contains("Single-Shot Rate"));
    }

    #[test]
    fn test_simulate_decisions_from_errors() {
        let decisions = simulate_decisions_from_errors(
            &["E0308".to_string(), "E0433".to_string()],
            &["subprocess not found".to_string()],
        );
        assert!(!decisions.is_empty());
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::TypeInference));
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
    }

    #[test]
    fn test_report_reached_target() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();

        // Add 80+ successes
        for i in 0..80 {
            analyzer
                .add_result(TranspilationResult::success(
                    format!("good_{}.py", i),
                    vec![],
                ))
                .unwrap();
        }

        // Add 20 failures
        for i in 0..20 {
            analyzer
                .add_result(TranspilationResult::compile_failure(
                    format!("bad_{}.py", i),
                    vec![],
                    vec!["E0001".to_string()],
                    vec![],
                ))
                .unwrap();
        }

        let report = analyzer.analyze();
        assert!(report.reached_target());
    }

    // ============================================================
    // Additional TranspilationResult Tests
    // ============================================================

    #[test]
    fn test_transpilation_result_transpile_failure() {
        let result = TranspilationResult::transpile_failure("broken.py");
        assert!(!result.transpiled);
        assert!(!result.compiled);
        assert!(result.error_codes.is_empty());
        assert!(result.decisions.is_empty());
    }

    #[test]
    fn test_transpilation_result_with_decisions() {
        let decisions = vec![
            TranspilerDecisionRecord::new(TranspilerDecision::TypeInference, "i32"),
            TranspilerDecisionRecord::new(TranspilerDecision::ModuleMapping, "std::collections"),
        ];
        let result = TranspilationResult::success("test.py", decisions.clone());
        assert_eq!(result.decisions.len(), 2);
        assert_eq!(
            result.decisions[0].decision_type,
            TranspilerDecision::TypeInference
        );
    }

    // ============================================================
    // CorpusAnalyzer Tests
    // ============================================================

    #[test]
    fn test_corpus_analyzer_add_transpile_failure() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        let result = TranspilationResult::transpile_failure("broken.py");
        analyzer.add_result(result).unwrap();
        assert_eq!(analyzer.results.len(), 1);

        // Analyze should work even with transpile failures
        let report = analyzer.analyze();
        assert_eq!(report.total_files, 1);
        assert_eq!(report.transpile_success, 0);
    }

    #[test]
    fn test_corpus_analyzer_add_results() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        let results = vec![
            TranspilationResult::success("a.py", vec![]),
            TranspilationResult::success("b.py", vec![]),
            TranspilationResult::compile_failure("c.py", vec![], vec!["E0001".to_string()], vec![]),
        ];
        analyzer.add_results(results).unwrap();
        assert_eq!(analyzer.results.len(), 3);
    }

    #[test]
    fn test_corpus_analyzer_clear() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        analyzer
            .add_result(TranspilationResult::success("test.py", vec![]))
            .unwrap();
        assert_eq!(analyzer.results.len(), 1);

        analyzer.clear().unwrap();
        assert_eq!(analyzer.results.len(), 0);
    }

    #[test]
    fn test_corpus_analyzer_top_suspicious() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        for i in 0..5 {
            analyzer
                .add_result(TranspilationResult::compile_failure(
                    format!("fail_{}.py", i),
                    vec![TranspilerDecisionRecord::new(
                        TranspilerDecision::TypeInference,
                        "bad",
                    )],
                    vec!["E0308".to_string()],
                    vec![],
                ))
                .unwrap();
        }

        let suspicious = analyzer.top_suspicious(3);
        assert!(suspicious.len() <= 3);
    }

    #[test]
    fn test_corpus_analyzer_debug() {
        let analyzer = CorpusAnalyzer::new().unwrap();
        let debug_str = format!("{:?}", analyzer);
        assert!(debug_str.contains("CorpusAnalyzer"));
        assert!(debug_str.contains("results"));
    }

    // ============================================================
    // CorpusAnalysisReport Tests
    // ============================================================

    #[test]
    fn test_report_top_suspicious() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        analyzer
            .add_result(TranspilationResult::compile_failure(
                "test.py",
                vec![TranspilerDecisionRecord::new(
                    TranspilerDecision::TypeInference,
                    "bad",
                )],
                vec!["E0308".to_string()],
                vec![],
            ))
            .unwrap();

        let report = analyzer.analyze();
        let top = report.top_suspicious(5);
        assert!(top.len() <= 5);
    }

    #[test]
    fn test_report_top_errors() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        for _ in 0..3 {
            analyzer
                .add_result(TranspilationResult::compile_failure(
                    "test.py",
                    vec![],
                    vec!["E0308".to_string()],
                    vec![],
                ))
                .unwrap();
        }
        analyzer
            .add_result(TranspilationResult::compile_failure(
                "test2.py",
                vec![],
                vec!["E0433".to_string()],
                vec![],
            ))
            .unwrap();

        let report = analyzer.analyze();
        let top_errors = report.top_errors(2);
        assert!(!top_errors.is_empty());
        // E0308 should be first with 3 occurrences
        assert_eq!(*top_errors[0].0, "E0308");
    }

    #[test]
    fn test_report_not_reached_target() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        for i in 0..10 {
            analyzer
                .add_result(TranspilationResult::compile_failure(
                    format!("fail_{}.py", i),
                    vec![],
                    vec!["E0001".to_string()],
                    vec![],
                ))
                .unwrap();
        }

        let report = analyzer.analyze();
        assert!(!report.reached_target());
    }

    #[test]
    fn test_report_empty_corpus() {
        let analyzer = CorpusAnalyzer::new().unwrap();
        let report = analyzer.analyze();
        assert_eq!(report.total_files, 0);
        assert_eq!(report.transpile_rate, 0.0);
        assert_eq!(report.single_shot_rate, 0.0);
    }

    #[test]
    fn test_report_markdown_with_errors() {
        let mut analyzer = CorpusAnalyzer::new().unwrap();
        analyzer
            .add_result(TranspilationResult::compile_failure(
                "test.py",
                vec![TranspilerDecisionRecord::new(
                    TranspilerDecision::ModuleMapping,
                    "missing",
                )],
                vec!["E0433".to_string()],
                vec!["unresolved import".to_string()],
            ))
            .unwrap();

        let report = analyzer.analyze();
        let md = report.to_markdown();
        assert!(md.contains("E0433"));
        assert!(md.contains("Top Error Codes"));
    }

    // ============================================================
    // simulate_decisions_from_errors Tests
    // ============================================================

    #[test]
    fn test_simulate_decisions_e0308() {
        let decisions = simulate_decisions_from_errors(&["E0308".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::TypeInference));
    }

    #[test]
    fn test_simulate_decisions_e0433() {
        let decisions = simulate_decisions_from_errors(&["E0433".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ImportGeneration));
    }

    #[test]
    fn test_simulate_decisions_e0599() {
        let decisions = simulate_decisions_from_errors(&["E0599".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::MethodTranslation));
    }

    #[test]
    fn test_simulate_decisions_e0277() {
        let decisions = simulate_decisions_from_errors(&["E0277".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::TypeInference));
    }

    #[test]
    fn test_simulate_decisions_e0425() {
        let decisions = simulate_decisions_from_errors(&["E0425".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ImportGeneration));
    }

    #[test]
    fn test_simulate_decisions_borrow_checker() {
        let decisions = simulate_decisions_from_errors(&["E0382".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::OwnershipInference));

        let decisions = simulate_decisions_from_errors(&["E0505".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::OwnershipInference));

        let decisions = simulate_decisions_from_errors(&["E0507".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::OwnershipInference));
    }

    #[test]
    fn test_simulate_decisions_e0106() {
        let decisions = simulate_decisions_from_errors(&["E0106".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::LifetimeInference));
    }

    #[test]
    fn test_simulate_decisions_unknown() {
        let decisions = simulate_decisions_from_errors(&["E9999".to_string()], &[]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::TypeInference));
    }

    #[test]
    fn test_simulate_decisions_message_subprocess() {
        let decisions =
            simulate_decisions_from_errors(&[], &["subprocess module not found".to_string()]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
    }

    #[test]
    fn test_simulate_decisions_message_datetime() {
        let decisions =
            simulate_decisions_from_errors(&[], &["datetime import failed".to_string()]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
    }

    #[test]
    fn test_simulate_decisions_message_os() {
        let decisions = simulate_decisions_from_errors(&[], &["os.path not found".to_string()]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
    }

    #[test]
    fn test_simulate_decisions_message_time() {
        let decisions = simulate_decisions_from_errors(&[], &["time module issue".to_string()]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
    }

    #[test]
    fn test_simulate_decisions_message_command() {
        let decisions = simulate_decisions_from_errors(&[], &["Command not found".to_string()]);
        assert!(decisions
            .iter()
            .any(|d| d.decision_type == TranspilerDecision::ModuleMapping));
    }

    // ============================================================
    // recommend_action Tests
    // ============================================================

    #[test]
    fn test_recommend_action_type_inference() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::TypeInference,
            suspiciousness: 0.8,
            fail_count: 10,
            success_count: 2,
            associated_errors: vec![],
            priority: FixPriority::Critical,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("type inference"));
    }

    #[test]
    fn test_recommend_action_module_mapping() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::ModuleMapping,
            suspiciousness: 0.7,
            fail_count: 8,
            success_count: 2,
            associated_errors: vec![],
            priority: FixPriority::High,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("module mapping"));
    }

    #[test]
    fn test_recommend_action_method_translation() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::MethodTranslation,
            suspiciousness: 0.6,
            fail_count: 6,
            success_count: 3,
            associated_errors: vec![],
            priority: FixPriority::Medium,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("method"));
    }

    #[test]
    fn test_recommend_action_ownership() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::OwnershipInference,
            suspiciousness: 0.5,
            fail_count: 5,
            success_count: 5,
            associated_errors: vec![],
            priority: FixPriority::Medium,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("borrow"));
    }

    #[test]
    fn test_recommend_action_return_type() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::ReturnTypeInference,
            suspiciousness: 0.4,
            fail_count: 4,
            success_count: 6,
            associated_errors: vec![],
            priority: FixPriority::Low,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("return type"));
    }

    #[test]
    fn test_recommend_action_error_handling() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::ErrorHandling,
            suspiciousness: 0.4,
            fail_count: 4,
            success_count: 6,
            associated_errors: vec![],
            priority: FixPriority::Low,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("Result") || action.contains("Option"));
    }

    #[test]
    fn test_recommend_action_container() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::ContainerMapping,
            suspiciousness: 0.4,
            fail_count: 4,
            success_count: 6,
            associated_errors: vec![],
            priority: FixPriority::Low,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("container"));
    }

    #[test]
    fn test_recommend_action_import() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::ImportGeneration,
            suspiciousness: 0.4,
            fail_count: 4,
            success_count: 6,
            associated_errors: vec![],
            priority: FixPriority::Low,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("use statement"));
    }

    #[test]
    fn test_recommend_action_other() {
        let decision = SuspiciousTranspilerDecision {
            decision_type: TranspilerDecision::LifetimeInference,
            suspiciousness: 0.4,
            fail_count: 4,
            success_count: 6,
            associated_errors: vec![],
            priority: FixPriority::Low,
        };
        let action = recommend_action(&decision);
        assert!(action.contains("Review"));
    }
}