decy-oracle 2.1.0

CITL (Compiler-in-the-Loop) oracle for C-to-Rust transpilation pattern mining
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
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
//! Bootstrap module for oracle cold start
//!
//! This module provides seed patterns for common C-to-Rust transpilation errors,
//! solving the cold start problem where the oracle has no patterns to learn from.
//!
//! # Toyota Way Principles
//!
//! - **Genchi Genbutsu** (現地現物): Patterns derived from real C→Rust transpilation errors
//! - **Yokoten** (横展): Cross-project pattern sharing from depyler ownership patterns
//! - **Jidoka** (自働化): Automated bootstrap when no patterns exist

#[cfg(feature = "citl")]
use entrenar::citl::{DecisionPatternStore, FixPattern};

#[cfg(feature = "citl")]
use crate::error::OracleError;

/// Bootstrap pattern definition
#[derive(Debug, Clone)]
pub struct BootstrapPattern {
    /// Error code (e.g., "E0308")
    pub error_code: &'static str,
    /// Fix diff showing the transformation
    pub fix_diff: &'static str,
    /// Decision context (e.g., "type_coercion", "unsafe_block")
    pub decision: &'static str,
    /// Human-readable description
    pub description: &'static str,
}

/// Get all bootstrap patterns for C→Rust transpilation
pub fn get_bootstrap_patterns() -> Vec<BootstrapPattern> {
    vec![
        // ============================================
        // E0308: Type Mismatch Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- let x: i32 = value;\n+ let x: i32 = value as i32;",
            decision: "type_coercion",
            description: "Add explicit type cast for integer conversion",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- fn foo(a: *mut i32)\n+ fn foo(a: &mut i32)",
            decision: "pointer_to_reference",
            description: "Convert raw pointer parameter to mutable reference",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- fn foo(a: *const i32)\n+ fn foo(a: &i32)",
            decision: "pointer_to_reference",
            description: "Convert raw pointer parameter to immutable reference",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- swap(&x, &y);\n+ swap(&mut x, &mut y);",
            decision: "mutable_reference",
            description: "Change immutable reference to mutable reference",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- exit(x);\n+ std::process::exit(x as i32);",
            decision: "type_coercion",
            description: "Cast to correct type for stdlib function",
        },

        // ============================================
        // E0133: Unsafe Block Required Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0133",
            fix_diff: "- *ptr = value;\n+ unsafe { *ptr = value; }",
            decision: "unsafe_deref",
            description: "Wrap pointer dereference in unsafe block",
        },
        BootstrapPattern {
            error_code: "E0133",
            fix_diff: "- let x = *ptr;\n+ let x = unsafe { *ptr };",
            decision: "unsafe_deref",
            description: "Wrap pointer read in unsafe block",
        },
        BootstrapPattern {
            error_code: "E0133",
            fix_diff: "- extern_fn();\n+ unsafe { extern_fn(); }",
            decision: "unsafe_extern",
            description: "Wrap extern function call in unsafe block",
        },

        // ============================================
        // E0382: Use After Move Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0382",
            fix_diff: "- process(value);\n- use(value);\n+ process(value.clone());\n+ use(value);",
            decision: "clone_before_move",
            description: "Clone value before move to allow subsequent use",
        },
        BootstrapPattern {
            error_code: "E0382",
            fix_diff: "- let y = x;\n- use(x);\n+ let y = &x;\n+ use(x);",
            decision: "borrow_instead_of_move",
            description: "Borrow instead of move to preserve ownership",
        },
        BootstrapPattern {
            error_code: "E0382",
            fix_diff: "- fn take(s: String)\n+ fn take(s: &String)",
            decision: "borrow_parameter",
            description: "Change function parameter to borrow instead of taking ownership",
        },

        // ============================================
        // E0499: Multiple Mutable Borrows Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0499",
            fix_diff: "- let a = &mut x;\n- let b = &mut x;\n+ let a = &mut x;\n+ drop(a);\n+ let b = &mut x;",
            decision: "sequential_mutable_borrow",
            description: "End first mutable borrow before starting second",
        },
        BootstrapPattern {
            error_code: "E0499",
            fix_diff: "- swap(&mut arr[i], &mut arr[j]);\n+ arr.swap(i, j);",
            decision: "use_stdlib_method",
            description: "Use stdlib method to avoid multiple mutable borrows",
        },

        // ============================================
        // E0506: Cannot Assign to Borrowed Value Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0506",
            fix_diff: "- let r = &x;\n- x = 5;\n- use(r);\n+ x = 5;\n+ let r = &x;\n+ use(r);",
            decision: "reorder_borrow",
            description: "Reorder borrow to occur after assignment",
        },

        // ============================================
        // E0597: Value Does Not Live Long Enough Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0597",
            fix_diff: "- let r;\n- {\n-     let x = 5;\n-     r = &x;\n- }\n+ let x = 5;\n+ let r = &x;",
            decision: "extend_lifetime",
            description: "Move value to outer scope to extend lifetime",
        },
        BootstrapPattern {
            error_code: "E0597",
            fix_diff: "- fn get_ref() -> &i32\n+ fn get_ref() -> i32",
            decision: "return_owned",
            description: "Return owned value instead of reference",
        },

        // ============================================
        // E0515: Cannot Return Reference to Local Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0515",
            fix_diff: "- fn create() -> &Vec<i32> {\n-     let v = vec![1,2,3];\n-     &v\n- }\n+ fn create() -> Vec<i32> {\n+     let v = vec![1,2,3];\n+     v\n+ }",
            decision: "return_owned",
            description: "Return owned value instead of reference to local",
        },
        BootstrapPattern {
            error_code: "E0515",
            fix_diff: "- return &local;\n+ return local.clone();",
            decision: "clone_return",
            description: "Clone local value to return owned copy",
        },

        // ============================================
        // C-Specific: Array/Pointer Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- fn process(arr: *const i32, len: usize)\n+ fn process(arr: &[i32])",
            decision: "array_to_slice",
            description: "Convert C array pointer to Rust slice",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- arr[i]\n+ arr.get(i).copied().unwrap_or(0)",
            decision: "bounds_checked_access",
            description: "Add bounds checking to array access",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- ptr + offset\n+ ptr.wrapping_add(offset)",
            decision: "safe_pointer_arithmetic",
            description: "Use safe pointer arithmetic method",
        },

        // ============================================
        // C-Specific: malloc/free Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- let ptr = malloc(size);\n+ let ptr = Box::new(value);",
            decision: "malloc_to_box",
            description: "Replace malloc with Box allocation",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- let arr = malloc(n * size);\n+ let arr = Vec::with_capacity(n);",
            decision: "malloc_array_to_vec",
            description: "Replace array malloc with Vec",
        },

        // ============================================
        // C-Specific: Struct Patterns
        // ============================================
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- p->field\n+ p.field",
            decision: "arrow_to_dot",
            description: "Replace C arrow operator with Rust dot operator",
        },
        BootstrapPattern {
            error_code: "E0308",
            fix_diff: "- struct Node *next;\n+ next: Option<Box<Node>>,",
            decision: "nullable_to_option",
            description: "Replace nullable pointer with Option<Box<T>>",
        },
    ]
}

