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
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
//! Pipeline module tests.

use super::*;
use std::path::{Path, PathBuf};

// ============================================================================
// PIPELINE CONTEXT TESTS
// ============================================================================

#[test]
fn test_pipeline_context_creation() {
    let input = PathBuf::from("/input");
    let output = PathBuf::from("/output");

    let ctx = PipelineContext::new(input.clone(), output.clone());

    assert_eq!(ctx.input_path, input);
    assert_eq!(ctx.output_path, output);
    assert!(ctx.primary_language.is_none());
    assert!(ctx.file_mappings.is_empty());
    assert!(ctx.optimizations.is_empty());
    assert!(ctx.validation_results.is_empty());
    assert!(ctx.metadata.is_empty());
}

#[test]
fn test_pipeline_context_with_language() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.primary_language = Some(crate::types::Language::Python);
    assert_eq!(ctx.primary_language, Some(crate::types::Language::Python));
}

#[test]
fn test_pipeline_context_file_mappings() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.file_mappings.push((PathBuf::from("/input/main.py"), PathBuf::from("/output/src/main.rs")));

    assert_eq!(ctx.file_mappings.len(), 1);
    assert_eq!(ctx.file_mappings[0].0, PathBuf::from("/input/main.py"));
    assert_eq!(ctx.file_mappings[0].1, PathBuf::from("/output/src/main.rs"));
}

#[test]
fn test_pipeline_context_optimizations() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.optimizations.push("SIMD enabled".to_string());
    ctx.optimizations.push("GPU dispatch enabled".to_string());

    assert_eq!(ctx.optimizations.len(), 2);
    assert_eq!(ctx.optimizations[0], "SIMD enabled");
    assert_eq!(ctx.optimizations[1], "GPU dispatch enabled");
}

#[test]
fn test_pipeline_context_validation_results() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.validation_results.push(ValidationResult {
        stage: "Analysis".to_string(),
        passed: true,
        message: "Language detected".to_string(),
        details: None,
    });

    assert_eq!(ctx.validation_results.len(), 1);
    assert!(ctx.validation_results[0].passed);
    assert_eq!(ctx.validation_results[0].stage, "Analysis");
}

#[test]
fn test_pipeline_context_metadata() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.metadata.insert("total_files".to_string(), serde_json::json!(42));
    ctx.metadata.insert("language".to_string(), serde_json::json!("Python"));

    assert_eq!(ctx.metadata.len(), 2);
    assert_eq!(ctx.metadata.get("total_files").unwrap(), &serde_json::json!(42));
    assert_eq!(ctx.metadata.get("language").unwrap(), &serde_json::json!("Python"));
}

#[test]
fn test_pipeline_context_output() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.file_mappings.push((PathBuf::from("/input/main.py"), PathBuf::from("/output/main.rs")));
    ctx.optimizations.push("SIMD".to_string());
    ctx.validation_results.push(ValidationResult {
        stage: "Test".to_string(),
        passed: true,
        message: "OK".to_string(),
        details: None,
    });

    let output = ctx.output();

    assert_eq!(output.output_path, PathBuf::from("/output"));
    assert_eq!(output.file_mappings.len(), 1);
    assert_eq!(output.optimizations.len(), 1);
    assert!(output.validation_passed);
}

#[test]
fn test_pipeline_context_output_validation_failed() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    // Add one passing and one failing validation result
    ctx.validation_results.push(ValidationResult {
        stage: "Stage1".to_string(),
        passed: true,
        message: "OK".to_string(),
        details: None,
    });
    ctx.validation_results.push(ValidationResult {
        stage: "Stage2".to_string(),
        passed: false,
        message: "Failed".to_string(),
        details: None,
    });

    let output = ctx.output();

    // Should be false because at least one validation failed
    assert!(!output.validation_passed);
}

// ============================================================================
// VALIDATION RESULT TESTS
// ============================================================================

#[test]
fn test_validation_result_passed() {
    let result = ValidationResult {
        stage: "TestStage".to_string(),
        passed: true,
        message: "All checks passed".to_string(),
        details: None,
    };

    assert_eq!(result.stage, "TestStage");
    assert!(result.passed);
    assert_eq!(result.message, "All checks passed");
    assert!(result.details.is_none());
}

#[test]
fn test_validation_result_failed() {
    let result = ValidationResult {
        stage: "TestStage".to_string(),
        passed: false,
        message: "Check failed".to_string(),
        details: Some(serde_json::json!({"error": "details here"})),
    };

    assert_eq!(result.stage, "TestStage");
    assert!(!result.passed);
    assert_eq!(result.message, "Check failed");
    assert!(result.details.is_some());
}

#[test]
fn test_validation_result_with_details() {
    let details = serde_json::json!({
        "errors": ["error1", "error2"],
        "warnings": ["warning1"]
    });

    let result = ValidationResult {
        stage: "Analysis".to_string(),
        passed: false,
        message: "Multiple issues found".to_string(),
        details: Some(details.clone()),
    };

    assert_eq!(result.details, Some(details));
}

// ============================================================================
// VALIDATION STRATEGY TESTS
// ============================================================================

#[test]
fn test_validation_strategy_equality() {
    assert_eq!(ValidationStrategy::StopOnError, ValidationStrategy::StopOnError);
    assert_eq!(ValidationStrategy::ContinueOnError, ValidationStrategy::ContinueOnError);
    assert_eq!(ValidationStrategy::None, ValidationStrategy::None);

    assert_ne!(ValidationStrategy::StopOnError, ValidationStrategy::ContinueOnError);
    assert_ne!(ValidationStrategy::StopOnError, ValidationStrategy::None);
    assert_ne!(ValidationStrategy::ContinueOnError, ValidationStrategy::None);
}

