aprender-orchestrate 0.29.0

Sovereign AI orchestration: autonomous agents, ML serving, code analysis, and transpilation pipelines
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
// =========================================================================
// BH-MOD-022: Coverage Gap Tests — source_forbids_unsafe / crate_forbids_unsafe
// =========================================================================

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_022_source_forbids_unsafe_present() {
    let temp = std::env::temp_dir().join("test_bh_mod_022_forbid");
    let _ = std::fs::create_dir_all(&temp);
    let file = temp.join("lib.rs");
    // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
    std::fs::write(&file, "#![forbid(unsafe_code)]\nfn safe() {}\n").unwrap();

    assert!(source_forbids_unsafe(&file));

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_022_source_forbids_unsafe_absent() {
    let temp = std::env::temp_dir().join("test_bh_mod_022_noforbid");
    let _ = std::fs::create_dir_all(&temp);
    let file = temp.join("lib.rs");
    // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
    std::fs::write(&file, "fn uses_unsafe() { unsafe {} }\n").unwrap();

    assert!(!source_forbids_unsafe(&file));

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_022_source_forbids_unsafe_nonexistent() {
    assert!(!source_forbids_unsafe(Path::new("/nonexistent/lib.rs")));
}

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_022_crate_forbids_unsafe_via_librs() {
    let temp = std::env::temp_dir().join("test_bh_mod_022_crate_lib");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    std::fs::write(
        temp.join("src/lib.rs"),
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "#![forbid(unsafe_code)]\npub fn safe() {}\n",
    )
    .unwrap();

    assert!(crate_forbids_unsafe(&temp));

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_022_crate_forbids_unsafe_via_cargo_toml() {
    let temp = std::env::temp_dir().join("test_bh_mod_022_crate_toml");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    std::fs::write(temp.join("src/lib.rs"), "pub fn code() {}\n").unwrap();
    std::fs::write(
        temp.join("Cargo.toml"),
        "[lints.rust]\nunsafe_code = \"forbid\"\n",
    )
    .unwrap();

    assert!(crate_forbids_unsafe(&temp));

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_022_crate_no_forbid() {
    let temp = std::env::temp_dir().join("test_bh_mod_022_crate_none");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    std::fs::write(temp.join("src/lib.rs"), "pub fn code() {}\n").unwrap();
    std::fs::write(temp.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();

    assert!(!crate_forbids_unsafe(&temp));

    let _ = std::fs::remove_dir_all(&temp);
}

// =========================================================================
// BH-MOD-023: Coverage Gap Tests — run_fuzz_mode
// =========================================================================

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_023_fuzz_mode_forbids_unsafe() {
    let temp = std::env::temp_dir().join("test_bh_mod_023_fuzz_forbid");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    std::fs::write(
        temp.join("src/lib.rs"),
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "#![forbid(unsafe_code)]\npub fn safe() {}\n",
    )
    .unwrap();

    let config = HuntConfig {
        mode: HuntMode::Fuzz,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Fuzz, config.clone());
    run_fuzz_mode(&temp, &config, &mut result);

    assert!(result.findings.iter().any(|f| f.id == "BH-FUZZ-SKIPPED"));
}

#[test]
fn test_bh_mod_023_fuzz_mode_no_fuzz_dir() {
    let temp = std::env::temp_dir().join("test_bh_mod_023_fuzz_nofuzz");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    std::fs::write(temp.join("src/lib.rs"), "pub fn code() {}\n").unwrap();

    let config = HuntConfig {
        mode: HuntMode::Fuzz,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Fuzz, config.clone());
    run_fuzz_mode(&temp, &config, &mut result);

    assert!(result.findings.iter().any(|f| f.id == "BH-FUZZ-NOTARGETS"));
}

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_023_fuzz_mode_with_unsafe() {
    let temp = std::env::temp_dir().join("test_bh_mod_023_fuzz_unsafe");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    std::fs::write(
        temp.join("src/lib.rs"),
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "pub fn danger() {\n    unsafe {\n        let ptr = 0 as *const i32;\n        let _ = *ptr;\n    }\n}\n",
    )
    .unwrap();

    let config = HuntConfig {
        mode: HuntMode::Fuzz,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Fuzz, config.clone());
    run_fuzz_mode(&temp, &config, &mut result);

    // Should find unsafe blocks + FUZZ-NOTARGETS (no fuzz dir)
    assert!(result.findings.iter().any(|f| f.id == "BH-FUZZ-NOTARGETS"));
    assert_eq!(result.stats.mode_stats.fuzz_coverage, 0.0);

    let _ = std::fs::remove_dir_all(&temp);
}

// =========================================================================
// BH-MOD-024: Coverage Gap Tests — hunt_with_spec
// =========================================================================

#[test]
fn test_bh_mod_024_hunt_with_spec_basic() {
    let temp = std::env::temp_dir().join("test_bh_mod_024_spec");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    let spec_content =
        "# Test Spec\n\n## Section 1\n\n### TST-01: Test Claim\n\nThis claim tests something.\n";
    std::fs::write(temp.join("spec.md"), spec_content).unwrap();

    std::fs::write(
        temp.join("src/lib.rs"),
        "// TST-01: implements test claim\nfn test_impl() {\n    let x = 42; // TODO: fix\n}\n",
    )
    .unwrap();

    let config = HuntConfig {
        mode: HuntMode::Analyze,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };

    let result = hunt_with_spec(&temp, &temp.join("spec.md"), None, config);
    assert!(result.is_ok());
    let (hunt_result, parsed_spec) = result.unwrap();
    assert!(!parsed_spec.claims.is_empty());
    assert_eq!(parsed_spec.claims[0].id, "TST-01");
    // Hunt ran (non-zero duration) or produced no findings
    assert!(hunt_result.duration_ms > 0);

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_024_hunt_with_spec_section_filter() {
    let temp = std::env::temp_dir().join("test_bh_mod_024_section");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    let spec_content = "\
## Security\n\n### SEC-01: Auth Check\n\nAuth claim.\n\n\
## Performance\n\n### PERF-01: Cache Opt\n\nPerf claim.\n";
    std::fs::write(temp.join("spec.md"), spec_content).unwrap();
    std::fs::write(temp.join("src/lib.rs"), "fn main() {}\n").unwrap();

    let config = HuntConfig {
        mode: HuntMode::Analyze,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };

    let result = hunt_with_spec(&temp, &temp.join("spec.md"), Some("Security"), config);
    assert!(result.is_ok());
    let (_hunt_result, parsed_spec) = result.unwrap();
    assert_eq!(parsed_spec.claims.len(), 2);

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_024_hunt_with_spec_nonexistent() {
    let config = HuntConfig::default();
    let result = hunt_with_spec(
        Path::new("/tmp"),
        Path::new("/nonexistent/spec.md"),
        None,
        config,
    );
    assert!(result.is_err());
}

// =========================================================================
// BH-MOD-025: Coverage Gap Tests — hunt_ensemble
// =========================================================================

#[test]
fn test_bh_mod_025_hunt_ensemble() {
    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let result = hunt_ensemble(Path::new("."), config);
    assert!(result.duration_ms > 0);
}

// =========================================================================
// BH-MOD-026: scan_file_for_unsafe_blocks
// =========================================================================

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_026_scan_file_no_unsafe() {
    let temp = std::env::temp_dir().join("test_scan_no_unsafe.rs");
    std::fs::write(&temp, "fn safe_function() { let x = 1; }\n").unwrap();

    let mut finding_id = 0;
    let mut unsafe_inventory = Vec::new();
    let mut result = HuntResult::default();

    scan_file_for_unsafe_blocks(&temp, &mut finding_id, &mut unsafe_inventory, &mut result);

    assert!(result.findings.is_empty());
    assert!(unsafe_inventory.is_empty());
    assert_eq!(finding_id, 0);

    let _ = std::fs::remove_file(&temp);
}

#[test]
fn test_bh_mod_026_scan_file_ptr_deref() {
    let temp = std::env::temp_dir().join("test_scan_ptr_deref.rs");
    std::fs::write(
        &temp,
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "fn danger() {\n    unsafe {\n        let val = *ptr;\n    }\n}\n",
    )
    .unwrap();

    let mut finding_id = 0;
    let mut unsafe_inventory = Vec::new();
    let mut result = HuntResult::default();

    scan_file_for_unsafe_blocks(&temp, &mut finding_id, &mut unsafe_inventory, &mut result);

    assert!(
        !result.findings.is_empty(),
        "Should detect pointer dereference in unsafe block"
    );
    assert!(finding_id > 0);
    assert!(!unsafe_inventory.is_empty());

    let finding = &result.findings[0];
    assert!(finding.id.contains("BH-UNSAFE"));
    assert_eq!(finding.severity, FindingSeverity::High);

    let _ = std::fs::remove_file(&temp);
}

#[test]
fn test_bh_mod_026_scan_file_transmute() {
    let temp = std::env::temp_dir().join("test_scan_transmute.rs");
    std::fs::write(
        &temp,
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "fn danger() {\n    unsafe {\n        let v = std::mem::transmute::<u32, f32>(bits);\n    }\n}\n",
    )
    .unwrap();

    let mut finding_id = 0;
    let mut unsafe_inventory = Vec::new();
    let mut result = HuntResult::default();

    scan_file_for_unsafe_blocks(&temp, &mut finding_id, &mut unsafe_inventory, &mut result);

    assert!(
        !result.findings.is_empty(),
        "Should detect transmute in unsafe block"
    );
    let finding = &result.findings[0];
    assert!(finding.id.contains("BH-UNSAFE"));
    assert_eq!(finding.severity, FindingSeverity::Critical);

    let _ = std::fs::remove_file(&temp);
}

#[test]
fn test_bh_mod_026_scan_file_both_patterns() {
    let temp = std::env::temp_dir().join("test_scan_both.rs");
    std::fs::write(
        &temp,
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "fn danger() {\n    unsafe {\n        let val = *ptr as *const u8;\n        let f = std::mem::transmute(bits);\n    }\n}\n",
    )
    .unwrap();

    let mut finding_id = 0;
    let mut unsafe_inventory = Vec::new();
    let mut result = HuntResult::default();

    scan_file_for_unsafe_blocks(&temp, &mut finding_id, &mut unsafe_inventory, &mut result);

    assert!(
        result.findings.len() >= 2,
        "Should detect both ptr deref and transmute, got {}",
        result.findings.len()
    );

    let _ = std::fs::remove_file(&temp);
}

#[test]
fn test_bh_mod_026_scan_file_nonexistent() {
    let mut finding_id = 0;
    let mut unsafe_inventory = Vec::new();
    let mut result = HuntResult::default();

    scan_file_for_unsafe_blocks(
        Path::new("/nonexistent/file.rs"),
        &mut finding_id,
        &mut unsafe_inventory,
        &mut result,
    );

    assert!(result.findings.is_empty());
}

// =========================================================================
// BH-MOD-027: extract_clippy_finding
// =========================================================================

#[test]
fn test_bh_mod_027_clippy_non_compiler_message() {
    let msg = serde_json::json!({
        "reason": "build-script-executed"
    });
    let config = HuntConfig::default();
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(result.is_none());
}

#[test]
fn test_bh_mod_027_clippy_info_level_skipped() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "note",
            "message": "Some info",
            "spans": [{"file_name": "src/lib.rs", "line_start": 1}],
            "code": {"code": "some_lint"}
        }
    });
    let config = HuntConfig::default();
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(result.is_none());
}

#[test]
fn test_bh_mod_027_clippy_dead_code_skipped() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "warning",
            "message": "unused variable",
            "spans": [{"file_name": "src/lib.rs", "line_start": 10}],
            "code": {"code": "dead_code"}
        }
    });
    let config = HuntConfig::default();
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(result.is_none(), "dead_code should be filtered");
}