/// Seed the oracle pattern store with bootstrap patterns
#[cfg(feature = "citl")]
pub fn seed_pattern_store(store: &mut DecisionPatternStore) -> Result<usize, OracleError> {
    let patterns = get_bootstrap_patterns();
    let mut count = 0;

    for bp in patterns {
        let pattern = FixPattern::new(bp.error_code, bp.fix_diff).with_decision(bp.decision);

        if store.index_fix(pattern).is_ok() {
            count += 1;
        }
    }

    Ok(count)
}

/// Create a new pattern store with bootstrap patterns pre-loaded
#[cfg(feature = "citl")]
pub fn create_bootstrapped_store() -> Result<DecisionPatternStore, OracleError> {
    let mut store =
        DecisionPatternStore::new().map_err(|e| OracleError::PatternStoreError(e.to_string()))?;

    seed_pattern_store(&mut store)?;

    Ok(store)
}

/// Bootstrap statistics
#[derive(Debug, Default)]
pub struct BootstrapStats {
    /// Total patterns available
    pub total_patterns: usize,
    /// Patterns by error code
    pub by_error_code: std::collections::HashMap<String, usize>,
    /// Patterns by decision type
    pub by_decision: std::collections::HashMap<String, usize>,
}

impl BootstrapStats {
    /// Calculate statistics from bootstrap patterns
    pub fn from_patterns() -> Self {
        let patterns = get_bootstrap_patterns();
        let mut stats = Self {
            total_patterns: patterns.len(),
            ..Default::default()
        };

        for p in patterns {
            *stats
                .by_error_code
                .entry(p.error_code.to_string())
                .or_default() += 1;
            *stats.by_decision.entry(p.decision.to_string()).or_default() += 1;
        }

        stats
    }