// ============================================================================
// TRANSPILATION PIPELINE TESTS
// ============================================================================

struct MockStage {
    name: String,
    should_fail: bool,
    validation_should_pass: bool,
}

impl MockStage {
    fn new(name: &str) -> Self {
        Self { name: name.to_string(), should_fail: false, validation_should_pass: true }
    }

    fn with_execution_failure(mut self) -> Self {
        self.should_fail = true;
        self
    }

    fn with_validation_failure(mut self) -> Self {
        self.validation_should_pass = false;
        self
    }
}

#[async_trait::async_trait]
impl PipelineStage for MockStage {
    fn name(&self) -> &str {
        &self.name
    }

    async fn execute(&self, mut ctx: PipelineContext) -> anyhow::Result<PipelineContext> {
        if self.should_fail {
            anyhow::bail!("Execution failed for {}", self.name);
        }

        ctx.metadata.insert(format!("{}_executed", self.name), serde_json::json!(true));

        Ok(ctx)
    }

    fn validate(&self, _ctx: &PipelineContext) -> anyhow::Result<ValidationResult> {
        Ok(ValidationResult {
            stage: self.name.clone(),
            passed: self.validation_should_pass,
            message: if self.validation_should_pass {
                format!("{} validation passed", self.name)
            } else {
                format!("{} validation failed", self.name)
            },
            details: None,
        })
    }
}

#[tokio::test]
async fn test_pipeline_creation() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError);
    assert_eq!(pipeline.stages.len(), 0);
    assert_eq!(pipeline.validation, ValidationStrategy::StopOnError);
}

#[tokio::test]
async fn test_pipeline_add_stage() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::None)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2")));

    assert_eq!(pipeline.stages.len(), 2);
}

#[tokio::test]
async fn test_pipeline_run_no_stages() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::None);

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    let pipeline_output = result.unwrap();
    assert_eq!(pipeline_output.output_path, output);
    assert!(pipeline_output.file_mappings.is_empty());
}

#[tokio::test]
async fn test_pipeline_run_single_stage() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::None)
        .add_stage(Box::new(MockStage::new("TestStage")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    let pipeline_output = result.unwrap();
    assert_eq!(pipeline_output.output_path, output);
}

#[tokio::test]
async fn test_pipeline_run_multiple_stages() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::None)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2")))
        .add_stage(Box::new(MockStage::new("Stage3")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());
}

#[tokio::test]
async fn test_pipeline_stage_execution_order() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::None)
        .add_stage(Box::new(MockStage::new("First")))
        .add_stage(Box::new(MockStage::new("Second")))
        .add_stage(Box::new(MockStage::new("Third")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    // Stages should execute in order, adding metadata
    // This is implicitly tested by the fact that execution succeeds
}

#[tokio::test]
async fn test_pipeline_stop_on_error_execution() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2").with_execution_failure()))
        .add_stage(Box::new(MockStage::new("Stage3")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_err());

    let err = result.unwrap_err();
    assert!(err.to_string().contains("Stage 'Stage2' failed"));
}

#[tokio::test]
async fn test_pipeline_stop_on_error_validation() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2").with_validation_failure()))
        .add_stage(Box::new(MockStage::new("Stage3")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_err());

    let err = result.unwrap_err();
    assert!(err.to_string().contains("Validation failed for stage 'Stage2'"));
}

#[tokio::test]
async fn test_pipeline_continue_on_error_validation() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::ContinueOnError)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2").with_validation_failure()))
        .add_stage(Box::new(MockStage::new("Stage3")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    // Validation failure should be recorded but pipeline continues
    let pipeline_output = result.unwrap();
    assert!(!pipeline_output.validation_passed);
}

#[tokio::test]
async fn test_pipeline_no_validation() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::None)
        .add_stage(Box::new(MockStage::new("Stage1").with_validation_failure()))
        .add_stage(Box::new(MockStage::new("Stage2").with_validation_failure()));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    // No validation should be performed, so pipeline succeeds
    let pipeline_output = result.unwrap();
    // With ValidationStrategy::None, no validation results are added
    assert!(pipeline_output.validation_passed); // All (zero) validations passed
}

// ============================================================================
// TRANSPILATION STAGE TESTS
// ============================================================================

#[test]
fn test_transpilation_stage_creation() {
    let stage = TranspilationStage::new(true, true);
    assert!(stage.incremental);
    assert!(stage.cache);
    // library_analyzer is initialized by default
    let _ = &stage.library_analyzer;
}

#[test]
fn test_transpilation_stage_name() {
    let stage = TranspilationStage::new(false, false);
    assert_eq!(stage.name(), "Transpilation");
}

// ============================================================================
// OPTIMIZATION STAGE TESTS
// ============================================================================

#[test]
fn test_optimization_stage_creation() {
    let stage = OptimizationStage::new(true, true, 1000);
    assert!(stage.enable_gpu);
    assert!(stage.enable_simd);
    assert_eq!(stage.gpu_threshold, 1000);
}

#[test]
fn test_optimization_stage_name() {
    let stage = OptimizationStage::new(false, false, 500);
    assert_eq!(stage.name(), "Optimization");
}