#[test]
fn test_bh_mod_027_clippy_unused_imports_skipped() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "warning",
            "message": "unused import",
            "spans": [{"file_name": "src/lib.rs", "line_start": 5}],
            "code": {"code": "unused_imports"}
        }
    });
    let config = HuntConfig::default();
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(result.is_none(), "unused_imports should be filtered");
}

#[test]
fn test_bh_mod_027_clippy_valid_warning() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "warning",
            "message": "this could be rewritten more concisely",
            "spans": [{"file_name": "src/pipeline.rs", "line_start": 42}],
            "code": {"code": "clippy::needless_return"}
        }
    });
    let config = HuntConfig {
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(
        result.is_some(),
        "Valid clippy warning should produce a finding"
    );
    let finding = result.unwrap();
    assert!(finding.id.contains("BH-CLIP"));
    assert_eq!(finding_id, 1);
}

#[test]
fn test_bh_mod_027_clippy_error_level() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "error",
            "message": "mismatched types",
            "spans": [{"file_name": "src/main.rs", "line_start": 100}],
            "code": {"code": "E0308"}
        }
    });
    let config = HuntConfig {
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(result.is_some(), "Error level should produce a finding");
}

#[test]
fn test_bh_mod_027_clippy_min_suspiciousness_filter() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "warning",
            "message": "minor style issue",
            "spans": [{"file_name": "src/lib.rs", "line_start": 1}],
            "code": {"code": "clippy::style"}
        }
    });
    let config = HuntConfig {
        min_suspiciousness: 0.99,
        ..Default::default()
    };
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(
        result.is_none(),
        "Low suspiciousness finding should be filtered by high min_suspiciousness"
    );
}