    /// Format as human-readable string
    pub fn to_string_pretty(&self) -> String {
        let mut s = format!("Bootstrap Patterns: {}\n\n", self.total_patterns);

        s.push_str("By Error Code:\n");
        let mut codes: Vec<_> = self.by_error_code.iter().collect();
        codes.sort_by_key(|(k, _)| *k);
        for (code, count) in codes {
            s.push_str(&format!("  {}: {}\n", code, count));
        }

        s.push_str("\nBy Decision Type:\n");
        let mut decisions: Vec<_> = self.by_decision.iter().collect();
        decisions.sort_by_key(|(_, v)| std::cmp::Reverse(*v));
        for (decision, count) in decisions {
            s.push_str(&format!("  {}: {}\n", decision, count));
        }

        s
    }
}

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

    #[test]
    fn test_bootstrap_patterns_not_empty() {
        let patterns = get_bootstrap_patterns();
        assert!(
            !patterns.is_empty(),
            "Bootstrap patterns should not be empty"
        );
    }

    #[test]
    fn test_bootstrap_patterns_count() {
        let patterns = get_bootstrap_patterns();
        // Should have substantial coverage
        assert!(
            patterns.len() >= 20,
            "Should have at least 20 bootstrap patterns"
        );
    }

    #[test]
    fn test_all_patterns_have_valid_error_codes() {
        let patterns = get_bootstrap_patterns();
        for p in patterns {
            assert!(
                p.error_code.starts_with("E"),
                "Error code should start with E: {}",
                p.error_code
            );
            assert!(
                p.error_code.len() == 5,
                "Error code should be 5 chars (EXXXX): {}",
                p.error_code
            );
        }
    }

    #[test]
    fn test_all_patterns_have_fix_diffs() {
        let patterns = get_bootstrap_patterns();
        for p in patterns {
            assert!(
                !p.fix_diff.is_empty(),
                "Fix diff should not be empty for {}",
                p.error_code
            );
            assert!(
                p.fix_diff.contains('-') || p.fix_diff.contains('+'),
                "Fix diff should contain - or +: {}",
                p.fix_diff
            );
        }
    }

    #[test]
    fn test_all_patterns_have_decisions() {
        let patterns = get_bootstrap_patterns();
        for p in patterns {
            assert!(
                !p.decision.is_empty(),
                "Decision should not be empty for {}",
                p.error_code
            );
        }
    }

    #[test]
    fn test_all_patterns_have_descriptions() {
        let patterns = get_bootstrap_patterns();
        for p in patterns {
            assert!(
                !p.description.is_empty(),
                "Description should not be empty for {}",
                p.error_code
            );
        }
    }

    #[test]
    fn test_bootstrap_stats() {
        let stats = BootstrapStats::from_patterns();
        assert!(stats.total_patterns > 0);
        assert!(!stats.by_error_code.is_empty());
        assert!(!stats.by_decision.is_empty());
    }

    #[test]
    fn test_bootstrap_stats_has_common_error_codes() {
        let stats = BootstrapStats::from_patterns();
        // Should have patterns for key C→Rust errors
        assert!(
            stats.by_error_code.contains_key("E0308"),
            "Should have E0308 (type mismatch)"
        );
        assert!(
            stats.by_error_code.contains_key("E0133"),
            "Should have E0133 (unsafe)"
        );
        assert!(
            stats.by_error_code.contains_key("E0382"),
            "Should have E0382 (use after move)"
        );
    }

    #[test]
    fn test_bootstrap_stats_pretty_format() {
        let stats = BootstrapStats::from_patterns();
        let pretty = stats.to_string_pretty();
        assert!(pretty.contains("Bootstrap Patterns:"));
        assert!(pretty.contains("By Error Code:"));
        assert!(pretty.contains("By Decision Type:"));
    }

    #[cfg(feature = "citl")]
    #[test]
    fn test_seed_pattern_store() {
        let mut store = DecisionPatternStore::new().unwrap();
        let count = seed_pattern_store(&mut store).unwrap();
        assert!(count > 0, "Should seed at least some patterns");
        assert_eq!(
            count,
            store.len(),
            "Store should contain all seeded patterns"
        );
    }

    #[cfg(feature = "citl")]
    #[test]
    fn test_create_bootstrapped_store() {
        let store = create_bootstrapped_store().unwrap();
        assert!(!store.is_empty(), "Bootstrapped store should have patterns");
    }

    #[cfg(feature = "citl")]
    #[test]
    fn test_bootstrapped_store_has_suggestions() {
        let store = create_bootstrapped_store().unwrap();

        // Should be able to get suggestions for E0308
        let suggestions = store.suggest_fix("E0308", &[], 5).unwrap();
        assert!(!suggestions.is_empty(), "Should have suggestions for E0308");
    }

    // ========================================================================
    // Coverage tests: exercise every pattern's fields for line coverage
    // ========================================================================

    #[test]
    fn test_iterate_all_patterns_read_all_fields() {
        let patterns = get_bootstrap_patterns();
        let mut error_codes = Vec::new();
        let mut fix_diffs = Vec::new();
        let mut decisions = Vec::new();
        let mut descriptions = Vec::new();

        for p in &patterns {
            error_codes.push(p.error_code.to_string());
            fix_diffs.push(p.fix_diff.to_string());
            decisions.push(p.decision.to_string());
            descriptions.push(p.description.to_string());
        }

        assert_eq!(error_codes.len(), patterns.len());
        assert_eq!(fix_diffs.len(), patterns.len());
        assert_eq!(decisions.len(), patterns.len());
        assert_eq!(descriptions.len(), patterns.len());

        // Verify no field is empty across the entire collection
        assert!(error_codes.iter().all(|s| !s.is_empty()));
        assert!(fix_diffs.iter().all(|s| !s.is_empty()));
        assert!(decisions.iter().all(|s| !s.is_empty()));
        assert!(descriptions.iter().all(|s| !s.is_empty()));
    }

    #[test]
    fn test_exact_pattern_count() {
        let patterns = get_bootstrap_patterns();
        assert_eq!(patterns.len(), 25, "Should have exactly 25 bootstrap patterns");
    }

    // ========================================================================
    // Error code distribution tests
    // ========================================================================

    #[test]
    fn test_e0308_type_mismatch_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0308: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0308").collect();
        assert_eq!(
            e0308.len(),
            12,
            "E0308 should have 12 patterns (5 type mismatch + 3 array/pointer + 2 malloc + 2 struct)"
        );
        // Verify all E0308 patterns have type-related content
        for p in &e0308 {
            assert!(
                !p.fix_diff.is_empty() && !p.decision.is_empty(),
                "E0308 pattern missing content: {}",
                p.description
            );
        }
    }

    #[test]
    fn test_e0133_unsafe_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0133: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0133").collect();
        assert_eq!(e0133.len(), 3, "E0133 should have 3 unsafe patterns");
        for p in &e0133 {
            assert!(
                p.fix_diff.contains("unsafe"),
                "E0133 fix_diff should mention unsafe: {}",
                p.description
            );
        }
    }

    #[test]
    fn test_e0382_use_after_move_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0382: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0382").collect();
        assert_eq!(e0382.len(), 3, "E0382 should have 3 use-after-move patterns");
    }

    #[test]
    fn test_e0499_multiple_mutable_borrow_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0499: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0499").collect();
        assert_eq!(e0499.len(), 2, "E0499 should have 2 multiple mutable borrow patterns");
    }

    #[test]
    fn test_e0506_assign_to_borrowed_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0506: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0506").collect();
        assert_eq!(
            e0506.len(),
            1,
            "E0506 should have 1 cannot-assign-to-borrowed pattern"
        );
        assert_eq!(e0506[0].decision, "reorder_borrow");
        assert!(e0506[0].description.contains("Reorder"));
    }

    #[test]
    fn test_e0597_lifetime_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0597: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0597").collect();
        assert_eq!(e0597.len(), 2, "E0597 should have 2 lifetime patterns");
    }

    #[test]
    fn test_e0515_return_reference_to_local_patterns() {
        let patterns = get_bootstrap_patterns();
        let e0515: Vec<_> = patterns.iter().filter(|p| p.error_code == "E0515").collect();
        assert_eq!(
            e0515.len(),
            2,
            "E0515 should have 2 return-reference-to-local patterns"
        );
    }

    #[test]
    fn test_error_code_counts_sum_to_total() {
        let patterns = get_bootstrap_patterns();
        let total = patterns.len();
        let e0308 = patterns.iter().filter(|p| p.error_code == "E0308").count();
        let e0133 = patterns.iter().filter(|p| p.error_code == "E0133").count();
        let e0382 = patterns.iter().filter(|p| p.error_code == "E0382").count();
        let e0499 = patterns.iter().filter(|p| p.error_code == "E0499").count();
        let e0506 = patterns.iter().filter(|p| p.error_code == "E0506").count();
        let e0597 = patterns.iter().filter(|p| p.error_code == "E0597").count();
        let e0515 = patterns.iter().filter(|p| p.error_code == "E0515").count();
        assert_eq!(
            e0308 + e0133 + e0382 + e0499 + e0506 + e0597 + e0515,
            total,
            "All error codes should account for all patterns"
        );
    }

    // ========================================================================
    // Decision type distribution tests
    // ========================================================================

    #[test]
    fn test_decision_type_coercion_patterns() {
        let patterns = get_bootstrap_patterns();
        let coercion: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "type_coercion")
            .collect();
        assert_eq!(coercion.len(), 2, "type_coercion should have 2 patterns");
        assert!(coercion.iter().all(|p| p.error_code == "E0308"));
    }

    #[test]
    fn test_decision_pointer_to_reference_patterns() {
        let patterns = get_bootstrap_patterns();
        let ptr_ref: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "pointer_to_reference")
            .collect();
        assert_eq!(ptr_ref.len(), 2, "pointer_to_reference should have 2 patterns");
        // One for *mut, one for *const
        assert!(ptr_ref.iter().any(|p| p.fix_diff.contains("*mut")));
        assert!(ptr_ref.iter().any(|p| p.fix_diff.contains("*const")));
    }

    #[test]
    fn test_decision_mutable_reference_pattern() {
        let patterns = get_bootstrap_patterns();
        let mut_ref: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "mutable_reference")
            .collect();
        assert_eq!(mut_ref.len(), 1, "mutable_reference should have 1 pattern");
        assert!(mut_ref[0].fix_diff.contains("&mut"));
    }

    #[test]
    fn test_decision_unsafe_deref_patterns() {
        let patterns = get_bootstrap_patterns();
        let deref: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "unsafe_deref")
            .collect();
        assert_eq!(deref.len(), 2, "unsafe_deref should have 2 patterns");
        for p in &deref {
            assert!(p.fix_diff.contains("unsafe"));
            assert!(p.error_code == "E0133");
        }
    }

    #[test]
    fn test_decision_unsafe_extern_pattern() {
        let patterns = get_bootstrap_patterns();
        let ext: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "unsafe_extern")
            .collect();
        assert_eq!(ext.len(), 1, "unsafe_extern should have 1 pattern");
        assert!(ext[0].fix_diff.contains("extern_fn"));
        assert!(ext[0].fix_diff.contains("unsafe"));
    }

    #[test]
    fn test_decision_clone_before_move_pattern() {
        let patterns = get_bootstrap_patterns();
        let clone_move: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "clone_before_move")
            .collect();
        assert_eq!(clone_move.len(), 1, "clone_before_move should have 1 pattern");
        assert!(clone_move[0].fix_diff.contains(".clone()"));
        assert_eq!(clone_move[0].error_code, "E0382");
    }

    #[test]
    fn test_decision_borrow_instead_of_move_pattern() {
        let patterns = get_bootstrap_patterns();
        let borrow: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "borrow_instead_of_move")
            .collect();
        assert_eq!(borrow.len(), 1, "borrow_instead_of_move should have 1 pattern");
        assert!(borrow[0].fix_diff.contains("&x"));
    }

    #[test]
    fn test_decision_borrow_parameter_pattern() {
        let patterns = get_bootstrap_patterns();
        let borrow_param: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "borrow_parameter")
            .collect();
        assert_eq!(borrow_param.len(), 1, "borrow_parameter should have 1 pattern");
        assert!(borrow_param[0].fix_diff.contains("&String"));
    }

    #[test]
    fn test_decision_sequential_mutable_borrow_pattern() {
        let patterns = get_bootstrap_patterns();
        let seq_mut: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "sequential_mutable_borrow")
            .collect();
        assert_eq!(seq_mut.len(), 1, "sequential_mutable_borrow should have 1 pattern");
        assert!(seq_mut[0].fix_diff.contains("drop"));
    }

    #[test]
    fn test_decision_use_stdlib_method_pattern() {
        let patterns = get_bootstrap_patterns();
        let stdlib: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "use_stdlib_method")
            .collect();
        assert_eq!(stdlib.len(), 1, "use_stdlib_method should have 1 pattern");
        assert!(stdlib[0].fix_diff.contains("arr.swap"));
    }

    #[test]
    fn test_decision_reorder_borrow_pattern() {
        let patterns = get_bootstrap_patterns();
        let reorder: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "reorder_borrow")
            .collect();
        assert_eq!(reorder.len(), 1, "reorder_borrow should have 1 pattern");
        assert_eq!(reorder[0].error_code, "E0506");
    }

    #[test]
    fn test_decision_extend_lifetime_pattern() {
        let patterns = get_bootstrap_patterns();
        let extend: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "extend_lifetime")
            .collect();
        assert_eq!(extend.len(), 1, "extend_lifetime should have 1 pattern");
        assert_eq!(extend[0].error_code, "E0597");
        assert!(extend[0].description.contains("outer scope"));
    }

    #[test]
    fn test_decision_return_owned_patterns() {
        let patterns = get_bootstrap_patterns();
        let owned: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "return_owned")
            .collect();
        assert_eq!(owned.len(), 2, "return_owned should have 2 patterns (E0597 + E0515)");
        let error_codes: Vec<_> = owned.iter().map(|p| p.error_code).collect();
        assert!(error_codes.contains(&"E0597"));
        assert!(error_codes.contains(&"E0515"));
    }

    #[test]
    fn test_decision_clone_return_pattern() {
        let patterns = get_bootstrap_patterns();
        let clone_ret: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "clone_return")
            .collect();
        assert_eq!(clone_ret.len(), 1, "clone_return should have 1 pattern");
        assert!(clone_ret[0].fix_diff.contains(".clone()"));
        assert_eq!(clone_ret[0].error_code, "E0515");
    }

    #[test]
    fn test_decision_array_to_slice_pattern() {
        let patterns = get_bootstrap_patterns();
        let slice: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "array_to_slice")
            .collect();
        assert_eq!(slice.len(), 1, "array_to_slice should have 1 pattern");
        assert!(slice[0].fix_diff.contains("&[i32]"));
        assert!(slice[0].description.contains("slice"));
    }

    #[test]
    fn test_decision_bounds_checked_access_pattern() {
        let patterns = get_bootstrap_patterns();
        let bounds: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "bounds_checked_access")
            .collect();
        assert_eq!(bounds.len(), 1, "bounds_checked_access should have 1 pattern");
        assert!(bounds[0].fix_diff.contains(".get(i)"));
        assert!(bounds[0].fix_diff.contains("unwrap_or"));
    }

    #[test]
    fn test_decision_safe_pointer_arithmetic_pattern() {
        let patterns = get_bootstrap_patterns();
        let arith: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "safe_pointer_arithmetic")
            .collect();
        assert_eq!(arith.len(), 1, "safe_pointer_arithmetic should have 1 pattern");
        assert!(arith[0].fix_diff.contains("wrapping_add"));
    }

    #[test]
    fn test_decision_malloc_to_box_pattern() {
        let patterns = get_bootstrap_patterns();
        let malloc_box: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "malloc_to_box")
            .collect();
        assert_eq!(malloc_box.len(), 1, "malloc_to_box should have 1 pattern");
        assert!(
            malloc_box[0].fix_diff.contains("Box::new"),
            "malloc_to_box pattern should contain Box::new"
        );
        assert!(malloc_box[0].fix_diff.contains("malloc"));
    }

    #[test]
    fn test_decision_malloc_array_to_vec_pattern() {
        let patterns = get_bootstrap_patterns();
        let malloc_vec: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "malloc_array_to_vec")
            .collect();
        assert_eq!(malloc_vec.len(), 1, "malloc_array_to_vec should have 1 pattern");
        assert!(malloc_vec[0].fix_diff.contains("Vec::with_capacity"));
    }

    #[test]
    fn test_decision_arrow_to_dot_pattern() {
        let patterns = get_bootstrap_patterns();
        let arrow: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "arrow_to_dot")
            .collect();
        assert_eq!(arrow.len(), 1, "arrow_to_dot should have 1 pattern");
        assert!(arrow[0].fix_diff.contains("p->field"));
        assert!(arrow[0].fix_diff.contains("p.field"));
    }

    #[test]
    fn test_decision_nullable_to_option_pattern() {
        let patterns = get_bootstrap_patterns();
        let nullable: Vec<_> = patterns
            .iter()
            .filter(|p| p.decision == "nullable_to_option")
            .collect();
        assert_eq!(nullable.len(), 1, "nullable_to_option should have 1 pattern");
        assert!(nullable[0].fix_diff.contains("Option<Box<Node>>"));
    }

    #[test]
    fn test_all_decision_types_covered() {
        let patterns = get_bootstrap_patterns();
        let mut decisions: std::collections::HashSet<&str> = std::collections::HashSet::new();
        for p in &patterns {
            decisions.insert(p.decision);
        }
        let expected_decisions = vec![
            "type_coercion",
            "pointer_to_reference",
            "mutable_reference",
            "unsafe_deref",
            "unsafe_extern",
            "clone_before_move",
            "borrow_instead_of_move",
            "borrow_parameter",
            "sequential_mutable_borrow",
            "use_stdlib_method",
            "reorder_borrow",
            "extend_lifetime",
            "return_owned",
            "clone_return",
            "array_to_slice",
            "bounds_checked_access",
            "safe_pointer_arithmetic",
            "malloc_to_box",
            "malloc_array_to_vec",
            "arrow_to_dot",
            "nullable_to_option",
        ];
        assert_eq!(
            decisions.len(),
            expected_decisions.len(),
            "Number of unique decision types should match expected"
        );
        for d in &expected_decisions {
            assert!(decisions.contains(d), "Missing decision type: {}", d);
        }
    }

    // ========================================================================
    // Specific pattern content validation (ordered by vec position)
    // ========================================================================

    #[test]
    fn test_pattern_0_type_coercion_cast() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[0];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "type_coercion");
        assert!(p.fix_diff.contains("as i32"));
        assert!(p.description.contains("explicit type cast"));
    }

    #[test]
    fn test_pattern_1_mut_pointer_to_ref() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[1];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "pointer_to_reference");
        assert!(p.fix_diff.contains("*mut i32"));
        assert!(p.fix_diff.contains("&mut i32"));
    }

    #[test]
    fn test_pattern_2_const_pointer_to_ref() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[2];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "pointer_to_reference");
        assert!(p.fix_diff.contains("*const i32"));
        assert!(p.fix_diff.contains("&i32"));
    }

    #[test]
    fn test_pattern_3_mutable_reference() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[3];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "mutable_reference");
        assert!(p.fix_diff.contains("swap"));
        assert!(p.fix_diff.contains("&mut x"));
    }

    #[test]
    fn test_pattern_4_exit_cast() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[4];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "type_coercion");
        assert!(p.fix_diff.contains("std::process::exit"));
    }

    #[test]
    fn test_pattern_5_unsafe_deref_write() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[5];
        assert_eq!(p.error_code, "E0133");
        assert_eq!(p.decision, "unsafe_deref");
        assert!(p.fix_diff.contains("*ptr = value"));
        assert!(p.description.contains("dereference"));
    }

    #[test]
    fn test_pattern_6_unsafe_deref_read() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[6];
        assert_eq!(p.error_code, "E0133");
        assert_eq!(p.decision, "unsafe_deref");
        assert!(p.fix_diff.contains("let x = *ptr"));
        assert!(p.description.contains("pointer read"));
    }

    #[test]
    fn test_pattern_7_unsafe_extern() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[7];
        assert_eq!(p.error_code, "E0133");
        assert_eq!(p.decision, "unsafe_extern");
        assert!(p.fix_diff.contains("extern_fn()"));
    }

    #[test]
    fn test_pattern_8_clone_before_move() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[8];
        assert_eq!(p.error_code, "E0382");
        assert_eq!(p.decision, "clone_before_move");
        assert!(p.fix_diff.contains("value.clone()"));
    }

    #[test]
    fn test_pattern_9_borrow_instead_of_move() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[9];
        assert_eq!(p.error_code, "E0382");
        assert_eq!(p.decision, "borrow_instead_of_move");
        assert!(p.fix_diff.contains("let y = &x"));
    }

    #[test]
    fn test_pattern_10_borrow_parameter() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[10];
        assert_eq!(p.error_code, "E0382");
        assert_eq!(p.decision, "borrow_parameter");
        assert!(p.fix_diff.contains("fn take(s: &String)"));
    }

    #[test]
    fn test_pattern_11_sequential_mutable_borrow() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[11];
        assert_eq!(p.error_code, "E0499");
        assert_eq!(p.decision, "sequential_mutable_borrow");
        assert!(p.fix_diff.contains("drop(a)"));
    }

    #[test]
    fn test_pattern_12_use_stdlib_swap() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[12];
        assert_eq!(p.error_code, "E0499");
        assert_eq!(p.decision, "use_stdlib_method");
        assert!(p.fix_diff.contains("arr.swap(i, j)"));
    }

    #[test]
    fn test_pattern_13_reorder_borrow() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[13];
        assert_eq!(p.error_code, "E0506");
        assert_eq!(p.decision, "reorder_borrow");
        assert!(p.fix_diff.contains("x = 5"));
    }

    #[test]
    fn test_pattern_14_extend_lifetime() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[14];
        assert_eq!(p.error_code, "E0597");
        assert_eq!(p.decision, "extend_lifetime");
        assert!(p.description.contains("outer scope"));
    }

    #[test]
    fn test_pattern_15_return_owned_e0597() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[15];
        assert_eq!(p.error_code, "E0597");
        assert_eq!(p.decision, "return_owned");
        assert!(p.fix_diff.contains("-> i32"));
    }

    #[test]
    fn test_pattern_16_return_owned_e0515() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[16];
        assert_eq!(p.error_code, "E0515");
        assert_eq!(p.decision, "return_owned");
        assert!(p.fix_diff.contains("-> Vec<i32>"));
    }

    #[test]
    fn test_pattern_17_clone_return() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[17];
        assert_eq!(p.error_code, "E0515");
        assert_eq!(p.decision, "clone_return");
        assert!(p.fix_diff.contains("local.clone()"));
    }

    #[test]
    fn test_pattern_18_array_to_slice() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[18];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "array_to_slice");
        assert!(p.fix_diff.contains("&[i32]"));
    }

    #[test]
    fn test_pattern_19_bounds_checked_access() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[19];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "bounds_checked_access");
        assert!(p.fix_diff.contains("arr.get(i).copied().unwrap_or(0)"));
    }

    #[test]
    fn test_pattern_20_safe_pointer_arithmetic() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[20];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "safe_pointer_arithmetic");
        assert!(p.fix_diff.contains("ptr.wrapping_add(offset)"));
    }

    #[test]
    fn test_pattern_21_malloc_to_box() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[21];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "malloc_to_box");
        assert!(p.fix_diff.contains("Box::new(value)"));
    }

    #[test]
    fn test_pattern_22_malloc_array_to_vec() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[22];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "malloc_array_to_vec");
        assert!(p.fix_diff.contains("Vec::with_capacity(n)"));
    }

    #[test]
    fn test_pattern_23_arrow_to_dot() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[23];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "arrow_to_dot");
        assert!(p.fix_diff.contains("p->field"));
        assert!(p.fix_diff.contains("p.field"));
    }

    #[test]
    fn test_pattern_24_nullable_to_option() {
        let patterns = get_bootstrap_patterns();
        let p = &patterns[24];
        assert_eq!(p.error_code, "E0308");
        assert_eq!(p.decision, "nullable_to_option");
        assert!(p.fix_diff.contains("Option<Box<Node>>"));
    }

    // ========================================================================
    // BootstrapStats comprehensive tests
    // ========================================================================

    #[test]
    fn test_bootstrap_stats_total_matches_patterns() {
        let patterns = get_bootstrap_patterns();
        let stats = BootstrapStats::from_patterns();
        assert_eq!(stats.total_patterns, patterns.len());
    }

    #[test]
    fn test_bootstrap_stats_error_code_counts() {
        let stats = BootstrapStats::from_patterns();
        assert_eq!(stats.by_error_code.get("E0308"), Some(&12));
        assert_eq!(stats.by_error_code.get("E0133"), Some(&3));
        assert_eq!(stats.by_error_code.get("E0382"), Some(&3));
        assert_eq!(stats.by_error_code.get("E0499"), Some(&2));
        assert_eq!(stats.by_error_code.get("E0506"), Some(&1));
        assert_eq!(stats.by_error_code.get("E0597"), Some(&2));
        assert_eq!(stats.by_error_code.get("E0515"), Some(&2));
    }

    #[test]
    fn test_bootstrap_stats_error_code_count_is_7() {
        let stats = BootstrapStats::from_patterns();
        assert_eq!(
            stats.by_error_code.len(),
            7,
            "Should have exactly 7 distinct error codes"
        );
    }

    #[test]
    fn test_bootstrap_stats_decision_counts() {
        let stats = BootstrapStats::from_patterns();
        assert_eq!(stats.by_decision.get("type_coercion"), Some(&2));
        assert_eq!(stats.by_decision.get("pointer_to_reference"), Some(&2));
        assert_eq!(stats.by_decision.get("mutable_reference"), Some(&1));
        assert_eq!(stats.by_decision.get("unsafe_deref"), Some(&2));
        assert_eq!(stats.by_decision.get("unsafe_extern"), Some(&1));
        assert_eq!(stats.by_decision.get("clone_before_move"), Some(&1));
        assert_eq!(stats.by_decision.get("borrow_instead_of_move"), Some(&1));
        assert_eq!(stats.by_decision.get("borrow_parameter"), Some(&1));
        assert_eq!(stats.by_decision.get("sequential_mutable_borrow"), Some(&1));
        assert_eq!(stats.by_decision.get("use_stdlib_method"), Some(&1));
        assert_eq!(stats.by_decision.get("reorder_borrow"), Some(&1));
        assert_eq!(stats.by_decision.get("extend_lifetime"), Some(&1));
        assert_eq!(stats.by_decision.get("return_owned"), Some(&2));
        assert_eq!(stats.by_decision.get("clone_return"), Some(&1));
        assert_eq!(stats.by_decision.get("array_to_slice"), Some(&1));
        assert_eq!(stats.by_decision.get("bounds_checked_access"), Some(&1));
        assert_eq!(stats.by_decision.get("safe_pointer_arithmetic"), Some(&1));
        assert_eq!(stats.by_decision.get("malloc_to_box"), Some(&1));
        assert_eq!(stats.by_decision.get("malloc_array_to_vec"), Some(&1));
        assert_eq!(stats.by_decision.get("arrow_to_dot"), Some(&1));
        assert_eq!(stats.by_decision.get("nullable_to_option"), Some(&1));
    }

    #[test]
    fn test_bootstrap_stats_decision_count_is_21() {
        let stats = BootstrapStats::from_patterns();
        assert_eq!(
            stats.by_decision.len(),
            21,
            "Should have exactly 21 distinct decision types"
        );
    }

    #[test]
    fn test_bootstrap_stats_pretty_contains_all_error_codes() {
        let stats = BootstrapStats::from_patterns();
        let pretty = stats.to_string_pretty();
        assert!(pretty.contains("E0308"));
        assert!(pretty.contains("E0133"));
        assert!(pretty.contains("E0382"));
        assert!(pretty.contains("E0499"));
        assert!(pretty.contains("E0506"));
        assert!(pretty.contains("E0597"));
        assert!(pretty.contains("E0515"));
    }

    #[test]
    fn test_bootstrap_stats_pretty_contains_counts() {
        let stats = BootstrapStats::from_patterns();
        let pretty = stats.to_string_pretty();
        // E0308 has 12 patterns
        assert!(pretty.contains("E0308: 12"), "Pretty format should show E0308: 12");
    }

    #[test]
    fn test_bootstrap_stats_pretty_sorted_error_codes() {
        let stats = BootstrapStats::from_patterns();
        let pretty = stats.to_string_pretty();
        // Error codes should appear in sorted order
        let e0133_pos = pretty.find("E0133").expect("E0133 should be in output");
        let e0308_pos = pretty.find("E0308").expect("E0308 should be in output");
        let e0382_pos = pretty.find("E0382").expect("E0382 should be in output");
        let e0499_pos = pretty.find("E0499").expect("E0499 should be in output");
        let e0506_pos = pretty.find("E0506").expect("E0506 should be in output");
        assert!(e0133_pos < e0308_pos, "E0133 should appear before E0308");
        assert!(e0308_pos < e0382_pos, "E0308 should appear before E0382");
        assert!(e0382_pos < e0499_pos, "E0382 should appear before E0499");
        assert!(e0499_pos < e0506_pos, "E0499 should appear before E0506");
    }

    #[test]
    fn test_bootstrap_stats_pretty_decisions_sorted_by_count_descending() {
        let stats = BootstrapStats::from_patterns();
        let pretty = stats.to_string_pretty();
        // Decisions with count 2 should appear before decisions with count 1
        // type_coercion has count 2, arrow_to_dot has count 1
        let decision_section_start = pretty
            .find("By Decision Type:")
            .expect("Should have decision section");
        let type_coercion_pos = pretty[decision_section_start..]
            .find("type_coercion")
            .expect("type_coercion should be in output");
        let arrow_to_dot_pos = pretty[decision_section_start..]
            .find("arrow_to_dot")
            .expect("arrow_to_dot should be in output");
        assert!(
            type_coercion_pos < arrow_to_dot_pos,
            "type_coercion (count 2) should appear before arrow_to_dot (count 1)"
        );
    }

    #[test]
    fn test_bootstrap_stats_default() {
        let stats = BootstrapStats::default();
        assert_eq!(stats.total_patterns, 0);
        assert!(stats.by_error_code.is_empty());
        assert!(stats.by_decision.is_empty());
    }

    #[test]
    fn test_bootstrap_pattern_debug_impl() {
        let patterns = get_bootstrap_patterns();
        for p in &patterns {
            let debug_str = format!("{:?}", p);
            assert!(debug_str.contains("BootstrapPattern"));
            assert!(debug_str.contains(p.error_code));
            assert!(debug_str.contains(p.decision));
        }
    }

    #[test]
    fn test_bootstrap_pattern_clone_impl() {
        let patterns = get_bootstrap_patterns();
        for p in &patterns {
            let cloned = p.clone();
            assert_eq!(cloned.error_code, p.error_code);
            assert_eq!(cloned.fix_diff, p.fix_diff);
            assert_eq!(cloned.decision, p.decision);
            assert_eq!(cloned.description, p.description);
        }
    }

    #[test]
    fn test_bootstrap_stats_debug_impl() {
        let stats = BootstrapStats::from_patterns();
        let debug_str = format!("{:?}", stats);
        assert!(debug_str.contains("BootstrapStats"));
        assert!(debug_str.contains("total_patterns"));
    }

    // ========================================================================
    // Fix diff content validation (ensures diff format correctness)
    // ========================================================================

    #[test]
    fn test_all_fix_diffs_have_minus_and_plus_lines() {
        let patterns = get_bootstrap_patterns();
        for p in &patterns {
            assert!(
                p.fix_diff.contains('-'),
                "Pattern '{}' fix_diff missing '-' line: {}",
                p.decision,
                p.fix_diff
            );
            assert!(
                p.fix_diff.contains('+'),
                "Pattern '{}' fix_diff missing '+' line: {}",
                p.decision,
                p.fix_diff
            );
        }
    }

    #[test]
    fn test_all_descriptions_start_with_capital() {
        let patterns = get_bootstrap_patterns();
        for p in &patterns {
            assert!(
                p.description.starts_with(|c: char| c.is_uppercase()),
                "Description should start with capital letter: '{}'",
                p.description
            );
        }
    }

    #[test]
    fn test_all_decisions_are_snake_case() {
        let patterns = get_bootstrap_patterns();
        for p in &patterns {
            assert!(
                p.decision.chars().all(|c| c.is_lowercase() || c == '_'),
                "Decision should be snake_case: '{}'",
                p.decision
            );
        }
    }

    #[test]
    fn test_all_error_codes_are_numeric_after_e() {
        let patterns = get_bootstrap_patterns();
        for p in &patterns {
            let code_num = &p.error_code[1..];
            assert!(
                code_num.chars().all(|c| c.is_ascii_digit()),
                "Error code after E should be numeric: '{}'",
                p.error_code
            );
        }
    }

    // ========================================================================
    // Deep coverage: force line-level execution of every struct literal
    // by snapshot-asserting the full content of every pattern field
    // ========================================================================

    /// Collect all (error_code, decision, description, fix_diff_len) tuples
    /// to force the compiler to materialize every field.
    #[test]
    fn test_snapshot_all_pattern_fields_materialized() {
        let patterns = get_bootstrap_patterns();
        let mut snapshot: Vec<(&str, &str, &str, usize)> = Vec::new();
        for p in &patterns {
            snapshot.push((
                p.error_code,
                p.decision,
                p.description,
                p.fix_diff.len(),
            ));
        }
        // Verify snapshot length matches pattern count
        assert_eq!(snapshot.len(), 25);

        // Verify each entry has non-empty fields
        for (i, (code, decision, desc, diff_len)) in snapshot.iter().enumerate() {
            assert!(!code.is_empty(), "Pattern {} error_code empty", i);
            assert!(!decision.is_empty(), "Pattern {} decision empty", i);
            assert!(!desc.is_empty(), "Pattern {} description empty", i);
            assert!(*diff_len > 0, "Pattern {} fix_diff empty", i);
        }
    }

    /// Hash every pattern's content to force all field reads.
    #[test]
    fn test_pattern_content_hashing_forces_field_access() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let patterns = get_bootstrap_patterns();
        let mut hashes: Vec<u64> = Vec::new();

        for p in &patterns {
            let mut hasher = DefaultHasher::new();
            p.error_code.hash(&mut hasher);
            p.fix_diff.hash(&mut hasher);
            p.decision.hash(&mut hasher);
            p.description.hash(&mut hasher);
            hashes.push(hasher.finish());
        }

        // All hashes should be unique (each pattern has unique content)
        let unique_count = {
            let mut sorted = hashes.clone();
            sorted.sort();
            sorted.dedup();
            sorted.len()
        };
        assert_eq!(
            unique_count,
            hashes.len(),
            "All patterns should have unique content hashes"
        );
    }

    /// Concatenate all fix_diffs and verify total content size is substantial.
    #[test]
    fn test_all_fix_diffs_concatenated_size() {
        let patterns = get_bootstrap_patterns();
        let total_diff_chars: usize = patterns.iter().map(|p| p.fix_diff.len()).sum();
        // 25 patterns with meaningful diffs should total > 500 chars
        assert!(
            total_diff_chars > 500,
            "Total fix_diff content should be >500 chars, got {}",
            total_diff_chars
        );
    }

    /// Verify specific fix_diff substring content for every pattern index.
    #[test]
    fn test_every_pattern_fix_diff_has_transformation() {
        let patterns = get_bootstrap_patterns();
        let expected_substrings: Vec<&str> = vec![
            "as i32",                     // 0: type_coercion cast
            "&mut i32",                   // 1: *mut -> &mut
            "&i32",                       // 2: *const -> &
            "&mut x",                     // 3: mutable_reference
            "std::process::exit",         // 4: exit cast
            "unsafe { *ptr = value; }",   // 5: unsafe deref write
            "unsafe { *ptr }",            // 6: unsafe deref read
            "unsafe { extern_fn(); }",    // 7: unsafe extern
            "value.clone()",              // 8: clone before move
            "let y = &x",                // 9: borrow instead of move
            "fn take(s: &String)",        // 10: borrow parameter
            "drop(a)",                    // 11: sequential mutable borrow
            "arr.swap(i, j)",             // 12: use stdlib method
            "x = 5",                      // 13: reorder borrow
            "let x = 5",                  // 14: extend lifetime
            "-> i32",                     // 15: return owned E0597
            "-> Vec<i32>",               // 16: return owned E0515
            "local.clone()",              // 17: clone return
            "&[i32]",                     // 18: array to slice
            "arr.get(i)",                 // 19: bounds checked access
            "wrapping_add",               // 20: safe pointer arithmetic
            "Box::new(value)",            // 21: malloc to box
            "Vec::with_capacity(n)",      // 22: malloc array to vec
            "p.field",                    // 23: arrow to dot
            "Option<Box<Node>>",          // 24: nullable to option
        ];

        assert_eq!(patterns.len(), expected_substrings.len());
        for (i, (p, expected)) in patterns.iter().zip(expected_substrings.iter()).enumerate() {
            assert!(
                p.fix_diff.contains(expected),
                "Pattern {} ({}) fix_diff should contain '{}', got: '{}'",
                i,
                p.decision,
                expected,
                p.fix_diff
            );
        }
    }

    /// Verify every description contains expected keywords.
    #[test]
    fn test_every_pattern_description_keywords() {
        let patterns = get_bootstrap_patterns();
        let expected_keywords: Vec<&str> = vec![
            "cast",           // 0
            "mutable",        // 1
            "immutable",      // 2
            "mutable",        // 3
            "Cast",           // 4
            "dereference",    // 5
            "pointer read",   // 6
            "extern function", // 7
            "Clone",          // 8
            "Borrow",         // 9
            "borrow",         // 10
            "mutable borrow", // 11
            "stdlib",         // 12
            "Reorder",        // 13
            "outer scope",    // 14
            "Return owned",   // 15
            "Return owned",   // 16
            "Clone local",    // 17
            "slice",          // 18
            "bounds",         // 19
            "pointer arithmetic", // 20
            "Box",            // 21
            "Vec",            // 22
            "arrow",          // 23
            "Option",         // 24
        ];

        assert_eq!(patterns.len(), expected_keywords.len());
        for (i, (p, keyword)) in patterns.iter().zip(expected_keywords.iter()).enumerate() {
            assert!(
                p.description.contains(keyword),
                "Pattern {} ({}) description should contain '{}', got: '{}'",
                i,
                p.decision,
                keyword,
                p.description
            );
        }
    }

    /// Verify the exact sequence of decisions in order.
    #[test]
    fn test_pattern_decision_sequence() {
        let patterns = get_bootstrap_patterns();
        let decisions: Vec<&str> = patterns.iter().map(|p| p.decision).collect();
        let expected = vec![
            "type_coercion",
            "pointer_to_reference",
            "pointer_to_reference",
            "mutable_reference",
            "type_coercion",
            "unsafe_deref",
            "unsafe_deref",
            "unsafe_extern",
            "clone_before_move",
            "borrow_instead_of_move",
            "borrow_parameter",
            "sequential_mutable_borrow",
            "use_stdlib_method",
            "reorder_borrow",
            "extend_lifetime",
            "return_owned",
            "return_owned",
            "clone_return",
            "array_to_slice",
            "bounds_checked_access",
            "safe_pointer_arithmetic",
            "malloc_to_box",
            "malloc_array_to_vec",
            "arrow_to_dot",
            "nullable_to_option",
        ];
        assert_eq!(decisions, expected, "Decision sequence should match exactly");
    }

    /// Verify the exact sequence of error codes in order.
    #[test]
    fn test_pattern_error_code_sequence() {
        let patterns = get_bootstrap_patterns();
        let codes: Vec<&str> = patterns.iter().map(|p| p.error_code).collect();
        let expected = vec![
            "E0308", "E0308", "E0308", "E0308", "E0308", // type mismatch group
            "E0133", "E0133", "E0133",                     // unsafe group
            "E0382", "E0382", "E0382",                     // use after move group
            "E0499", "E0499",                               // multiple mutable borrow group
            "E0506",                                         // assign to borrowed
            "E0597", "E0597",                               // lifetime group
            "E0515", "E0515",                               // return reference to local group
            "E0308", "E0308", "E0308",                     // C-specific array/pointer
            "E0308", "E0308",                               // C-specific malloc
            "E0308", "E0308",                               // C-specific struct
        ];
        assert_eq!(codes, expected, "Error code sequence should match exactly");
    }

    /// Verify all fix_diffs contain both removal and addition lines.
    #[test]
    fn test_every_fix_diff_has_removal_and_addition() {
        let patterns = get_bootstrap_patterns();
        for (i, p) in patterns.iter().enumerate() {
            let has_removal = p.fix_diff.lines().any(|l| l.starts_with('-'));
            let has_addition = p.fix_diff.lines().any(|l| l.starts_with('+'));
            assert!(
                has_removal,
                "Pattern {} ({}) should have '-' removal line in fix_diff: '{}'",
                i, p.decision, p.fix_diff
            );
            assert!(
                has_addition,
                "Pattern {} ({}) should have '+' addition line in fix_diff: '{}'",
                i, p.decision, p.fix_diff
            );
        }
    }

    /// Force materialization of patterns by collecting into a formatted string.
    #[test]
    fn test_format_all_patterns_to_string() {
        let patterns = get_bootstrap_patterns();
        let mut output = String::new();
        for (i, p) in patterns.iter().enumerate() {
            output.push_str(&format!(
                "[{}] {} | {} | {} | diff_len={}\n",
                i, p.error_code, p.decision, p.description, p.fix_diff.len()
            ));
        }
        // Should have 25 entries (one per pattern)
        assert_eq!(output.lines().count(), 25);
        // Total output should be substantial
        assert!(output.len() > 500, "Formatted output should be >500 chars");
    }

    /// Test that patterns can be cloned into a new vec without losing data.
    #[test]
    fn test_clone_all_patterns_preserves_data() {
        let originals = get_bootstrap_patterns();
        let clones: Vec<BootstrapPattern> = originals
            .iter()
            .map(|p| p.clone())
            .collect();

        assert_eq!(originals.len(), clones.len());
        for (orig, cloned) in originals.iter().zip(clones.iter()) {
            assert_eq!(orig.error_code, cloned.error_code);
            assert_eq!(orig.fix_diff, cloned.fix_diff);
            assert_eq!(orig.decision, cloned.decision);
            assert_eq!(orig.description, cloned.description);
        }
    }

    /// Verify patterns are grouped by error category sections.
    #[test]
    fn test_patterns_grouped_by_error_category() {
        let patterns = get_bootstrap_patterns();

        // E0308 type mismatch: indices 0-4
        for i in 0..5 {
            assert_eq!(
                patterns[i].error_code, "E0308",
                "Index {} should be E0308",
                i
            );
        }

        // E0133 unsafe: indices 5-7
        for i in 5..8 {
            assert_eq!(
                patterns[i].error_code, "E0133",
                "Index {} should be E0133",
                i
            );
        }

        // E0382 use after move: indices 8-10
        for i in 8..11 {
            assert_eq!(
                patterns[i].error_code, "E0382",
                "Index {} should be E0382",
                i
            );
        }

        // E0499 multiple mutable borrow: indices 11-12
        for i in 11..13 {
            assert_eq!(
                patterns[i].error_code, "E0499",
                "Index {} should be E0499",
                i
            );
        }

        // E0506 assign to borrowed: index 13
        assert_eq!(patterns[13].error_code, "E0506");

        // E0597 lifetime: indices 14-15
        for i in 14..16 {
            assert_eq!(
                patterns[i].error_code, "E0597",
                "Index {} should be E0597",
                i
            );
        }

        // E0515 return ref to local: indices 16-17
        for i in 16..18 {
            assert_eq!(
                patterns[i].error_code, "E0515",
                "Index {} should be E0515",
                i
            );
        }

        // C-specific E0308: indices 18-24
        for i in 18..25 {
            assert_eq!(
                patterns[i].error_code, "E0308",
                "Index {} should be E0308",
                i
            );
        }
    }

    /// Verify every pattern's fix_diff has multiple lines (contains newlines).
    #[test]
    fn test_all_fix_diffs_are_multiline() {
        let patterns = get_bootstrap_patterns();
        for (i, p) in patterns.iter().enumerate() {
            let line_count = p.fix_diff.lines().count();
            assert!(
                line_count >= 2,
                "Pattern {} ({}) fix_diff should have at least 2 lines, got {}",
                i,
                p.decision,
                line_count
            );
        }
    }

    /// Test that calling get_bootstrap_patterns twice returns identical data.
    #[test]
    fn test_get_bootstrap_patterns_is_deterministic() {
        let first = get_bootstrap_patterns();
        let second = get_bootstrap_patterns();
        assert_eq!(first.len(), second.len());
        for (a, b) in first.iter().zip(second.iter()) {
            assert_eq!(a.error_code, b.error_code);
            assert_eq!(a.fix_diff, b.fix_diff);
            assert_eq!(a.decision, b.decision);
            assert_eq!(a.description, b.description);
        }
    }

    /// Verify unique decisions count matches expected.
    #[test]
    fn test_unique_decisions_count() {
        let patterns = get_bootstrap_patterns();
        let unique: std::collections::HashSet<&str> =
            patterns.iter().map(|p| p.decision).collect();
        assert_eq!(unique.len(), 21);
    }

    /// Verify unique error codes count matches expected.
    #[test]
    fn test_unique_error_codes_count() {
        let patterns = get_bootstrap_patterns();
        let unique: std::collections::HashSet<&str> =
            patterns.iter().map(|p| p.error_code).collect();
        assert_eq!(unique.len(), 7);
    }

    /// BootstrapStats: verify by_decision sum matches total.
    #[test]
    fn test_bootstrap_stats_decision_sum_matches_total() {
        let stats = BootstrapStats::from_patterns();
        let decision_sum: usize = stats.by_decision.values().sum();
        assert_eq!(
            decision_sum, stats.total_patterns,
            "Sum of decision counts should equal total patterns"
        );
    }

    /// BootstrapStats: verify by_error_code sum matches total.
    #[test]
    fn test_bootstrap_stats_error_code_sum_matches_total() {
        let stats = BootstrapStats::from_patterns();
        let code_sum: usize = stats.by_error_code.values().sum();
        assert_eq!(
            code_sum, stats.total_patterns,
            "Sum of error code counts should equal total patterns"
        );
    }

    /// Test BootstrapStats pretty format line count.
    #[test]
    fn test_bootstrap_stats_pretty_line_count() {
        let stats = BootstrapStats::from_patterns();
        let pretty = stats.to_string_pretty();
        let line_count = pretty.lines().count();
        // Header (1) + blank (1) + "By Error Code:" (1) + 7 codes + blank (1)
        // + "By Decision Type:" (1) + 21 decisions = 33+
        assert!(
            line_count >= 30,
            "Pretty format should have at least 30 lines, got {}",
            line_count
        );
    }

    /// Verify BootstrapStats default has zero values.
    #[test]
    fn test_bootstrap_stats_default_values_are_zero() {
        let stats = BootstrapStats::default();
        assert_eq!(stats.total_patterns, 0);
        assert_eq!(stats.by_error_code.len(), 0);
        assert_eq!(stats.by_decision.len(), 0);
        let pretty = stats.to_string_pretty();
        assert!(pretty.contains("Bootstrap Patterns: 0"));
    }
}