#[test]
fn test_optimization_stage_analyze_optimizations() {
    let stage = OptimizationStage::new(true, true, 1000);
    let recommendations = stage.analyze_optimizations();

    // Should return 3 recommendations (from the hardcoded workloads)
    assert_eq!(recommendations.len(), 3);

    // Check that recommendations contain backend information
    assert!(recommendations[0].contains("Element-wise operations"));
    assert!(recommendations[1].contains("Vector reductions"));
    assert!(recommendations[2].contains("Matrix multiplications"));
}

#[tokio::test]
async fn test_optimization_stage_execute() {
    let stage = OptimizationStage::new(true, true, 1000);

    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();

    // Check that optimizations were added
    assert!(!ctx.optimizations.is_empty());
    assert!(ctx.optimizations.iter().any(|o| o.contains("SIMD")));
    assert!(ctx.optimizations.iter().any(|o| o.contains("GPU")));

    // Check metadata
    assert!(ctx.metadata.contains_key("optimizations_applied"));
    assert!(ctx.metadata.contains_key("moe_routing_enabled"));
}

#[tokio::test]
async fn test_optimization_stage_simd_only() {
    let stage = OptimizationStage::new(false, true, 1000);

    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();

    // Should have SIMD but not GPU in traditional optimizations
    assert!(ctx.optimizations.iter().any(|o| o.contains("SIMD")));
    assert!(!ctx.optimizations.iter().any(|o| o.contains("GPU dispatch enabled")));
}

#[tokio::test]
async fn test_optimization_stage_gpu_only() {
    let stage = OptimizationStage::new(true, false, 2000);

    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();

    // Should have GPU but not SIMD in traditional optimizations
    assert!(!ctx.optimizations.iter().any(|o| o.contains("SIMD vectorization enabled")));
    assert!(ctx.optimizations.iter().any(|o| o.contains("GPU")));
    assert!(ctx.optimizations.iter().any(|o| o.contains("2000")));
}

// ============================================================================
// VALIDATION STAGE TESTS
// ============================================================================

#[test]
fn test_validation_stage_creation() {
    let stage = ValidationStage::new(true, true);
    assert!(stage.trace_syscalls);
    assert!(stage.run_tests);
}

#[test]
fn test_validation_stage_name() {
    let stage = ValidationStage::new(false, false);
    assert_eq!(stage.name(), "Validation");
}

#[test]
fn test_validation_stage_compare_traces_identical() {
    let trace1 =
        vec!["open(/file)".to_string(), "read(fd, buf, 100)".to_string(), "close(fd)".to_string()];

    let trace2 =
        vec!["open(/file)".to_string(), "read(fd, buf, 100)".to_string(), "close(fd)".to_string()];

    assert!(ValidationStage::compare_traces(&trace1, &trace2));
}

#[test]
fn test_validation_stage_compare_traces_different_length() {
    let trace1 = vec!["open(/file)".to_string(), "close(fd)".to_string()];

    let trace2 = vec!["open(/file)".to_string()];

    assert!(!ValidationStage::compare_traces(&trace1, &trace2));
}

#[test]
fn test_validation_stage_compare_traces_different_syscalls() {
    let trace1 = vec!["open(/file)".to_string(), "read(fd, buf, 100)".to_string()];

    let trace2 = vec!["open(/file)".to_string(), "write(fd, buf, 100)".to_string()];

    assert!(!ValidationStage::compare_traces(&trace1, &trace2));
}

#[test]
fn test_validation_stage_compare_traces_same_syscall_different_args() {
    // Should pass - only syscall names are compared, not arguments
    let trace1 = vec!["open(/file1)".to_string(), "read(fd, buf, 100)".to_string()];

    let trace2 = vec!["open(/file2)".to_string(), "read(fd, buf, 200)".to_string()];

    assert!(ValidationStage::compare_traces(&trace1, &trace2));
}

// ============================================================================
// BUILD STAGE TESTS
// ============================================================================

#[test]
fn test_build_stage_creation() {
    let stage = BuildStage::new(true, Some("x86_64-unknown-linux-gnu".to_string()), false);
    assert!(stage.release);
    assert_eq!(stage.target, Some("x86_64-unknown-linux-gnu".to_string()));
    assert!(!stage.wasm);
}

#[test]
fn test_build_stage_creation_wasm() {
    let stage = BuildStage::new(false, None, true);
    assert!(!stage.release);
    assert!(stage.target.is_none());
    assert!(stage.wasm);
}

#[test]
fn test_build_stage_name() {
    let stage = BuildStage::new(false, None, false);
    assert_eq!(stage.name(), "Build");
}

#[test]
fn test_build_stage_validate_no_build_dir() {
    let stage = BuildStage::new(true, None, false);

    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/nonexistent"));

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert!(!validation.passed);
    assert!(validation.message.contains("not found"));
}

// ============================================================================
// ANALYSIS STAGE TESTS
// ============================================================================

#[test]
fn test_analysis_stage_name() {
    let stage = AnalysisStage;
    assert_eq!(stage.name(), "Analysis");
}

#[test]
fn test_analysis_stage_validate_no_language() {
    let stage = AnalysisStage;

    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/output"));

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert!(!validation.passed);
    assert!(validation.message.contains("Could not detect"));
}

#[test]
fn test_analysis_stage_validate_with_language() {
    let stage = AnalysisStage;

    let mut ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/output"));
    ctx.primary_language = Some(crate::types::Language::Python);

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert!(validation.passed);
    assert!(validation.message.contains("Language detected"));
}

// ============================================================================
// SERIALIZATION TESTS
// ============================================================================