#[test]
fn test_bh_mod_027_clippy_no_spans() {
    let msg = serde_json::json!({
        "reason": "compiler-message",
        "message": {
            "level": "warning",
            "message": "something",
            "spans": [],
            "code": {"code": "some_lint"}
        }
    });
    let config = HuntConfig::default();
    let mut finding_id = 0;

    let result = extract_clippy_finding(&msg, &config, &mut finding_id);
    assert!(result.is_none(), "Empty spans should return None");
}

// =========================================================================
// BH-MOD-028: categorize_clippy_warning
// =========================================================================

#[test]
// SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
fn test_bh_mod_028_categorize_clippy_unsafe() {
    let (cat, sev) =
        categorize_clippy_warning("clippy::undocumented_unsafe_blocks", "unsafe block");
    assert_eq!(cat, DefectCategory::SecurityVulnerabilities);
    assert!(matches!(
        sev,
        FindingSeverity::Critical | FindingSeverity::High
    ));
}

#[test]
fn test_bh_mod_028_categorize_clippy_unknown() {
    let (cat, sev) = categorize_clippy_warning("some_random_lint", "something");
    // Unknown lints should get a default categorization
    let _ = cat;
    let _ = sev;
}

// =========================================================================
// BH-MOD-029: Coverage Gap Tests — parse_defect_category
// =========================================================================

#[test]
fn test_bh_mod_029_parse_defect_category_logic() {
    assert_eq!(
        parse_defect_category("logicerrors"),
        DefectCategory::LogicErrors
    );
    assert_eq!(parse_defect_category("logic"), DefectCategory::LogicErrors);
    assert_eq!(parse_defect_category("Logic"), DefectCategory::LogicErrors);
    assert_eq!(
        parse_defect_category("LOGICERRORS"),
        DefectCategory::LogicErrors
    );
}

#[test]
fn test_bh_mod_029_parse_defect_category_memory() {
    assert_eq!(
        parse_defect_category("memorysafety"),
        DefectCategory::MemorySafety
    );
    assert_eq!(
        parse_defect_category("memory"),
        DefectCategory::MemorySafety
    );
    assert_eq!(
        parse_defect_category("MEMORY"),
        DefectCategory::MemorySafety
    );
}

