ruchy 4.2.1

A systems scripting language that transpiles to idiomatic Rust with extreme quality engineering
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
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
//! Quality gate enforcement system (RUCHY-0815)
use crate::quality::scoring::{Grade, QualityScore};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
/// Quality gate configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QualityGateConfig {
    /// Minimum overall score required (0.0-1.0)
    pub min_score: f64,
    /// Minimum grade required
    pub min_grade: Grade,
    /// Component-specific thresholds
    pub component_thresholds: ComponentThresholds,
    /// Anti-gaming rules
    pub anti_gaming: AntiGamingRules,
    /// CI/CD integration settings
    pub ci_integration: CiIntegration,
    /// Project-specific overrides
    pub project_overrides: HashMap<String, f64>,
}
/// Component-specific quality thresholds
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentThresholds {
    /// Minimum correctness score (0.0-1.0)
    pub correctness: f64,
    /// Minimum performance score (0.0-1.0)
    pub performance: f64,
    /// Minimum maintainability score (0.0-1.0)
    pub maintainability: f64,
    /// Minimum safety score (0.0-1.0)
    pub safety: f64,
    /// Minimum idiomaticity score (0.0-1.0)
    pub idiomaticity: f64,
}
/// Anti-gaming rules to prevent score manipulation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AntiGamingRules {
    /// Minimum confidence level required (0.0-1.0)
    pub min_confidence: f64,
    /// Maximum cache hit rate allowed (0.0-1.0) - prevents stale analysis
    pub max_cache_hit_rate: f64,
    /// Require deep analysis for critical files
    pub require_deep_analysis: Vec<String>,
    /// Penalty for files that are too small (gaming by splitting)
    pub min_file_size_bytes: usize,
    /// Penalty for excessive test file ratios (gaming with trivial tests)
    pub max_test_ratio: f64,
}
/// CI/CD integration configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CiIntegration {
    /// Fail CI/CD pipeline on gate failure
    pub fail_on_violation: bool,
    /// Export results in `JUnit` XML format
    pub junit_xml: bool,
    /// Export results in JSON format for tooling
    pub json_output: bool,
    /// Send notifications on quality degradation
    pub notifications: NotificationConfig,
    /// Block merge requests below threshold
    pub block_merge: bool,
}
/// Notification configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NotificationConfig {
    /// Enable Slack notifications
    pub slack: bool,
    /// Enable email notifications  
    pub email: bool,
    /// Webhook URL for custom notifications
    pub webhook: Option<String>,
}
/// Quality gate enforcement result
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct GateResult {
    /// Whether the quality gate passed
    pub passed: bool,
    /// Overall score achieved
    pub score: f64,
    /// Grade achieved
    pub grade: Grade,
    /// Specific violations found
    pub violations: Vec<Violation>,
    /// Confidence in the result
    pub confidence: f64,
    /// Anti-gaming warnings
    pub gaming_warnings: Vec<String>,
}
/// Specific quality gate violation
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct Violation {
    /// Type of violation
    pub violation_type: ViolationType,
    /// Actual value that caused violation
    pub actual: f64,
    /// Required threshold
    pub required: f64,
    /// Severity of the violation
    pub severity: Severity,
    /// Human-readable message
    pub message: String,
}
/// Types of quality gate violations
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ViolationType {
    OverallScore,
    Grade,
    Correctness,
    Performance,
    Maintainability,
    Safety,
    Idiomaticity,
    Confidence,
    Gaming,
}
/// Violation severity levels
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum Severity {
    Critical, // Must fix to pass
    High,     // Should fix soon
    Medium,   // Should improve
    Low,      // Nice to improve
}
/// Quality gate enforcer
pub struct QualityGateEnforcer {
    config: QualityGateConfig,
}
impl Default for QualityGateConfig {
    fn default() -> Self {
        Self {
            min_score: 0.7, // B- grade minimum
            min_grade: Grade::BMinus,
            component_thresholds: ComponentThresholds {
                correctness: 0.8,     // High correctness required
                performance: 0.6,     // Moderate performance required
                maintainability: 0.7, // Good maintainability required
                safety: 0.8,          // High safety required
                idiomaticity: 0.5,    // Basic idiomaticity required
            },
            anti_gaming: AntiGamingRules {
                min_confidence: 0.6,
                max_cache_hit_rate: 0.8,
                require_deep_analysis: vec!["src/main.rs".to_string(), "src/lib.rs".to_string()],
                min_file_size_bytes: 100,
                max_test_ratio: 2.0,
            },
            ci_integration: CiIntegration {
                fail_on_violation: true,
                junit_xml: true,
                json_output: true,
                notifications: NotificationConfig {
                    slack: false,
                    email: false,
                    webhook: None,
                },
                block_merge: true,
            },
            project_overrides: HashMap::new(),
        }
    }
}
impl QualityGateEnforcer {
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::gates::QualityGateEnforcer;
    ///
    /// let instance = QualityGateEnforcer::new();
    /// // Verify behavior
    /// ```
    pub fn new(config: QualityGateConfig) -> Self {
        Self { config }
    }
    /// Load configuration from .ruchy/score.toml
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::gates::QualityGateEnforcer;
    ///
    /// let mut instance = QualityGateEnforcer::new();
    /// let result = instance.load_config();
    /// // Verify behavior
    /// ```
    pub fn load_config(project_root: &Path) -> anyhow::Result<QualityGateConfig> {
        let config_path = project_root.join(".ruchy").join("score.toml");
        if config_path.exists() {
            let content = std::fs::read_to_string(&config_path)?;
            let config: QualityGateConfig = toml::from_str(&content)?;
            Ok(config)
        } else {
            // Create default configuration file
            let default_config = QualityGateConfig::default();
            std::fs::create_dir_all(project_root.join(".ruchy"))?;
            let toml_content = toml::to_string_pretty(&default_config)?;
            std::fs::write(&config_path, toml_content)?;
            Ok(default_config)
        }
    }
    /// Enforce quality gates on a score
    /// # Examples
    ///
    /// ```
    /// use ruchy::quality::gates::QualityGateEnforcer;
    ///
    /// let mut instance = QualityGateEnforcer::new();
    /// let result = instance.enforce_gates();
    /// // Verify behavior
    /// ```
    pub fn enforce_gates(&self, score: &QualityScore, file_path: Option<&PathBuf>) -> GateResult {
        let mut violations = Vec::new();
        let mut gaming_warnings = Vec::new();
        // Check overall score threshold
        if score.value < self.config.min_score {
            violations.push(Violation {
                violation_type: ViolationType::OverallScore,
                actual: score.value,
                required: self.config.min_score,
                severity: Severity::Critical,
                message: format!(
                    "Overall score {:.1}% below minimum {:.1}%",
                    score.value * 100.0,
                    self.config.min_score * 100.0
                ),
            });
        }
        // Check grade requirement
        if score.grade < self.config.min_grade {
            violations.push(Violation {
                violation_type: ViolationType::Grade,
                actual: score.value,
                required: self.config.min_score,
                severity: Severity::Critical,
                message: format!(
                    "Grade {} below minimum {}",
                    score.grade, self.config.min_grade
                ),
            });
        }
        // Check component thresholds
        self.check_component_thresholds(score, &mut violations);
        // Check anti-gaming rules
        self.check_anti_gaming_rules(score, file_path, &mut gaming_warnings, &mut violations);
        // Check confidence threshold
        if score.confidence < self.config.anti_gaming.min_confidence {
            violations.push(Violation {
                violation_type: ViolationType::Confidence,
                actual: score.confidence,
                required: self.config.anti_gaming.min_confidence,
                severity: Severity::High,
                message: format!(
                    "Confidence {:.1}% below minimum {:.1}%",
                    score.confidence * 100.0,
                    self.config.anti_gaming.min_confidence * 100.0
                ),
            });
        }
        let passed = violations.iter().all(|v| v.severity != Severity::Critical);
        GateResult {
            passed,
            score: score.value,
            grade: score.grade,
            violations,
            confidence: score.confidence,
            gaming_warnings,
        }
    }
    fn check_component_thresholds(&self, score: &QualityScore, violations: &mut Vec<Violation>) {
        let thresholds = &self.config.component_thresholds;
        if score.components.correctness < thresholds.correctness {
            violations.push(Violation {
                violation_type: ViolationType::Correctness,
                actual: score.components.correctness,
                required: thresholds.correctness,
                severity: Severity::Critical,
                message: format!(
                    "Correctness {:.1}% below minimum {:.1}%",
                    score.components.correctness * 100.0,
                    thresholds.correctness * 100.0
                ),
            });
        }
        if score.components.performance < thresholds.performance {
            violations.push(Violation {
                violation_type: ViolationType::Performance,
                actual: score.components.performance,
                required: thresholds.performance,
                severity: Severity::High,
                message: format!(
                    "Performance {:.1}% below minimum {:.1}%",
                    score.components.performance * 100.0,
                    thresholds.performance * 100.0
                ),
            });
        }
        if score.components.maintainability < thresholds.maintainability {
            violations.push(Violation {
                violation_type: ViolationType::Maintainability,
                actual: score.components.maintainability,
                required: thresholds.maintainability,
                severity: Severity::High,
                message: format!(
                    "Maintainability {:.1}% below minimum {:.1}%",
                    score.components.maintainability * 100.0,
                    thresholds.maintainability * 100.0
                ),
            });
        }
        if score.components.safety < thresholds.safety {
            violations.push(Violation {
                violation_type: ViolationType::Safety,
                actual: score.components.safety,
                required: thresholds.safety,
                severity: Severity::Critical,
                message: format!(
                    "Safety {:.1}% below minimum {:.1}%",
                    score.components.safety * 100.0,
                    thresholds.safety * 100.0
                ),
            });
        }
        if score.components.idiomaticity < thresholds.idiomaticity {
            violations.push(Violation {
                violation_type: ViolationType::Idiomaticity,
                actual: score.components.idiomaticity,
                required: thresholds.idiomaticity,
                severity: Severity::Medium,
                message: format!(
                    "Idiomaticity {:.1}% below minimum {:.1}%",
                    score.components.idiomaticity * 100.0,
                    thresholds.idiomaticity * 100.0
                ),
            });
        }
    }
    fn check_anti_gaming_rules(
        &self,
        score: &QualityScore,
        file_path: Option<&PathBuf>,
        gaming_warnings: &mut Vec<String>,
        violations: &mut Vec<Violation>,
    ) {
        // Check cache hit rate (prevent stale analysis gaming)
        if score.cache_hit_rate > self.config.anti_gaming.max_cache_hit_rate {
            gaming_warnings.push(format!(
                "High cache hit rate {:.1}% may indicate stale analysis",
                score.cache_hit_rate * 100.0
            ));
        }
        // Check file size requirements
        if let Some(path) = file_path {
            if let Ok(metadata) = std::fs::metadata(path) {
                if metadata.len() < self.config.anti_gaming.min_file_size_bytes as u64 {
                    gaming_warnings.push(format!(
                        "File {} is very small ({} bytes) - may indicate gaming by splitting",
                        path.display(),
                        metadata.len()
                    ));
                }
            }
            // Check if critical files require deep analysis
            let path_str = path.to_string_lossy();
            if self
                .config
                .anti_gaming
                .require_deep_analysis
                .iter()
                .any(|p| path_str.contains(p))
                && score.confidence < 0.9
            {
                violations.push(Violation {
                    violation_type: ViolationType::Gaming,
                    actual: score.confidence,
                    required: 0.9,
                    severity: Severity::Critical,
                    message: format!(
                        "Critical file {} requires deep analysis (confidence < 90%)",
                        path.display()
                    ),
                });
            }
        }
    }
    /// Export results for CI/CD integration
    /// # Examples
    ///
    /// ```ignore
    /// use ruchy::quality::gates::export_ci_results;
    ///
    /// let result = export_ci_results(());
    /// assert_eq!(result, Ok(()));
    /// ```
    pub fn export_ci_results(
        &self,
        results: &[GateResult],
        output_dir: &Path,
    ) -> anyhow::Result<()> {
        if self.config.ci_integration.json_output {
            self.export_json_results(results, output_dir)?;
        }
        if self.config.ci_integration.junit_xml {
            self.export_junit_results(results, output_dir)?;
        }
        Ok(())
    }
    fn export_json_results(&self, results: &[GateResult], output_dir: &Path) -> anyhow::Result<()> {
        let output_path = output_dir.join("quality-gates.json");
        let json_content = serde_json::to_string_pretty(results)?;
        std::fs::write(output_path, json_content)?;
        Ok(())
    }
    fn export_junit_results(
        &self,
        results: &[GateResult],
        output_dir: &Path,
    ) -> anyhow::Result<()> {
        let output_path = output_dir.join("quality-gates.xml");
        let total = results.len();
        let failures = results.iter().filter(|r| !r.passed).count();
        let mut xml = format!(
            r#"<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="Quality Gates" tests="{total}" failures="{failures}" time="0.0">
"#
        );
        for (i, result) in results.iter().enumerate() {
            let test_name = format!("quality-gate-{i}");
            if result.passed {
                xml.push_str(&format!(
                    r#"  <testcase name="{test_name}" classname="QualityGate" time="0.0"/>
"#
                ));
            } else {
                xml.push_str(&format!(
                    r#"  <testcase name="{}" classname="QualityGate" time="0.0">
    <failure message="Quality gate violation">Score: {:.1}%, Grade: {}</failure>
  </testcase>
"#,
                    test_name,
                    result.score * 100.0,
                    result.grade
                ));
            }
        }
        xml.push_str("</testsuite>\n");
        std::fs::write(output_path, xml)?;
        Ok(())
    }
}
impl PartialOrd for Grade {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for Grade {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.to_rank().cmp(&other.to_rank())
    }
}
// PartialEq and Eq are now derived in scoring.rs
#[cfg(test)]
mod tests {
    use super::*;
    use crate::quality::scoring::{Grade, QualityScore};
    use tempfile::TempDir;
    fn create_minimal_score() -> QualityScore {
        use crate::quality::scoring::ScoreComponents;
        QualityScore {
            value: 0.5,
            components: ScoreComponents {
                correctness: 0.5,
                performance: 0.5,
                maintainability: 0.5,
                safety: 0.5,
                idiomaticity: 0.5,
            },
            grade: Grade::D,
            confidence: 0.4,
            cache_hit_rate: 0.3,
        }
    }
    fn create_passing_score() -> QualityScore {
        use crate::quality::scoring::ScoreComponents;
        QualityScore {
            value: 0.85,
            components: ScoreComponents {
                correctness: 0.9,
                performance: 0.8,
                maintainability: 0.8,
                safety: 0.9,
                idiomaticity: 0.7,
            },
            grade: Grade::APlus,
            confidence: 0.9,
            cache_hit_rate: 0.2,
        }
    }
    // Test 1: Default Configuration Creation
    #[test]
    fn test_default_quality_gate_config() {
        let config = QualityGateConfig::default();
        assert_eq!(config.min_score, 0.7);
        assert_eq!(config.min_grade, Grade::BMinus);
        assert_eq!(config.component_thresholds.correctness, 0.8);
        assert_eq!(config.component_thresholds.safety, 0.8);
        assert_eq!(config.anti_gaming.min_confidence, 0.6);
        assert!(config.ci_integration.fail_on_violation);
        assert!(config.project_overrides.is_empty());
    }
    // Test 2: Quality Gate Enforcer Creation
    #[test]
    fn test_quality_gate_enforcer_creation() {
        let config = QualityGateConfig::default();
        let enforcer = QualityGateEnforcer::new(config);
        // Verify enforcer uses the provided config
        let score = create_minimal_score();
        let result = enforcer.enforce_gates(&score, None);
        // Should fail with default thresholds
        assert!(!result.passed);
        assert!(!result.violations.is_empty());
    }
    // Test 3: Passing Quality Gate - All Criteria Met
    #[test]
    fn test_quality_gate_passes_with_high_score() {
        let config = QualityGateConfig::default();
        let enforcer = QualityGateEnforcer::new(config);
        let score = create_passing_score();
        let result = enforcer.enforce_gates(&score, None);
        assert!(result.passed, "High quality score should pass all gates");
        assert_eq!(result.score, 0.85);
        assert_eq!(result.grade, Grade::APlus);
        assert!(result.violations.is_empty());
        assert_eq!(result.confidence, 0.9);
        assert!(result.gaming_warnings.is_empty());
    }
    // Test 4: Failing Overall Score Threshold
    #[test]
    fn test_quality_gate_fails_overall_score() {
        let config = QualityGateConfig::default(); // min_score: 0.7
        let enforcer = QualityGateEnforcer::new(config);
        let mut score = create_minimal_score();
        score.value = 0.6; // Below 0.7 threshold
        let result = enforcer.enforce_gates(&score, None);
        assert!(!result.passed, "Score below threshold should fail");
        // Should have overall score violation
        let overall_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::OverallScore)
            .collect();
        assert_eq!(overall_violations.len(), 1);
        let violation = &overall_violations[0];
        assert_eq!(violation.actual, 0.6);
        assert_eq!(violation.required, 0.7);
        assert_eq!(violation.severity, Severity::Critical);
        assert!(violation.message.contains("60.0%"));
        assert!(violation.message.contains("70.0%"));
    }
    // Test 5: Confidence Threshold Violation
    #[test]
    fn test_confidence_threshold_violation() {
        let config = QualityGateConfig::default(); // min_confidence: 0.6
        let enforcer = QualityGateEnforcer::new(config);
        let mut score = create_passing_score();
        score.confidence = 0.4; // Below 0.6 threshold
        let result = enforcer.enforce_gates(&score, None);
        let confidence_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Confidence)
            .collect();
        assert_eq!(confidence_violations.len(), 1);
        let violation = &confidence_violations[0];
        assert_eq!(violation.severity, Severity::High);
        assert_eq!(violation.actual, 0.4);
        assert_eq!(violation.required, 0.6);
    }
    // Test 6: Configuration File Loading (Success)
    #[test]
    fn test_load_config_creates_default() {
        let temp_dir = TempDir::new().expect("operation should succeed in test");
        let project_root = temp_dir.path();
        let config = QualityGateEnforcer::load_config(project_root)
            .expect("operation should succeed in test");
        // Should create default config
        assert_eq!(config.min_score, 0.7);
        assert_eq!(config.min_grade, Grade::BMinus);
        // Should create .ruchy/score.toml file
        let config_path = project_root.join(".ruchy").join("score.toml");
        assert!(config_path.exists(), "Config file should be created");
        // File should contain valid TOML
        let content =
            std::fs::read_to_string(config_path).expect("operation should succeed in test");
        assert!(content.contains("min_score"));
        assert!(content.contains("0.7"));
    }
    // Test 7: Serialization/Deserialization
    #[test]
    fn test_config_serialization() {
        let original_config = QualityGateConfig::default();
        // Serialize to TOML
        let toml_content =
            toml::to_string(&original_config).expect("operation should succeed in test");
        assert!(toml_content.contains("min_score"));
        // Deserialize back
        let deserialized_config: QualityGateConfig =
            toml::from_str(&toml_content).expect("operation should succeed in test");
        assert_eq!(deserialized_config.min_score, original_config.min_score);
        assert_eq!(deserialized_config.min_grade, original_config.min_grade);
    }

    // Test 8: Grade Comparison Testing
    #[test]
    fn test_grade_ordering() {
        // Test all grade comparisons
        assert!(Grade::F < Grade::D);
        assert!(Grade::D < Grade::CMinus);
        assert!(Grade::CMinus < Grade::C);
        assert!(Grade::C < Grade::CPlus);
        assert!(Grade::CPlus < Grade::BMinus);
        assert!(Grade::BMinus < Grade::B);
        assert!(Grade::B < Grade::BPlus);
        assert!(Grade::BPlus < Grade::AMinus);
        assert!(Grade::AMinus < Grade::A);
        assert!(Grade::A < Grade::APlus);

        // Test specific comparisons used in gates
        assert!(Grade::C < Grade::BMinus); // Used in test_grade_threshold_violation
        assert!(Grade::BMinus < Grade::A);
    }

    // Test 9: Grade Threshold Violation
    #[test]
    fn test_grade_threshold_violation() {
        let config = QualityGateConfig::default(); // min_grade: BMinus
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.grade = Grade::C; // Below BMinus threshold

        let result = enforcer.enforce_gates(&score, None);
        let grade_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Grade)
            .collect();

        assert_eq!(grade_violations.len(), 1);
        let violation = &grade_violations[0];
        assert_eq!(violation.severity, Severity::Critical);
        assert!(violation.message.contains("Grade C below minimum B-"));
    }

    // Test 10: Component Threshold Violations - Correctness
    #[test]
    fn test_correctness_threshold_violation() {
        let config = QualityGateConfig::default(); // correctness: 0.8
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.components.correctness = 0.7; // Below 0.8 threshold

        let result = enforcer.enforce_gates(&score, None);
        let correctness_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Correctness)
            .collect();

        assert_eq!(correctness_violations.len(), 1);
        let violation = &correctness_violations[0];
        assert_eq!(violation.actual, 0.7);
        assert_eq!(violation.required, 0.8);
        assert_eq!(violation.severity, Severity::Critical);
        assert!(violation.message.contains("70.0%"));
        assert!(violation.message.contains("80.0%"));
    }

    // Test 11: Component Threshold Violations - Performance
    #[test]
    fn test_performance_threshold_violation() {
        let config = QualityGateConfig::default(); // performance: 0.6
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.components.performance = 0.5; // Below 0.6 threshold

        let result = enforcer.enforce_gates(&score, None);
        let performance_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Performance)
            .collect();

        assert_eq!(performance_violations.len(), 1);
        let violation = &performance_violations[0];
        assert_eq!(violation.actual, 0.5);
        assert_eq!(violation.required, 0.6);
        assert_eq!(violation.severity, Severity::High);
    }

    // Test 12: Component Threshold Violations - Safety
    #[test]
    fn test_safety_threshold_violation() {
        let config = QualityGateConfig::default(); // safety: 0.8
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.components.safety = 0.75; // Below 0.8 threshold

        let result = enforcer.enforce_gates(&score, None);
        let safety_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Safety)
            .collect();

        assert_eq!(safety_violations.len(), 1);
        let violation = &safety_violations[0];
        assert_eq!(violation.severity, Severity::Critical);
        assert!(violation.message.contains("75.0%"));
        assert!(violation.message.contains("80.0%"));
    }

    // Test 13: Component Threshold Violations - Maintainability
    #[test]
    fn test_maintainability_threshold_violation() {
        let config = QualityGateConfig::default(); // maintainability: 0.7
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.components.maintainability = 0.65; // Below 0.7 threshold

        let result = enforcer.enforce_gates(&score, None);
        let maintainability_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Maintainability)
            .collect();

        assert_eq!(maintainability_violations.len(), 1);
        let violation = &maintainability_violations[0];
        assert_eq!(violation.severity, Severity::High);
        assert_eq!(violation.actual, 0.65);
        assert_eq!(violation.required, 0.7);
    }

    // Test 14: Component Threshold Violations - Idiomaticity
    #[test]
    fn test_idiomaticity_threshold_violation() {
        let config = QualityGateConfig::default(); // idiomaticity: 0.5
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.components.idiomaticity = 0.4; // Below 0.5 threshold

        let result = enforcer.enforce_gates(&score, None);
        let idiomaticity_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Idiomaticity)
            .collect();

        assert_eq!(idiomaticity_violations.len(), 1);
        let violation = &idiomaticity_violations[0];
        assert_eq!(violation.severity, Severity::Medium);
        assert_eq!(violation.actual, 0.4);
        assert_eq!(violation.required, 0.5);
    }

    // Test 15: Anti-Gaming Rules - Cache Hit Rate Warning
    #[test]
    fn test_high_cache_hit_rate_warning() {
        let config = QualityGateConfig::default(); // max_cache_hit_rate: 0.8
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.cache_hit_rate = 0.9; // Above 0.8 threshold

        let result = enforcer.enforce_gates(&score, None);

        assert!(!result.gaming_warnings.is_empty());
        let warning = &result.gaming_warnings[0];
        assert!(warning.contains("High cache hit rate 90.0%"));
        assert!(warning.contains("stale analysis"));
    }

    // Test 16: Anti-Gaming Rules - File Size Warning
    #[test]
    fn test_small_file_size_warning() -> anyhow::Result<()> {
        let temp_dir = TempDir::new().expect("operation should succeed in test");
        let small_file = temp_dir.path().join("small.rs");
        std::fs::write(&small_file, "// Small file")?; // ~13 bytes, below 100 threshold

        let config = QualityGateConfig::default(); // min_file_size_bytes: 100
        let enforcer = QualityGateEnforcer::new(config);
        let score = create_passing_score();

        let result = enforcer.enforce_gates(&score, Some(&small_file));

        assert!(!result.gaming_warnings.is_empty());
        let warning = &result.gaming_warnings[0];
        assert!(warning.contains("very small"));
        assert!(warning.contains("gaming by splitting"));
        Ok(())
    }

    // Test 17: Anti-Gaming Rules - Critical Files Deep Analysis
    #[test]
    fn test_critical_files_deep_analysis() {
        let temp_dir = TempDir::new().expect("operation should succeed in test");
        let critical_file = temp_dir.path().join("src").join("main.rs");
        std::fs::create_dir_all(
            critical_file
                .parent()
                .expect("operation should succeed in test"),
        )
        .expect("operation should succeed in test");
        std::fs::write(&critical_file, "fn main() {}").expect("operation should succeed in test");

        let config = QualityGateConfig::default(); // require_deep_analysis includes "src/main.rs"
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.confidence = 0.8; // Below 0.9 required for critical files

        let result = enforcer.enforce_gates(&score, Some(&critical_file));

        let gaming_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Gaming)
            .collect();

        assert_eq!(gaming_violations.len(), 1);
        let violation = &gaming_violations[0];
        assert_eq!(violation.severity, Severity::Critical);
        assert_eq!(violation.actual, 0.8);
        assert_eq!(violation.required, 0.9);
        assert!(violation.message.contains("deep analysis"));
    }

    // Test 18: Multiple Violations Combination
    #[test]
    fn test_multiple_violations() {
        let config = QualityGateConfig::default();
        let enforcer = QualityGateEnforcer::new(config);

        let score = create_minimal_score(); // This should fail multiple criteria
        let result = enforcer.enforce_gates(&score, None);

        assert!(!result.passed);
        // Should have multiple violations
        assert!(result.violations.len() >= 3); // At least overall score, grade, and confidence

        // Check we have different violation types
        let violation_types: std::collections::HashSet<_> = result
            .violations
            .iter()
            .map(|v| &v.violation_type)
            .collect();
        assert!(violation_types.contains(&ViolationType::OverallScore));
        assert!(violation_types.contains(&ViolationType::Grade));
        assert!(violation_types.contains(&ViolationType::Confidence));
    }

    // Test 19: CI Results Export - JSON Format
    #[test]
    fn test_export_json_results() -> anyhow::Result<()> {
        let temp_dir = TempDir::new().expect("operation should succeed in test");
        let output_dir = temp_dir.path();

        let mut config = QualityGateConfig::default();
        config.ci_integration.json_output = true;
        config.ci_integration.junit_xml = false;

        let enforcer = QualityGateEnforcer::new(config);
        let results = vec![create_gate_result_passed(), create_gate_result_failed()];

        enforcer.export_ci_results(&results, output_dir)?;

        let json_file = output_dir.join("quality-gates.json");
        assert!(json_file.exists());

        let content = std::fs::read_to_string(json_file)?;
        let parsed: Vec<GateResult> = serde_json::from_str(&content)?;
        assert_eq!(parsed.len(), 2);
        assert!(parsed[0].passed);
        assert!(!parsed[1].passed);

        Ok(())
    }

    // Test 20: CI Results Export - JUnit XML Format
    #[test]
    fn test_export_junit_xml_results() -> anyhow::Result<()> {
        let temp_dir = TempDir::new().expect("operation should succeed in test");
        let output_dir = temp_dir.path();

        let mut config = QualityGateConfig::default();
        config.ci_integration.json_output = false;
        config.ci_integration.junit_xml = true;

        let enforcer = QualityGateEnforcer::new(config);
        let results = vec![create_gate_result_passed(), create_gate_result_failed()];

        enforcer.export_ci_results(&results, output_dir)?;

        let xml_file = output_dir.join("quality-gates.xml");
        assert!(xml_file.exists());

        let content = std::fs::read_to_string(xml_file)?;
        assert!(content.contains("<?xml version="));
        assert!(content.contains("<testsuite name=\"Quality Gates\" tests=\"2\" failures=\"1\""));
        assert!(content.contains("<testcase name=\"quality-gate-0\" classname=\"QualityGate\""));
        assert!(content.contains("<failure message=\"Quality gate violation\""));
        assert!(content.contains("</testsuite>"));

        Ok(())
    }

    // Test 21: Violation Type and Severity Enum Coverage
    #[test]
    fn test_violation_enums_coverage() {
        // Test all ViolationType variants can be created and compared
        let types = [
            ViolationType::OverallScore,
            ViolationType::Grade,
            ViolationType::Correctness,
            ViolationType::Performance,
            ViolationType::Maintainability,
            ViolationType::Safety,
            ViolationType::Idiomaticity,
            ViolationType::Confidence,
            ViolationType::Gaming,
        ];

        for (i, vtype) in types.iter().enumerate() {
            for (j, other) in types.iter().enumerate() {
                if i == j {
                    assert_eq!(vtype, other);
                } else {
                    assert_ne!(vtype, other);
                }
            }
        }

        // Test all Severity variants
        let severities = [
            Severity::Critical,
            Severity::High,
            Severity::Medium,
            Severity::Low,
        ];

        for (i, severity) in severities.iter().enumerate() {
            for (j, other) in severities.iter().enumerate() {
                if i == j {
                    assert_eq!(severity, other);
                } else {
                    assert_ne!(severity, other);
                }
            }
        }
    }

    // Test 22: Notification Config Serialization
    #[test]
    fn test_notification_config_serialization() {
        let config = NotificationConfig {
            slack: true,
            email: false,
            webhook: Some("https://test.example.com/webhook".to_string()),
        };

        let serialized = serde_json::to_string(&config).expect("operation should succeed in test");
        let deserialized: NotificationConfig =
            serde_json::from_str(&serialized).expect("operation should succeed in test");

        assert!(deserialized.slack);
        assert!(!deserialized.email);
        assert_eq!(
            deserialized.webhook,
            Some("https://test.example.com/webhook".to_string())
        );
    }

    // === EXTREME TDD Round 162 - 95% Coverage Push Tests ===

    // Test 23: Gate passes at exact threshold boundary
    #[test]
    fn test_gate_passes_at_exact_boundary_r162() {
        let config = QualityGateConfig::default(); // min_score: 0.7
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.value = 0.7; // Exactly at threshold
        score.grade = Grade::BMinus;

        let result = enforcer.enforce_gates(&score, None);
        let score_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::OverallScore)
            .collect();

        // Should pass at exact boundary (not below)
        assert!(score_violations.is_empty());
    }

    // Test 24: Gate fails just below threshold
    #[test]
    fn test_gate_fails_just_below_boundary_r162() {
        let config = QualityGateConfig::default(); // min_score: 0.7
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.value = 0.699; // Just below threshold

        let result = enforcer.enforce_gates(&score, None);
        let score_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::OverallScore)
            .collect();

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

    // Test 25: Custom strict config (A- minimum)
    #[test]
    fn test_strict_config_a_minus_minimum_r162() {
        let mut config = QualityGateConfig::default();
        config.min_score = 0.85;
        config.min_grade = Grade::AMinus;

        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.value = 0.84; // Below A- threshold
        score.grade = Grade::BPlus;

        let result = enforcer.enforce_gates(&score, None);
        assert!(!result.passed);
    }

    // Test 26: Lenient config (C minimum)
    #[test]
    fn test_lenient_config_c_minimum_r162() {
        let mut config = QualityGateConfig::default();
        config.min_score = 0.5;
        config.min_grade = Grade::C;
        config.component_thresholds.correctness = 0.5;
        config.component_thresholds.safety = 0.5;
        config.anti_gaming.min_confidence = 0.3;

        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_minimal_score();
        score.value = 0.55;
        score.grade = Grade::C;
        score.components.correctness = 0.55;
        score.components.safety = 0.55;
        score.confidence = 0.4;

        let result = enforcer.enforce_gates(&score, None);
        // Should pass with lenient config
        let critical_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.severity == Severity::Critical)
            .collect();
        assert!(critical_violations.is_empty());
    }

    // Test 27: Project overrides applied correctly
    #[test]
    fn test_project_overrides_r162() {
        let mut config = QualityGateConfig::default();
        config
            .project_overrides
            .insert("performance".to_string(), 0.3);

        // Project overrides should be stored
        assert_eq!(config.project_overrides.get("performance"), Some(&0.3));
    }

    // Test 28: Grade ordering A+ > A
    #[test]
    fn test_grade_ordering_a_plus_greater_than_a_r162() {
        assert!(Grade::APlus > Grade::A);
    }

    // Test 29: Grade ordering A > A-
    #[test]
    fn test_grade_ordering_a_greater_than_a_minus_r162() {
        assert!(Grade::A > Grade::AMinus);
    }

    // Test 30: Grade ordering A- > B+
    #[test]
    fn test_grade_ordering_a_minus_greater_than_b_plus_r162() {
        assert!(Grade::AMinus > Grade::BPlus);
    }

    // Test 31: Grade ordering F < D
    #[test]
    fn test_grade_ordering_f_less_than_d_r162() {
        assert!(Grade::F < Grade::D);
    }

    // Test 32: Grade equality
    #[test]
    fn test_grade_equality_r162() {
        assert!(Grade::A == Grade::A);
        assert!(Grade::BMinus == Grade::BMinus);
    }

    // Test 33: GateResult serialization roundtrip
    #[test]
    fn test_gate_result_serialization_roundtrip_r162() {
        let result = create_gate_result_passed();
        let serialized = serde_json::to_string(&result).expect("serialize should succeed");
        let deserialized: GateResult =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert_eq!(result.passed, deserialized.passed);
        assert!((result.score - deserialized.score).abs() < f64::EPSILON);
        assert_eq!(result.grade, deserialized.grade);
    }

    // Test 34: Violation serialization roundtrip
    #[test]
    fn test_violation_serialization_roundtrip_r162() {
        let violation = Violation {
            violation_type: ViolationType::Correctness,
            actual: 0.65,
            required: 0.8,
            severity: Severity::Critical,
            message: "Test violation message".to_string(),
        };

        let serialized = serde_json::to_string(&violation).expect("serialize should succeed");
        let deserialized: Violation =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert_eq!(violation.violation_type, deserialized.violation_type);
        assert_eq!(violation.severity, deserialized.severity);
        assert_eq!(violation.message, deserialized.message);
    }

    // Test 35: ComponentThresholds serialization
    #[test]
    fn test_component_thresholds_serialization_r162() {
        let thresholds = ComponentThresholds {
            correctness: 0.9,
            performance: 0.7,
            maintainability: 0.8,
            safety: 0.95,
            idiomaticity: 0.6,
        };

        let serialized = serde_json::to_string(&thresholds).expect("serialize should succeed");
        let deserialized: ComponentThresholds =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert!((thresholds.correctness - deserialized.correctness).abs() < f64::EPSILON);
        assert!((thresholds.safety - deserialized.safety).abs() < f64::EPSILON);
    }

    // Test 36: AntiGamingRules serialization
    #[test]
    fn test_anti_gaming_rules_serialization_r162() {
        let rules = AntiGamingRules {
            min_confidence: 0.7,
            max_cache_hit_rate: 0.75,
            require_deep_analysis: vec!["src/lib.rs".to_string()],
            min_file_size_bytes: 200,
            max_test_ratio: 1.5,
        };

        let serialized = serde_json::to_string(&rules).expect("serialize should succeed");
        let deserialized: AntiGamingRules =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert_eq!(rules.min_file_size_bytes, deserialized.min_file_size_bytes);
        assert_eq!(
            rules.require_deep_analysis.len(),
            deserialized.require_deep_analysis.len()
        );
    }

    // Test 37: CiIntegration serialization
    #[test]
    fn test_ci_integration_serialization_r162() {
        let ci = CiIntegration {
            fail_on_violation: true,
            junit_xml: true,
            json_output: false,
            notifications: NotificationConfig {
                slack: true,
                email: true,
                webhook: Some("https://hook.example.com".to_string()),
            },
            block_merge: false,
        };

        let serialized = serde_json::to_string(&ci).expect("serialize should succeed");
        let deserialized: CiIntegration =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert_eq!(ci.fail_on_violation, deserialized.fail_on_violation);
        assert_eq!(ci.block_merge, deserialized.block_merge);
        assert!(deserialized.notifications.slack);
    }

    // Test 38: Empty violations list means passed
    #[test]
    fn test_empty_violations_means_passed_r162() {
        let result = GateResult {
            passed: true,
            score: 0.95,
            grade: Grade::APlus,
            violations: vec![],
            confidence: 0.99,
            gaming_warnings: vec![],
        };

        assert!(result.passed);
        assert!(result.violations.is_empty());
    }

    // Test 39: Performance threshold violation severity is High (not Critical)
    #[test]
    fn test_performance_violation_severity_is_high_r162() {
        let config = QualityGateConfig::default();
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.components.performance = 0.5; // Below 0.6 threshold

        let result = enforcer.enforce_gates(&score, None);
        let perf_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Performance)
            .collect();

        assert_eq!(perf_violations.len(), 1);
        assert_eq!(perf_violations[0].severity, Severity::High);
    }

    // Test 40: Full config serialization roundtrip
    #[test]
    fn test_full_config_serialization_roundtrip_r162() {
        let config = QualityGateConfig::default();

        let serialized = serde_json::to_string(&config).expect("serialize should succeed");
        let deserialized: QualityGateConfig =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert!((config.min_score - deserialized.min_score).abs() < f64::EPSILON);
        assert_eq!(config.min_grade, deserialized.min_grade);
    }

    // Test 41: Cache hit rate at exact max threshold
    #[test]
    fn test_cache_hit_rate_at_exact_max_r162() {
        let config = QualityGateConfig::default(); // max_cache_hit_rate: 0.8
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.cache_hit_rate = 0.8; // Exactly at max threshold

        let result = enforcer.enforce_gates(&score, None);
        // Should NOT warn at exact threshold (only above)
        assert!(result.gaming_warnings.is_empty());
    }

    // Test 42: Confidence at exact minimum threshold passes
    #[test]
    fn test_confidence_at_exact_min_passes_r162() {
        let config = QualityGateConfig::default(); // min_confidence: 0.6
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.confidence = 0.6; // Exactly at minimum

        let result = enforcer.enforce_gates(&score, None);
        let confidence_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| v.violation_type == ViolationType::Confidence)
            .collect();

        // Should pass at exact threshold
        assert!(confidence_violations.is_empty());
    }

    // Test 43: All component thresholds pass at exact values
    #[test]
    fn test_all_components_at_exact_thresholds_pass_r162() {
        let config = QualityGateConfig::default();
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        // Set all to exact thresholds
        score.components.correctness = 0.8;
        score.components.performance = 0.6;
        score.components.maintainability = 0.7;
        score.components.safety = 0.8;
        score.components.idiomaticity = 0.5;

        let result = enforcer.enforce_gates(&score, None);

        // Should have no component violations
        let component_violations: Vec<_> = result
            .violations
            .iter()
            .filter(|v| {
                matches!(
                    v.violation_type,
                    ViolationType::Correctness
                        | ViolationType::Performance
                        | ViolationType::Maintainability
                        | ViolationType::Safety
                        | ViolationType::Idiomaticity
                )
            })
            .collect();

        assert!(component_violations.is_empty());
    }

    // Test 44: NotificationConfig with None webhook
    #[test]
    fn test_notification_config_none_webhook_r162() {
        let config = NotificationConfig {
            slack: false,
            email: false,
            webhook: None,
        };

        let serialized = serde_json::to_string(&config).expect("serialize should succeed");
        let deserialized: NotificationConfig =
            serde_json::from_str(&serialized).expect("deserialize should succeed");

        assert!(!deserialized.slack);
        assert!(!deserialized.email);
        assert!(deserialized.webhook.is_none());
    }

    // Test 45: Violation message contains percentage formatting
    #[test]
    fn test_violation_message_percentage_format_r162() {
        let config = QualityGateConfig::default();
        let enforcer = QualityGateEnforcer::new(config);

        let mut score = create_passing_score();
        score.value = 0.55; // 55%

        let result = enforcer.enforce_gates(&score, None);
        let score_violation = result
            .violations
            .iter()
            .find(|v| v.violation_type == ViolationType::OverallScore)
            .expect("should have score violation");

        // Message should contain percentage formatting
        assert!(score_violation.message.contains("55.0%"));
        assert!(score_violation.message.contains("70.0%"));
    }

    // Helper functions for testing
    fn create_gate_result_passed() -> GateResult {
        GateResult {
            passed: true,
            score: 0.85,
            grade: Grade::APlus,
            violations: vec![],
            confidence: 0.9,
            gaming_warnings: vec![],
        }
    }

    fn create_gate_result_failed() -> GateResult {
        GateResult {
            passed: false,
            score: 0.6,
            grade: Grade::D,
            violations: vec![Violation {
                violation_type: ViolationType::OverallScore,
                actual: 0.6,
                required: 0.7,
                severity: Severity::Critical,
                message: "Overall score 60.0% below minimum 70.0%".to_string(),
            }],
            confidence: 0.5,
            gaming_warnings: vec!["Low confidence warning".to_string()],
        }
    }
}
#[cfg(test)]
mod property_tests_gates {
    use proptest::proptest;

    proptest! {
        /// Property: Function never panics on any input
        #[test]
        fn test_new_never_panics(input: String) {
            // Limit input size to avoid timeout
            let _input = if input.len() > 100 { &input[..100] } else { &input[..] };
            // Function should not panic on any input
            let _ = std::panic::catch_unwind(|| {
                // Call function with various inputs
                // This is a template - adjust based on actual function signature
            });
        }
    }
}