#[test]
fn test_pipeline_context_serialization() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));
    ctx.primary_language = Some(crate::types::Language::Python);
    ctx.file_mappings.push((PathBuf::from("a.py"), PathBuf::from("a.rs")));
    ctx.optimizations.push("SIMD".to_string());

    let json = serde_json::to_string(&ctx).unwrap();
    let deserialized: PipelineContext = serde_json::from_str(&json).unwrap();

    assert_eq!(ctx.input_path, deserialized.input_path);
    assert_eq!(ctx.output_path, deserialized.output_path);
    assert_eq!(ctx.primary_language, deserialized.primary_language);
    assert_eq!(ctx.file_mappings.len(), deserialized.file_mappings.len());
    assert_eq!(ctx.optimizations.len(), deserialized.optimizations.len());
}

#[test]
fn test_validation_result_serialization() {
    let result = ValidationResult {
        stage: "Test".to_string(),
        passed: true,
        message: "OK".to_string(),
        details: Some(serde_json::json!({"key": "value"})),
    };

    let json = serde_json::to_string(&result).unwrap();
    let deserialized: ValidationResult = serde_json::from_str(&json).unwrap();

    assert_eq!(result.stage, deserialized.stage);
    assert_eq!(result.passed, deserialized.passed);
    assert_eq!(result.message, deserialized.message);
    assert_eq!(result.details, deserialized.details);
}

#[test]
fn test_pipeline_output_serialization() {
    let output = PipelineOutput {
        output_path: PathBuf::from("/output"),
        file_mappings: vec![(PathBuf::from("a"), PathBuf::from("b"))],
        optimizations: vec!["opt1".to_string(), "opt2".to_string()],
        validation_passed: true,
    };

    let json = serde_json::to_string(&output).unwrap();
    let deserialized: PipelineOutput = serde_json::from_str(&json).unwrap();

    assert_eq!(output.output_path, deserialized.output_path);
    assert_eq!(output.file_mappings.len(), deserialized.file_mappings.len());
    assert_eq!(output.optimizations.len(), deserialized.optimizations.len());
    assert_eq!(output.validation_passed, deserialized.validation_passed);
}

// ============================================================================
// ANALYSIS STAGE EXECUTION TESTS
// ============================================================================

#[cfg(feature = "native")]
#[tokio::test]
async fn test_analysis_stage_execute_with_rust_project() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let src_dir = temp_dir.path().join("src");
    std::fs::create_dir(&src_dir).unwrap();
    std::fs::write(src_dir.join("main.rs"), "fn main() {}").unwrap();

    let stage = AnalysisStage;
    let ctx = PipelineContext::new(temp_dir.path().to_path_buf(), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.primary_language, Some(crate::types::Language::Rust));
    assert!(ctx.metadata.contains_key("total_files"));
    assert!(ctx.metadata.contains_key("total_lines"));
}

#[cfg(feature = "native")]
#[tokio::test]
async fn test_analysis_stage_execute_with_python_project() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    std::fs::write(temp_dir.path().join("main.py"), "print('hello')").unwrap();

    let stage = AnalysisStage;
    let ctx = PipelineContext::new(temp_dir.path().to_path_buf(), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.primary_language, Some(crate::types::Language::Python));
}

#[cfg(feature = "native")]
#[tokio::test]
async fn test_analysis_stage_execute_empty_directory() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();

    let stage = AnalysisStage;
    let ctx = PipelineContext::new(temp_dir.path().to_path_buf(), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert!(ctx.primary_language.is_none());
}

// ============================================================================
// TRANSPILATION STAGE EXECUTION TESTS
// ============================================================================

#[cfg(feature = "native")]
#[tokio::test]
async fn test_transpilation_stage_creates_directories() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("output");

    let stage = TranspilationStage::new(false, false);
    let mut ctx = PipelineContext::new(temp_dir.path().to_path_buf(), output_dir.clone());
    ctx.primary_language = Some(crate::types::Language::Rust);

    // This will fail at transpilation but should create directories
    let _result = stage.execute(ctx).await;

    // Check that directories were created even if transpilation fails
    assert!(output_dir.exists());
    assert!(output_dir.join("src").exists());
}

#[test]
fn test_transpilation_stage_validate_empty_output() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("output");
    std::fs::create_dir_all(output_dir.join("src")).unwrap();

    let stage = TranspilationStage::new(false, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), output_dir.clone());

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    // Should fail because src dir is empty
    assert!(!validation.passed);
}

#[test]
fn test_transpilation_stage_validate_with_files() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("output");
    std::fs::create_dir_all(output_dir.join("src")).unwrap();
    std::fs::write(output_dir.join("src/main.rs"), "fn main() {}").unwrap();

    let stage = TranspilationStage::new(false, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), output_dir.clone());

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert!(validation.passed);
}

// ============================================================================
// BUILD STAGE EXECUTION TESTS
// ============================================================================

#[test]
fn test_build_stage_validate_debug_build() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("output");
    std::fs::create_dir_all(output_dir.join("target/debug")).unwrap();

    let stage = BuildStage::new(false, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), output_dir.clone());

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert!(validation.passed);
}

#[test]
fn test_build_stage_validate_release_build() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let output_dir = temp_dir.path().join("output");
    std::fs::create_dir_all(output_dir.join("target/release")).unwrap();

    let stage = BuildStage::new(true, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), output_dir.clone());

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert!(validation.passed);
}

// ============================================================================
// VALIDATION STAGE TESTS
// ============================================================================