#[test]
fn test_bh_mod_029_parse_defect_category_concurrency() {
    assert_eq!(
        parse_defect_category("concurrency"),
        DefectCategory::ConcurrencyBugs
    );
    assert_eq!(
        parse_defect_category("concurrencybugs"),
        DefectCategory::ConcurrencyBugs
    );
}

#[test]
fn test_bh_mod_029_parse_defect_category_gpu() {
    assert_eq!(
        parse_defect_category("gpukernelbugs"),
        DefectCategory::GpuKernelBugs
    );
    assert_eq!(parse_defect_category("gpu"), DefectCategory::GpuKernelBugs);
}

#[test]
fn test_bh_mod_029_parse_defect_category_silent() {
    assert_eq!(
        parse_defect_category("silentdegradation"),
        DefectCategory::SilentDegradation
    );
    assert_eq!(
        parse_defect_category("silent"),
        DefectCategory::SilentDegradation
    );
}

#[test]
fn test_bh_mod_029_parse_defect_category_test() {
    assert_eq!(parse_defect_category("testdebt"), DefectCategory::TestDebt);
    assert_eq!(parse_defect_category("test"), DefectCategory::TestDebt);
}

#[test]
fn test_bh_mod_029_parse_defect_category_hidden() {
    assert_eq!(
        parse_defect_category("hiddendebt"),
        DefectCategory::HiddenDebt
    );
    assert_eq!(parse_defect_category("debt"), DefectCategory::HiddenDebt);
}

#[test]
fn test_bh_mod_029_parse_defect_category_performance() {
    assert_eq!(
        parse_defect_category("performanceissues"),
        DefectCategory::PerformanceIssues
    );
    assert_eq!(
        parse_defect_category("performance"),
        DefectCategory::PerformanceIssues
    );
}

#[test]
fn test_bh_mod_029_parse_defect_category_security() {
    assert_eq!(
        parse_defect_category("securityvulnerabilities"),
        DefectCategory::SecurityVulnerabilities
    );
    assert_eq!(
        parse_defect_category("security"),
        DefectCategory::SecurityVulnerabilities
    );
}

#[test]
fn test_bh_mod_029_parse_defect_category_unknown_defaults_logic() {
    assert_eq!(
        parse_defect_category("nonsense"),
        DefectCategory::LogicErrors
    );
    assert_eq!(parse_defect_category(""), DefectCategory::LogicErrors);
    assert_eq!(parse_defect_category("xyzzy"), DefectCategory::LogicErrors);
}

// =========================================================================
// BH-MOD-030: Coverage Gap Tests — parse_finding_severity
// =========================================================================

#[test]
fn test_bh_mod_030_parse_finding_severity_critical() {
    assert_eq!(
        parse_finding_severity("critical"),
        FindingSeverity::Critical
    );
    assert_eq!(
        parse_finding_severity("Critical"),
        FindingSeverity::Critical
    );
    assert_eq!(
        parse_finding_severity("CRITICAL"),
        FindingSeverity::Critical
    );
}

#[test]
fn test_bh_mod_030_parse_finding_severity_high() {
    assert_eq!(parse_finding_severity("high"), FindingSeverity::High);
    assert_eq!(parse_finding_severity("High"), FindingSeverity::High);
}

#[test]
fn test_bh_mod_030_parse_finding_severity_medium() {
    assert_eq!(parse_finding_severity("medium"), FindingSeverity::Medium);
    assert_eq!(parse_finding_severity("Medium"), FindingSeverity::Medium);
}

#[test]
fn test_bh_mod_030_parse_finding_severity_low() {
    assert_eq!(parse_finding_severity("low"), FindingSeverity::Low);
    assert_eq!(parse_finding_severity("Low"), FindingSeverity::Low);
}

#[test]
fn test_bh_mod_030_parse_finding_severity_info() {
    assert_eq!(parse_finding_severity("info"), FindingSeverity::Info);
    assert_eq!(parse_finding_severity("Info"), FindingSeverity::Info);
}

#[test]
fn test_bh_mod_030_parse_finding_severity_unknown_defaults_medium() {
    assert_eq!(parse_finding_severity("nonsense"), FindingSeverity::Medium);
    assert_eq!(parse_finding_severity(""), FindingSeverity::Medium);
    assert_eq!(parse_finding_severity("warning"), FindingSeverity::Medium);
}

// =========================================================================
// BH-MOD-031: Coverage Gap Tests — detect_mutation_targets
// =========================================================================

#[test]
fn test_bh_mod_031_detect_mutation_no_targets() {
    let matches = detect_mutation_targets("let x = 42;");
    assert!(matches.is_empty());
}

#[test]
fn test_bh_mod_031_detect_mutation_boundary() {
    let matches = detect_mutation_targets("if v.len() > 0 {");
    assert!(matches.iter().any(|m| m.prefix == "boundary"));
}

#[test]
fn test_bh_mod_031_detect_mutation_boundary_size() {
    let matches = detect_mutation_targets("if buf.size() <= limit {");
    assert!(matches.iter().any(|m| m.prefix == "boundary"));
}

#[test]
fn test_bh_mod_031_detect_mutation_arithmetic_cast() {
    let matches = detect_mutation_targets("let idx = offset + count as usize;");
    assert!(matches.iter().any(|m| m.prefix == "arith"));
}