#[tokio::test]
async fn test_validation_stage_execute_no_binaries() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();

    let stage = ValidationStage::new(true, false);
    let ctx = PipelineContext::new(temp_dir.path().to_path_buf(), temp_dir.path().join("output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert!(ctx.metadata.contains_key("validation_completed"));
}

#[tokio::test]
async fn test_validation_stage_execute_without_tracing() {
    let stage = ValidationStage::new(false, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), PathBuf::from("/tmp/output"));

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.metadata.get("validation_completed"), Some(&serde_json::json!(true)));
}

// ============================================================================
// EDGE CASE TESTS
// ============================================================================

#[test]
fn test_pipeline_context_clone() {
    let mut ctx1 = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));
    ctx1.optimizations.push("test".to_string());

    let ctx2 = ctx1.clone();
    assert_eq!(ctx1.input_path, ctx2.input_path);
    assert_eq!(ctx1.output_path, ctx2.output_path);
    assert_eq!(ctx1.optimizations.len(), ctx2.optimizations.len());
}

#[test]
fn test_validation_result_clone() {
    let result1 = ValidationResult {
        stage: "Test".to_string(),
        passed: true,
        message: "OK".to_string(),
        details: None,
    };

    let result2 = result1.clone();
    assert_eq!(result1.stage, result2.stage);
    assert_eq!(result1.passed, result2.passed);
}

#[test]
fn test_pipeline_output_clone() {
    let output1 = PipelineOutput {
        output_path: PathBuf::from("/out"),
        file_mappings: vec![],
        optimizations: vec!["opt".to_string()],
        validation_passed: true,
    };

    let output2 = output1.clone();
    assert_eq!(output1.output_path, output2.output_path);
    assert_eq!(output1.validation_passed, output2.validation_passed);
}

#[test]
fn test_optimization_stage_no_gpu_no_simd() {
    let stage = OptimizationStage::new(false, false, 500);
    let recommendations = stage.analyze_optimizations();

    // Should still return MoE recommendations even without GPU/SIMD
    assert!(!recommendations.is_empty());
}

// ============================================================================
// ADDITIONAL COVERAGE TESTS
// ============================================================================

#[test]
fn test_pipeline_context_output_method_extended() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    // Add some data
    ctx.file_mappings.push((PathBuf::from("a.py"), PathBuf::from("a.rs")));
    ctx.optimizations.push("simd".to_string());
    ctx.validation_results.push(ValidationResult {
        stage: "test".to_string(),
        passed: true,
        message: "ok".to_string(),
        details: None,
    });

    let output = ctx.output();
    assert_eq!(output.output_path, PathBuf::from("/output"));
    assert_eq!(output.file_mappings.len(), 1);
    assert!(output.validation_passed);
}

#[test]
fn test_pipeline_context_output_fails_validation_extended() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    ctx.validation_results.push(ValidationResult {
        stage: "test".to_string(),
        passed: false,
        message: "failed".to_string(),
        details: None,
    });

    let output = ctx.output();
    assert!(!output.validation_passed);
}

#[test]
fn test_transpilation_stage_library_analyzer_initialized() {
    let stage = TranspilationStage::new(true, true);
    // Library analyzer is initialized on construction
    let _ = &stage.library_analyzer;
}

#[test]
fn test_optimization_stage_with_different_simd_thresholds_ext() {
    let stage_low = OptimizationStage::new(false, true, 100);
    let stage_high = OptimizationStage::new(false, true, 10000);

    let recs_low = stage_low.analyze_optimizations();
    let recs_high = stage_high.analyze_optimizations();

    // Both should have recommendations but may differ
    assert!(!recs_low.is_empty());
    assert!(!recs_high.is_empty());
}

#[test]
fn test_transpilation_stage_validate_ext() {
    let stage = TranspilationStage::new(true, true);
    let mut ctx = PipelineContext::new(PathBuf::from("/tmp"), PathBuf::from("/tmp/out"));

    // Without output files, validation result exists
    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    // With file mappings
    ctx.file_mappings.push((PathBuf::from("a.py"), PathBuf::from("a.rs")));
    let result = stage.validate(&ctx);
    assert!(result.is_ok());
}

// ============================================================================
// Additional Coverage Tests
// ============================================================================

#[test]
fn test_pipeline_context_empty_metadata() {
    let ctx = PipelineContext::new(PathBuf::from("/in"), PathBuf::from("/out"));
    assert!(ctx.metadata.is_empty());
    assert!(ctx.file_mappings.is_empty());
    assert!(ctx.optimizations.is_empty());
    assert!(ctx.validation_results.is_empty());
}

#[test]
fn test_pipeline_context_complex_metadata() {
    let mut ctx = PipelineContext::new(PathBuf::from("/in"), PathBuf::from("/out"));

    ctx.metadata.insert("array".to_string(), serde_json::json!([1, 2, 3]));
    ctx.metadata.insert("nested".to_string(), serde_json::json!({"a": {"b": "c"}}));
    ctx.metadata.insert("null".to_string(), serde_json::Value::Null);
    ctx.metadata.insert("bool".to_string(), serde_json::json!(true));

    assert_eq!(ctx.metadata.len(), 4);
}

#[test]
fn test_validation_result_default_details() {
    let result = ValidationResult {
        stage: "Test".to_string(),
        passed: true,
        message: "OK".to_string(),
        details: None,
    };

    assert!(result.details.is_none());
    assert!(result.passed);
}

#[test]
fn test_pipeline_output_all_fields() {
    let output = PipelineOutput {
        output_path: PathBuf::from("/output"),
        file_mappings: vec![
            (PathBuf::from("a.py"), PathBuf::from("a.rs")),
            (PathBuf::from("b.py"), PathBuf::from("b.rs")),
        ],
        optimizations: vec!["opt1".to_string(), "opt2".to_string()],
        validation_passed: true,
    };

    assert_eq!(output.file_mappings.len(), 2);
    assert_eq!(output.optimizations.len(), 2);
    assert!(output.validation_passed);
}

#[test]
fn test_analysis_stage_name_immutable() {
    let stage = AnalysisStage;
    let name1 = stage.name();
    let name2 = stage.name();
    assert_eq!(name1, name2);
}

#[test]
fn test_validation_stage_empty_traces() {
    let _stage = ValidationStage::new(true, true);
    let trace1: Vec<String> = vec![];
    let trace2: Vec<String> = vec![];

    // Empty traces should match
    assert!(ValidationStage::compare_traces(&trace1, &trace2));
}

#[test]
fn test_optimization_stage_edge_cases() {
    // Test with zero threshold
    let stage = OptimizationStage::new(true, true, 0);
    let recommendations = stage.analyze_optimizations();
    assert!(!recommendations.is_empty());

    // Test with very high threshold
    let stage_high = OptimizationStage::new(true, true, 10_000_000);
    let rec_high = stage_high.analyze_optimizations();
    assert!(!rec_high.is_empty());
}

#[test]
fn test_build_stage_all_configurations() {
    // Debug, no target, no WASM
    let stage1 = BuildStage::new(false, None, false);
    assert!(!stage1.release);
    assert!(stage1.target.is_none());
    assert!(!stage1.wasm);

    // Release, with target, no WASM
    let stage2 = BuildStage::new(true, Some("aarch64-apple-darwin".to_string()), false);
    assert!(stage2.release);
    assert!(stage2.target.is_some());

    // Debug, no target, WASM
    let stage3 = BuildStage::new(false, None, true);
    assert!(stage3.wasm);
}

#[test]
fn test_transpilation_stage_no_cache() {
    let stage = TranspilationStage::new(false, false);
    assert!(!stage.incremental);
    assert!(!stage.cache);
}

#[test]
fn test_validation_stage_no_tracing() {
    let stage = ValidationStage::new(false, false);
    assert!(!stage.trace_syscalls);
    assert!(!stage.run_tests);
}

// ============================================================================
// ADDITIONAL COVERAGE TESTS - UNIQUE ONLY
// ============================================================================

#[test]
fn test_trace_binary_nonexistent_cov() {
    let result = ValidationStage::trace_binary(Path::new("/nonexistent/binary"));
    // May error if renacer isn't available
    let _ = result;
}

// ============================================================================
// COVERAGE GAP TESTS - execution.rs
// ============================================================================

/// Test pipeline with StopOnError validation where ALL stages pass validation.
/// This covers the branch in run() where validation_result.passed is true
/// and the bail is NOT taken (line 69 false branch).
#[tokio::test]
async fn test_pipeline_stop_on_error_all_pass() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2")))
        .add_stage(Box::new(MockStage::new("Stage3")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    let pipeline_output = result.unwrap();
    // All 3 validations passed
    assert!(pipeline_output.validation_passed);
}

/// Test pipeline with ContinueOnError where ALL stages pass validation.
/// Exercises the non-None validation path with no failures.
#[tokio::test]
async fn test_pipeline_continue_on_error_all_pass() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::ContinueOnError)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    let pipeline_output = result.unwrap();
    assert!(pipeline_output.validation_passed);
}

/// Test pipeline with ContinueOnError where execution fails (not validation).
/// This exercises the stage.execute() error path with ContinueOnError strategy.
#[tokio::test]
async fn test_pipeline_continue_on_error_execution_failure() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::ContinueOnError)
        .add_stage(Box::new(MockStage::new("Stage1")))
        .add_stage(Box::new(MockStage::new("Stage2").with_execution_failure()));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    // Execution failure is always fatal regardless of validation strategy
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("Stage 'Stage2' failed"));
}

/// Test pipeline where first stage fails execution (stops immediately).
#[tokio::test]
async fn test_pipeline_first_stage_execution_failure() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError)
        .add_stage(Box::new(MockStage::new("Stage1").with_execution_failure()))
        .add_stage(Box::new(MockStage::new("Stage2")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("Stage 'Stage1' failed"));
}

// ============================================================================
// COVERAGE GAP TESTS - build.rs (execute method)
// ============================================================================

/// Test BuildStage execute fails when no Cargo.toml exists.
/// This covers the bail at line 45 in build.rs.
#[tokio::test]
async fn test_build_stage_execute_no_cargo_toml() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let stage = BuildStage::new(false, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), temp_dir.path().to_path_buf());

    let result = stage.execute(ctx).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("No Cargo.toml found"));
}

/// Test BuildStage execute with a real minimal Cargo.toml (debug build).
/// This covers the happy path of execute including metadata insertion.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_build_stage_execute_debug_build() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let project_dir = temp_dir.path().join("project");
    std::fs::create_dir_all(project_dir.join("src")).unwrap();
    std::fs::write(
        project_dir.join("Cargo.toml"),
        r#"[package]
name = "test-build"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    std::fs::write(project_dir.join("src/main.rs"), "fn main() {}\n").unwrap();

    let stage = BuildStage::new(false, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), project_dir.clone());

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.metadata.get("build_mode"), Some(&serde_json::json!("debug")));
    // No wasm_build metadata when wasm is false
    assert!(!ctx.metadata.contains_key("wasm_build"));
}