#[test]
fn test_bh_mod_031_detect_mutation_arithmetic_safe_ops() {
    // saturating_ prevents arithmetic pattern
    let matches = detect_mutation_targets("let x = a.saturating_add(1) as usize;");
    assert!(
        !matches.iter().any(|m| m.prefix == "arith"),
        "saturating_ ops should not trigger"
    );
}

#[test]
fn test_bh_mod_031_detect_mutation_boolean() {
    let matches = detect_mutation_targets("if !active && is_valid(x) {");
    assert!(matches.iter().any(|m| m.prefix == "bool"));
}

#[test]
fn test_bh_mod_031_detect_mutation_boolean_or_predicate() {
    let matches = detect_mutation_targets("if has_data(x) || !is_empty(x) {");
    assert!(matches.iter().any(|m| m.prefix == "bool"));
}

#[test]
fn test_bh_mod_031_detect_mutation_multiple() {
    // Line with both boundary and boolean
    let matches = detect_mutation_targets("if v.len() >= 1 && !is_valid(x) || has_data(y) {");
    assert!(
        matches.len() >= 2,
        "Should detect boundary + boolean, got {}",
        matches.len()
    );
}

// =========================================================================
// BH-MOD-032: Coverage Gap Tests — run_falsify_mode
// =========================================================================

#[test]
fn test_bh_mod_032_falsify_mode_with_source_files() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_032_falsify_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    // File with boundary and arithmetic patterns
    std::fs::write(
        temp.join("src/code.rs"),
        "fn process(v: &[u8]) -> usize {\n\
            if v.len() > 0 {\n\
                let idx = v.len() - 1 as usize;\n\
                idx\n\
            } else {\n\
                0\n\
            }\n\
        }\n",
    )
    .unwrap();

    let config = HuntConfig {
        mode: HuntMode::Falsify,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Falsify, config.clone());

    run_falsify_mode(&temp, &config, &mut result);

    // When cargo-mutants is not installed, run_falsify_mode returns early
    // with a BH-FALSIFY-UNAVAIL info finding instead of scanning for
    // mutation targets.  This is the expected path in clean-room containers.
    let mutants_available = std::process::Command::new("cargo")
        .args(["mutants", "--version"])
        .output()
        .map(|o| o.status.success())
        .unwrap_or(false);

    if mutants_available {
        let mut_findings: Vec<_> = result
            .findings
            .iter()
            .filter(|f| f.id.starts_with("BH-MUT-"))
            .collect();
        assert!(
            !mut_findings.is_empty(),
            "Should find mutation targets in source files"
        );
    } else {
        assert!(
            result.findings.iter().any(|f| f.id == "BH-FALSIFY-UNAVAIL"),
            "Should report cargo-mutants unavailable"
        );
    }

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_032_falsify_mode_empty_dir() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_032_falsify_empty_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    let config = HuntConfig {
        mode: HuntMode::Falsify,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Falsify, config.clone());

    run_falsify_mode(&temp, &config, &mut result);

    // No .rs files => no mutation findings (might have unavail finding)
    let mut_findings: Vec<_> = result
        .findings
        .iter()
        .filter(|f| f.id.starts_with("BH-MUT-"))
        .collect();
    assert!(mut_findings.is_empty());

    let _ = std::fs::remove_dir_all(&temp);
}

// =========================================================================
// BH-MOD-033: Coverage Gap Tests — run_deep_hunt_mode
// =========================================================================