/// Test BuildStage execute with release mode.
/// Covers the release arg push at line 52.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_build_stage_execute_release_build() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let project_dir = temp_dir.path().join("project");
    std::fs::create_dir_all(project_dir.join("src")).unwrap();
    std::fs::write(
        project_dir.join("Cargo.toml"),
        r#"[package]
name = "test-build"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    std::fs::write(project_dir.join("src/main.rs"), "fn main() {}\n").unwrap();

    let stage = BuildStage::new(true, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), project_dir.clone());

    let result = stage.execute(ctx).await;
    assert!(result.is_ok());

    let ctx = result.unwrap();
    assert_eq!(ctx.metadata.get("build_mode"), Some(&serde_json::json!("release")));
}

/// Test BuildStage execute with custom target.
/// Covers the target arg push at lines 56-57.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_build_stage_execute_with_target() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let project_dir = temp_dir.path().join("project");
    std::fs::create_dir_all(project_dir.join("src")).unwrap();
    std::fs::write(
        project_dir.join("Cargo.toml"),
        r#"[package]
name = "test-build"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    std::fs::write(project_dir.join("src/main.rs"), "fn main() {}\n").unwrap();

    // Use the native target so compilation should succeed
    let stage = BuildStage::new(false, Some("x86_64-unknown-linux-gnu".to_string()), false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), project_dir.clone());

    let result = stage.execute(ctx).await;
    // Should succeed (compiling for the same architecture we're on)
    assert!(result.is_ok());
}

/// Test BuildStage validate with release=false when build dir doesn't exist.
#[test]
fn test_build_stage_validate_debug_no_dir() {
    let stage = BuildStage::new(false, None, false);
    let ctx = PipelineContext::new(
        PathBuf::from("/tmp/input"),
        PathBuf::from("/tmp/nonexistent_dir_for_test"),
    );

    let result = stage.validate(&ctx);
    assert!(result.is_ok());
    let validation = result.unwrap();
    assert!(!validation.passed);
    assert_eq!(validation.message, "Build directory not found");
}

/// Test BuildStage validate passing case for release=true.
#[test]
fn test_build_stage_validate_release_passing() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    std::fs::create_dir_all(temp_dir.path().join("target/release")).unwrap();

    let stage = BuildStage::new(true, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), temp_dir.path().to_path_buf());

    let result = stage.validate(&ctx);
    assert!(result.is_ok());
    let validation = result.unwrap();
    assert!(validation.passed);
    assert_eq!(validation.message, "Build artifacts found");
}

// ============================================================================
// COVERAGE GAP TESTS - types.rs (default validate method)
// ============================================================================

/// A stage that does NOT override validate(), so the default impl is used.
/// This covers lines 95-103 in types.rs.
struct DefaultValidateStage;

#[async_trait::async_trait]
impl PipelineStage for DefaultValidateStage {
    fn name(&self) -> &str {
        "DefaultValidate"
    }

    async fn execute(&self, ctx: PipelineContext) -> anyhow::Result<PipelineContext> {
        Ok(ctx)
    }
    // NOTE: validate() is NOT overridden, so the default impl is used
}

#[test]
fn test_default_validate_method() {
    let stage = DefaultValidateStage;
    let ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));

    let result = stage.validate(&ctx);
    assert!(result.is_ok());

    let validation = result.unwrap();
    assert_eq!(validation.stage, "DefaultValidate");
    assert!(validation.passed);
    assert_eq!(validation.message, "No validation configured");
    assert!(validation.details.is_none());
}

/// Test pipeline run with a stage using default validate (non-None strategy).
/// This exercises the default validate method through the pipeline run path.
#[tokio::test]
async fn test_pipeline_run_with_default_validate_stage() {
    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError)
        .add_stage(Box::new(DefaultValidateStage));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    let pipeline_output = result.unwrap();
    assert!(pipeline_output.validation_passed);
}

// ============================================================================
// COVERAGE GAP TESTS - PipelineContext Debug + Clone coverage
// ============================================================================

#[test]
fn test_pipeline_context_debug_format() {
    let ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));
    let debug_str = format!("{:?}", ctx);
    assert!(debug_str.contains("PipelineContext"));
    assert!(debug_str.contains("/input"));
    assert!(debug_str.contains("/output"));
}

#[test]
fn test_validation_result_debug_format() {
    let result = ValidationResult {
        stage: "TestStage".to_string(),
        passed: true,
        message: "OK".to_string(),
        details: None,
    };
    let debug_str = format!("{:?}", result);
    assert!(debug_str.contains("ValidationResult"));
    assert!(debug_str.contains("TestStage"));
}

#[test]
fn test_pipeline_output_debug_format() {
    let output = PipelineOutput {
        output_path: PathBuf::from("/out"),
        file_mappings: vec![],
        optimizations: vec![],
        validation_passed: false,
    };
    let debug_str = format!("{:?}", output);
    assert!(debug_str.contains("PipelineOutput"));
    assert!(debug_str.contains("false"));
}

#[test]
fn test_validation_strategy_debug_format() {
    let strategy = ValidationStrategy::StopOnError;
    let debug_str = format!("{:?}", strategy);
    assert_eq!(debug_str, "StopOnError");

    let strategy2 = ValidationStrategy::ContinueOnError;
    let debug_str2 = format!("{:?}", strategy2);
    assert_eq!(debug_str2, "ContinueOnError");

    let strategy3 = ValidationStrategy::None;
    let debug_str3 = format!("{:?}", strategy3);
    assert_eq!(debug_str3, "None");
}

#[test]
fn test_validation_strategy_copy_semantics() {
    let s1 = ValidationStrategy::StopOnError;
    let s2 = s1; // Copy
    assert_eq!(s1, s2); // s1 still usable after copy
}

#[test]
fn test_pipeline_context_with_all_fields_populated() {
    let mut ctx = PipelineContext::new(PathBuf::from("/input"), PathBuf::from("/output"));
    ctx.primary_language = Some(crate::types::Language::Python);
    ctx.file_mappings.push((PathBuf::from("a.py"), PathBuf::from("a.rs")));
    ctx.file_mappings.push((PathBuf::from("b.py"), PathBuf::from("b.rs")));
    ctx.optimizations.push("simd".to_string());
    ctx.optimizations.push("gpu".to_string());
    ctx.validation_results.push(ValidationResult {
        stage: "s1".to_string(),
        passed: true,
        message: "ok".to_string(),
        details: Some(serde_json::json!({"info": "details"})),
    });
    ctx.metadata.insert("key1".to_string(), serde_json::json!("val1"));

    let output = ctx.output();
    assert_eq!(output.file_mappings.len(), 2);
    assert_eq!(output.optimizations.len(), 2);
    assert!(output.validation_passed);
}

/// Test BuildStage execute with broken source code (cargo build fails).
/// Covers the cargo build failure path at lines 73-75 in build.rs.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_build_stage_execute_cargo_build_fails() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let project_dir = temp_dir.path().join("project");
    std::fs::create_dir_all(project_dir.join("src")).unwrap();
    std::fs::write(
        project_dir.join("Cargo.toml"),
        r#"[package]
name = "broken-build"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    // Invalid Rust source to cause build failure
    std::fs::write(project_dir.join("src/main.rs"), "fn main() { this is not valid rust }")
        .unwrap();

    let stage = BuildStage::new(false, None, false);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), project_dir.clone());

    let result = stage.execute(ctx).await;
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(err.to_string().contains("Cargo build failed"));
}

/// Test BuildStage with wasm=true to cover wasm metadata insertion (lines 83-86).
/// Note: This test uses a real project with wasm target which may not be installed.
/// The build may fail, but we test the wasm arg construction path.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_build_stage_execute_wasm_flag() {
    use tempfile::TempDir;

    let temp_dir = TempDir::new().unwrap();
    let project_dir = temp_dir.path().join("project");
    std::fs::create_dir_all(project_dir.join("src")).unwrap();
    std::fs::write(
        project_dir.join("Cargo.toml"),
        r#"[package]
name = "wasm-test"
version = "0.1.0"
edition = "2021"
"#,
    )
    .unwrap();
    std::fs::write(project_dir.join("src/lib.rs"), "pub fn hello() {}\n").unwrap();

    let stage = BuildStage::new(false, None, true);
    let ctx = PipelineContext::new(PathBuf::from("/tmp/input"), project_dir.clone());

    let result = stage.execute(ctx).await;
    // WASM target may or may not be installed; if it succeeds, check metadata
    if let Ok(ctx) = result {
        assert_eq!(ctx.metadata.get("build_mode"), Some(&serde_json::json!("debug")));
        assert_eq!(ctx.metadata.get("wasm_build"), Some(&serde_json::json!(true)));
    }
    // If it fails due to missing wasm target, that's acceptable
}

// ============================================================================
// COVERAGE GAP TESTS - execution.rs info!() macro line coverage
// ============================================================================

/// Test pipeline run with a tracing subscriber installed to force evaluation
/// of the info!() format arguments in execution.rs lines 50-55.
/// Without a subscriber, tracing macros may short-circuit and skip formatting.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_pipeline_run_with_tracing_subscriber() {
    use tracing_subscriber::fmt;
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::util::SubscriberInitExt;

    // Create a subscriber that captures all output (sink it to avoid test noise)
    let subscriber = tracing_subscriber::registry().with(fmt::layer().with_writer(std::io::sink));

    // Use a guard so the subscriber is only active for this test
    let _guard = subscriber.set_default();

    let pipeline = TranspilationPipeline::new(ValidationStrategy::StopOnError)
        .add_stage(Box::new(MockStage::new("Analysis")))
        .add_stage(Box::new(MockStage::new("Build")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());

    let pipeline_output = result.unwrap();
    assert!(pipeline_output.validation_passed);
}

/// Test pipeline with ContinueOnError and tracing to hit the debug!() line at 65.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_pipeline_run_continue_on_error_with_tracing() {
    use tracing_subscriber::fmt;
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::util::SubscriberInitExt;

    let subscriber = tracing_subscriber::registry().with(fmt::layer().with_writer(std::io::sink));
    let _guard = subscriber.set_default();

    let pipeline = TranspilationPipeline::new(ValidationStrategy::ContinueOnError)
        .add_stage(Box::new(MockStage::new("Stage1").with_validation_failure()))
        .add_stage(Box::new(MockStage::new("Stage2")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());
    assert!(!result.unwrap().validation_passed);
}

/// Test pipeline single stage with tracing for info!() format arg coverage.
#[cfg(feature = "native")]
#[tokio::test]
async fn test_pipeline_single_stage_with_tracing() {
    use tracing_subscriber::fmt;
    use tracing_subscriber::layer::SubscriberExt;
    use tracing_subscriber::util::SubscriberInitExt;

    let subscriber = tracing_subscriber::registry().with(fmt::layer().with_writer(std::io::sink));
    let _guard = subscriber.set_default();

    let pipeline = TranspilationPipeline::new(ValidationStrategy::None)
        .add_stage(Box::new(MockStage::new("OnlyStage")));

    let input = PathBuf::from("/tmp/input");
    let output = PathBuf::from("/tmp/output");

    let result = pipeline.run(&input, &output).await;
    assert!(result.is_ok());
}