#[test]
fn test_bh_mod_033_deep_hunt_mode_with_files() {
    let temp = std::env::temp_dir().join("test_bh_mod_033_deep");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    // File with deeply nested conditionals
    std::fs::write(
        temp.join("src/deep.rs"),
        "fn complex(a: i32, b: i32, c: i32) {\n\
            if a > 0 {\n\
                if b > 0 {\n\
                    if c > 0 {\n\
                        println!(\"deep\");\n\
                    }\n\
                }\n\
            }\n\
        }\n",
    )
    .unwrap();

    let config = HuntConfig {
        mode: HuntMode::DeepHunt,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::DeepHunt, config.clone());

    run_deep_hunt_mode(&temp, &config, &mut result);

    let deep_findings: Vec<_> = result
        .findings
        .iter()
        .filter(|f| f.id.starts_with("BH-DEEP-"))
        .collect();
    assert!(
        !deep_findings.is_empty(),
        "Should find deeply nested conditionals"
    );

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_033_deep_hunt_mode_empty() {
    let temp = std::env::temp_dir().join("test_bh_mod_033_deep_empty");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    let config = HuntConfig {
        mode: HuntMode::DeepHunt,
        targets: vec![PathBuf::from("src")],
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::DeepHunt, config.clone());

    run_deep_hunt_mode(&temp, &config, &mut result);

    // No .rs files => no deep hunt findings (may have coverage findings)

    let _ = std::fs::remove_dir_all(&temp);
}

// =========================================================================
// BH-MOD-034: Coverage Gap Tests — analyze_common_patterns (extended)
// =========================================================================

#[test]
fn test_bh_mod_034_common_patterns_rust_memory_safety() {
    // Rust files use language-specific patterns from languages.rs, which include
    // unsafe and transmute patterns for MemorySafety category.
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_mem_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    std::fs::write(
        temp.join("src/mem.rs"),
        // SAFETY: no actual unsafe code -- test string literal or variable containing 'unsafe'
        "fn danger() {\n    unsafe { std::ptr::null::<u8>().read() };\n}\n",
    )
    .unwrap();

    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    let mem_finding = result
        .findings
        .iter()
        .any(|f| f.category == DefectCategory::MemorySafety);
    assert!(
        mem_finding,
        "Should detect unsafe block as MemorySafety pattern"
    );

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_034_common_patterns_hidden_debt() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_debt_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    std::fs::write(
        temp.join("src/lib.rs"),
        "// not implemented yet\nfn placeholder() {}\n",
    )
    .unwrap();

    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    let debt_finding = result
        .findings
        .iter()
        .any(|f| f.category == DefectCategory::HiddenDebt);
    assert!(
        debt_finding,
        "Should detect 'not implemented' as hidden debt"
    );

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_034_common_patterns_silent_degradation() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_silent_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    std::fs::write(
        temp.join("src/lib.rs"),
        "fn handle() {\n    x.unwrap_or_else(|_| default());\n}\nfn default() -> i32 { 0 }\n",
    )
    .unwrap();

    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    let silent_finding = result
        .findings
        .iter()
        .any(|f| f.category == DefectCategory::SilentDegradation);
    assert!(
        silent_finding,
        "Should detect .unwrap_or_else(|_| as silent degradation"
    );

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_034_common_patterns_test_debt() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_testdebt_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    std::fs::write(
        temp.join("src/tests.rs"),
        "#[cfg(test)]\nmod tests {\n    #[test]\n    #[ignore]\n    fn test_broken() {}\n}\n",
    )
    .unwrap();

    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    let test_debt = result
        .findings
        .iter()
        .any(|f| f.category == DefectCategory::TestDebt);
    assert!(test_debt, "Should detect #[ignore] as test debt");

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_034_common_patterns_gpu_keywords() {
    // GPU/CUDA keywords are in the gpu_patterns vec but for .rs files the
    // language-specific patterns override the fallback set. Verify that
    // analyze_common_patterns runs without error on CUDA-related content
    // and that standard Rust patterns (e.g., unwrap) still produce findings.
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_gpu_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    std::fs::write(
        temp.join("src/gpu.rs"),
        "// CUDA_ERROR: kernel launch failed\nfn broken_kernel() { x.unwrap(); }\n",
    )
    .unwrap();

    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    // Rust-language patterns (unwrap) should still be detected
    let has_logic_finding = result
        .findings
        .iter()
        .any(|f| f.category == DefectCategory::LogicErrors);
    assert!(
        has_logic_finding,
        "Should detect unwrap() as LogicErrors pattern in GPU-related file"
    );

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_034_common_patterns_with_custom_patterns() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_custom_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));
    let _ = std::fs::create_dir_all(temp.join(".pmat"));

    // Create a custom pattern config
    std::fs::write(
        temp.join(".pmat/bug-hunter.toml"),
        "[[patterns]]\npattern = \"PERF-ISSUE\"\ncategory = \"performance\"\nseverity = \"high\"\nsuspiciousness = 0.8\n",
    )
    .unwrap();

    std::fs::write(
        temp.join("src/perf.rs"),
        "// PERF-ISSUE: this loop is O(n^2)\nfn slow() {}\n",
    )
    .unwrap();

    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    let custom = result
        .findings
        .iter()
        .any(|f| f.title.contains("PERF-ISSUE"));
    assert!(custom, "Should detect custom pattern from config");

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_034_common_patterns_pmat_satd_mode() {
    let temp = std::env::temp_dir().join(format!("test_bh_mod_034_satd_{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(temp.join("src"));

    std::fs::write(
        temp.join("src/lib.rs"),
        "// TODO: fix this\nfn code() { let x = val.unwrap(); }\n",
    )
    .unwrap();

    // With pmat_satd enabled but no pmat available, patterns fall through
    let config = HuntConfig {
        targets: vec![PathBuf::from("src")],
        min_suspiciousness: 0.0,
        pmat_satd: true,
        ..Default::default()
    };
    let mut result = HuntResult::new(&temp, HuntMode::Analyze, config.clone());

    analyze_common_patterns(&temp, &config, &mut result);

    // PMAT SATD mode might skip TODO/FIXME patterns, but unwrap should still be caught
    // (This tests the pmat_satd branch at line 998)

    let _ = std::fs::remove_dir_all(&temp);
}

// =========================================================================
// BH-MOD-035: Coverage Gap Tests — parse_lcov_da_line
// =========================================================================

#[test]
fn test_bh_mod_035_parse_lcov_da_line_valid_uncovered() {
    let mut file_uncovered = std::collections::HashMap::new();
    parse_lcov_da_line("42,0", "src/lib.rs", &mut file_uncovered);
    assert_eq!(file_uncovered.get("src/lib.rs").unwrap(), &vec![42]);
}

#[test]
fn test_bh_mod_035_parse_lcov_da_line_valid_covered() {
    let mut file_uncovered = std::collections::HashMap::new();
    parse_lcov_da_line("10,5", "src/lib.rs", &mut file_uncovered);
    assert!(
        file_uncovered.is_empty(),
        "Covered lines should not be added"
    );
}

#[test]
fn test_bh_mod_035_parse_lcov_da_line_no_comma() {
    let mut file_uncovered = std::collections::HashMap::new();
    parse_lcov_da_line("42", "src/lib.rs", &mut file_uncovered);
    assert!(file_uncovered.is_empty(), "No comma should return early");
}

#[test]
fn test_bh_mod_035_parse_lcov_da_line_invalid_line_num() {
    let mut file_uncovered = std::collections::HashMap::new();
    parse_lcov_da_line("abc,0", "src/lib.rs", &mut file_uncovered);
    assert!(
        file_uncovered.is_empty(),
        "Invalid line number should return early"
    );
}

#[test]
fn test_bh_mod_035_parse_lcov_da_line_invalid_hits() {
    let mut file_uncovered = std::collections::HashMap::new();
    parse_lcov_da_line("42,xyz", "src/lib.rs", &mut file_uncovered);
    assert!(
        file_uncovered.is_empty(),
        "Invalid hits should return early"
    );
}

// =========================================================================
// BH-MOD-036: Coverage Gap Tests — report_uncovered_hotspots
// =========================================================================

#[test]
fn test_bh_mod_036_report_uncovered_hotspots_above_threshold() {
    let mut file_uncovered = std::collections::HashMap::new();
    file_uncovered.insert("src/lib.rs".to_string(), vec![1, 2, 3, 4, 5, 6]);

    let mut result = HuntResult::new("/project", HuntMode::Hunt, HuntConfig::default());
    report_uncovered_hotspots(file_uncovered, Path::new("/project"), &mut result);

    assert_eq!(result.findings.len(), 1);
    assert!(result.findings[0].id.starts_with("BH-COV-"));
    assert!(result.findings[0].title.contains("6 uncovered lines"));
}

#[test]
fn test_bh_mod_036_report_uncovered_hotspots_below_threshold() {
    let mut file_uncovered = std::collections::HashMap::new();
    file_uncovered.insert("src/lib.rs".to_string(), vec![1, 2, 3]);

    let mut result = HuntResult::new("/project", HuntMode::Hunt, HuntConfig::default());
    report_uncovered_hotspots(file_uncovered, Path::new("/project"), &mut result);

    assert!(
        result.findings.is_empty(),
        "<=5 uncovered lines should not produce a finding"
    );
}

#[test]
fn test_bh_mod_036_report_uncovered_hotspots_exactly_five() {
    let mut file_uncovered = std::collections::HashMap::new();
    file_uncovered.insert("src/lib.rs".to_string(), vec![1, 2, 3, 4, 5]);

    let mut result = HuntResult::new("/project", HuntMode::Hunt, HuntConfig::default());
    report_uncovered_hotspots(file_uncovered, Path::new("/project"), &mut result);

    assert!(
        result.findings.is_empty(),
        "Exactly 5 uncovered lines should not trigger (>5 is threshold)"
    );
}

#[test]
fn test_bh_mod_036_report_uncovered_hotspots_suspiciousness_cap() {
    let mut file_uncovered = std::collections::HashMap::new();
    // 200 uncovered lines => suspiciousness = (200/100).min(0.8) = 0.8
    file_uncovered.insert("src/huge.rs".to_string(), (1..=200).collect());

    let mut result = HuntResult::new("/project", HuntMode::Hunt, HuntConfig::default());
    report_uncovered_hotspots(file_uncovered, Path::new("/project"), &mut result);

    assert_eq!(result.findings.len(), 1);
    assert!(
        (result.findings[0].suspiciousness - 0.8).abs() < f64::EPSILON,
        "Should cap at 0.8"
    );
}

#[test]
fn test_bh_mod_036_report_uncovered_hotspots_multiple_files() {
    let mut file_uncovered = std::collections::HashMap::new();
    file_uncovered.insert("src/a.rs".to_string(), vec![1, 2, 3, 4, 5, 6]);
    file_uncovered.insert("src/b.rs".to_string(), vec![10, 20, 30, 40, 50, 60, 70]);
    file_uncovered.insert("src/c.rs".to_string(), vec![1]); // Below threshold

    let mut result = HuntResult::new("/project", HuntMode::Hunt, HuntConfig::default());
    report_uncovered_hotspots(file_uncovered, Path::new("/project"), &mut result);

    assert_eq!(
        result.findings.len(),
        2,
        "Only files with >5 uncovered lines"
    );
}

// =========================================================================
// BH-MOD-037: Coverage Gap Tests — categorize_clippy_warning (all branches)
// =========================================================================

#[test]
fn test_bh_mod_037_categorize_mem() {
    let (cat, sev) = categorize_clippy_warning("clippy::mem_replace", "memory");
    assert_eq!(cat, DefectCategory::MemorySafety);
    assert_eq!(sev, FindingSeverity::High);
}

#[test]
fn test_bh_mod_037_categorize_uninit() {
    let (cat, sev) = categorize_clippy_warning("clippy::uninit_assumed_init", "uninitialized");
    assert_eq!(cat, DefectCategory::MemorySafety);
    assert_eq!(sev, FindingSeverity::High);
}

#[test]
fn test_bh_mod_037_categorize_arc() {
    let (cat, sev) = categorize_clippy_warning("clippy::arc_with_non_send_sync", "arc issue");
    assert_eq!(cat, DefectCategory::ConcurrencyBugs);
    assert_eq!(sev, FindingSeverity::High);
}

#[test]
fn test_bh_mod_037_categorize_send() {
    let (cat, sev) = categorize_clippy_warning("not_send_bound", "not Send");
    assert_eq!(cat, DefectCategory::ConcurrencyBugs);
    assert_eq!(sev, FindingSeverity::High);
}

#[test]
fn test_bh_mod_037_categorize_sync() {
    let (cat, sev) = categorize_clippy_warning("not_sync_bound", "not Sync");
    assert_eq!(cat, DefectCategory::ConcurrencyBugs);
    assert_eq!(sev, FindingSeverity::High);
}

#[test]
fn test_bh_mod_037_categorize_transmute_security() {
    let (cat, sev) = categorize_clippy_warning("clippy::transmute_int_to_bool", "transmute");
    assert_eq!(cat, DefectCategory::SecurityVulnerabilities);
    assert_eq!(sev, FindingSeverity::High);
}

#[test]
fn test_bh_mod_037_categorize_expect() {
    let (cat, sev) = categorize_clippy_warning("clippy::expect_used", "expect");
    assert_eq!(cat, DefectCategory::LogicErrors);
    assert_eq!(sev, FindingSeverity::Medium);
}

#[test]
fn test_bh_mod_037_categorize_panic() {
    let (cat, sev) = categorize_clippy_warning("clippy::panic_in_result_fn", "panic");
    assert_eq!(cat, DefectCategory::LogicErrors);
    assert_eq!(sev, FindingSeverity::Medium);
}

#[test]
fn test_bh_mod_037_categorize_cast() {
    let (cat, sev) = categorize_clippy_warning("clippy::cast_sign_loss", "cast");
    assert_eq!(cat, DefectCategory::TypeErrors);
    assert_eq!(sev, FindingSeverity::Medium);
}

#[test]
fn test_bh_mod_037_categorize_as() {
    let (cat, sev) = categorize_clippy_warning("clippy::as_conversions", "as conversion");
    assert_eq!(cat, DefectCategory::TypeErrors);
    assert_eq!(sev, FindingSeverity::Medium);
}

#[test]
fn test_bh_mod_037_categorize_into() {
    let (cat, sev) = categorize_clippy_warning("clippy::into_iter_on_ref", "into iter");
    assert_eq!(cat, DefectCategory::TypeErrors);
    assert_eq!(sev, FindingSeverity::Medium);
}

// =========================================================================
// BH-MOD-038: Coverage Gap Tests — scan_file_for_patterns
// =========================================================================

#[test]
fn test_bh_mod_038_scan_file_for_patterns_basic() {
    let temp = std::env::temp_dir().join("test_bh_mod_038_patterns");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(&temp);

    let file = temp.join("scan_test.rs");
    std::fs::write(
        &file,
        "fn risky() {\n    let x = val.unwrap();\n    panic!(\"oops\");\n}\n",
    )
    .unwrap();

    let patterns: Vec<(&str, DefectCategory, FindingSeverity, f64)> = vec![
        (
            "unwrap()",
            DefectCategory::LogicErrors,
            FindingSeverity::Medium,
            0.4,
        ),
        (
            "panic!",
            DefectCategory::LogicErrors,
            FindingSeverity::Medium,
            0.5,
        ),
    ];
    let custom_patterns: Vec<(String, DefectCategory, FindingSeverity, f64)> = vec![];
    let bh_config = self::config::BugHunterConfig::default();
    let mut findings = Vec::new();

    scan_file_for_patterns(
        &file,
        &patterns,
        &custom_patterns,
        &bh_config,
        0.0,
        &mut findings,
    );

    assert!(
        findings.len() >= 2,
        "Should find unwrap and panic patterns, got {}",
        findings.len()
    );

    let _ = std::fs::remove_dir_all(&temp);
}

#[test]
fn test_bh_mod_038_scan_file_for_patterns_nonexistent() {
    let patterns: Vec<(&str, DefectCategory, FindingSeverity, f64)> = vec![];
    let custom_patterns: Vec<(String, DefectCategory, FindingSeverity, f64)> = vec![];
    let bh_config = self::config::BugHunterConfig::default();
    let mut findings = Vec::new();

    scan_file_for_patterns(
        Path::new("/nonexistent/file.rs"),
        &patterns,
        &custom_patterns,
        &bh_config,
        0.0,
        &mut findings,
    );

    assert!(findings.is_empty());
}

#[test]
fn test_bh_mod_038_scan_file_for_patterns_custom() {
    let temp = std::env::temp_dir().join("test_bh_mod_038_custom_scan");
    let _ = std::fs::remove_dir_all(&temp);
    let _ = std::fs::create_dir_all(&temp);

    let file = temp.join("custom.rs");
    std::fs::write(&file, "// MY-MARKER: review this\nfn code() {}\n").unwrap();

    let patterns: Vec<(&str, DefectCategory, FindingSeverity, f64)> = vec![];
    let custom_patterns = vec![(
        "MY-MARKER".to_string(),
        DefectCategory::LogicErrors,
        FindingSeverity::High,
        0.8,
    )];
    let bh_config = self::config::BugHunterConfig::default();
    let mut findings = Vec::new();

    scan_file_for_patterns(
        &file,
        &patterns,
        &custom_patterns,
        &bh_config,
        0.0,
        &mut findings,
    );

    assert!(findings.iter().any(|f| f.title.contains("MY-MARKER")));

    let _ = std::fs::remove_dir_all(&temp);
}