aprender-simulate 0.30.0

Unified Simulation Engine for the Sovereign AI Stack
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
//! Report generation for EDD experiments.
//!
//! This module provides functionality to generate various report formats
//! from experiment results:
//! - Markdown reports
//! - JSON reports
//! - HTML reports (planned)
//!
//! # Report Contents
//!
//! Generated reports include:
//! - Experiment metadata
//! - Verification test results
//! - Falsification criteria results
//! - Reproducibility verification
//! - Execution metrics
//!
//! # Example
//!
//! ```ignore
//! let result = runner.run("experiment.yaml")?;
//! let report = ReportGenerator::markdown(&result)?;
//! std::fs::write("report.md", report)?;
//! ```

use super::runner::{
    EmcComplianceReport, ExecutionMetrics, ExperimentResult, FalsificationSummary,
    ReproducibilitySummary, VerificationSummary,
};
use std::fmt::Write;

/// Report format options.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReportFormat {
    /// Markdown format
    Markdown,
    /// JSON format
    Json,
    /// Plain text format
    Text,
}

/// Report generator for experiment results.
pub struct ReportGenerator;

impl ReportGenerator {
    /// Generate a markdown report from experiment results.
    ///
    /// # Errors
    /// Returns error if formatting fails.
    pub fn markdown(result: &ExperimentResult) -> Result<String, String> {
        let mut report = String::new();

        // Header
        writeln!(report, "# Experiment Report: {}", result.name).map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        // Metadata
        writeln!(report, "## Metadata").map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;
        writeln!(report, "| Field | Value |").map_err(|e| e.to_string())?;
        writeln!(report, "|-------|-------|").map_err(|e| e.to_string())?;
        writeln!(report, "| Experiment ID | {} |", result.experiment_id)
            .map_err(|e| e.to_string())?;
        writeln!(report, "| Seed | {} |", result.seed).map_err(|e| e.to_string())?;
        writeln!(
            report,
            "| Status | {} |",
            if result.passed { "PASSED" } else { "FAILED" }
        )
        .map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        // Verification Tests
        writeln!(report, "## Verification Tests").map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;
        Self::write_verification_summary(&mut report, &result.verification)?;

        // Falsification Criteria
        writeln!(report, "## Falsification Criteria").map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;
        Self::write_falsification_summary(&mut report, &result.falsification)?;

        // Reproducibility
        if let Some(ref repro) = result.reproducibility {
            writeln!(report, "## Reproducibility").map_err(|e| e.to_string())?;
            writeln!(report).map_err(|e| e.to_string())?;
            Self::write_reproducibility_summary(&mut report, repro)?;
        }

        // Execution Metrics
        writeln!(report, "## Execution Metrics").map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;
        Self::write_execution_metrics(&mut report, &result.execution)?;

        // Warnings
        if !result.warnings.is_empty() {
            writeln!(report, "## Warnings").map_err(|e| e.to_string())?;
            writeln!(report).map_err(|e| e.to_string())?;
            for warning in &result.warnings {
                writeln!(report, "- {warning}").map_err(|e| e.to_string())?;
            }
            writeln!(report).map_err(|e| e.to_string())?;
        }

        // Footer
        writeln!(report, "---").map_err(|e| e.to_string())?;
        writeln!(
            report,
            "*Generated by simular v{}*",
            env!("CARGO_PKG_VERSION")
        )
        .map_err(|e| e.to_string())?;

        Ok(report)
    }

    fn write_verification_summary(
        report: &mut String,
        summary: &VerificationSummary,
    ) -> Result<(), String> {
        writeln!(
            report,
            "**Summary:** {} passed, {} failed out of {} total",
            summary.passed, summary.failed, summary.total
        )
        .map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        if !summary.tests.is_empty() {
            writeln!(
                report,
                "| ID | Name | Status | Expected | Actual | Tolerance |"
            )
            .map_err(|e| e.to_string())?;
            writeln!(report, "|---|---|---|---|---|---|").map_err(|e| e.to_string())?;

            for test in &summary.tests {
                let status = if test.passed { "PASS" } else { "FAIL" };
                let expected = test
                    .expected
                    .map_or_else(|| "-".to_string(), |v| format!("{v:.6}"));
                let actual = test
                    .actual
                    .map_or_else(|| "-".to_string(), |v| format!("{v:.6}"));
                let tolerance = test
                    .tolerance
                    .map_or_else(|| "-".to_string(), |v| format!("{v:.2e}"));

                writeln!(
                    report,
                    "| {} | {} | {} | {} | {} | {} |",
                    test.id, test.name, status, expected, actual, tolerance
                )
                .map_err(|e| e.to_string())?;
            }
            writeln!(report).map_err(|e| e.to_string())?;
        }

        Ok(())
    }

    fn write_falsification_summary(
        report: &mut String,
        summary: &FalsificationSummary,
    ) -> Result<(), String> {
        writeln!(
            report,
            "**Summary:** {} passed, {} triggered out of {} total",
            summary.passed, summary.triggered, summary.total
        )
        .map_err(|e| e.to_string())?;

        if summary.jidoka_triggered {
            writeln!(report, "\n**Jidoka:** TRIGGERED (stop-on-error)")
                .map_err(|e| e.to_string())?;
        }
        writeln!(report).map_err(|e| e.to_string())?;

        if !summary.criteria.is_empty() {
            writeln!(report, "| ID | Name | Triggered | Severity | Condition |")
                .map_err(|e| e.to_string())?;
            writeln!(report, "|---|---|---|---|---|").map_err(|e| e.to_string())?;

            for crit in &summary.criteria {
                let triggered = if crit.triggered { "YES" } else { "NO" };
                writeln!(
                    report,
                    "| {} | {} | {} | {} | {} |",
                    crit.id, crit.name, triggered, crit.severity, crit.condition
                )
                .map_err(|e| e.to_string())?;
            }
            writeln!(report).map_err(|e| e.to_string())?;
        }

        Ok(())
    }

    fn write_reproducibility_summary(
        report: &mut String,
        summary: &ReproducibilitySummary,
    ) -> Result<(), String> {
        writeln!(report, "| Property | Value |").map_err(|e| e.to_string())?;
        writeln!(report, "|---|---|").map_err(|e| e.to_string())?;
        writeln!(
            report,
            "| Passed | {} |",
            if summary.passed { "YES" } else { "NO" }
        )
        .map_err(|e| e.to_string())?;
        writeln!(report, "| Runs | {} |", summary.runs).map_err(|e| e.to_string())?;
        writeln!(report, "| Identical | {} |", summary.identical).map_err(|e| e.to_string())?;
        writeln!(report, "| Platform | {} |", summary.platform).map_err(|e| e.to_string())?;
        writeln!(report, "| Reference Hash | `{}` |", summary.reference_hash)
            .map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        Ok(())
    }

    fn write_execution_metrics(
        report: &mut String,
        metrics: &ExecutionMetrics,
    ) -> Result<(), String> {
        writeln!(report, "| Metric | Value |").map_err(|e| e.to_string())?;
        writeln!(report, "|---|---|").map_err(|e| e.to_string())?;
        writeln!(report, "| Duration | {} ms |", metrics.duration_ms).map_err(|e| e.to_string())?;
        writeln!(report, "| Steps | {} |", metrics.steps).map_err(|e| e.to_string())?;
        writeln!(report, "| Replications | {} |", metrics.replications)
            .map_err(|e| e.to_string())?;

        if let Some(mem) = metrics.peak_memory_bytes {
            writeln!(report, "| Peak Memory | {mem} bytes |").map_err(|e| e.to_string())?;
        }
        writeln!(report).map_err(|e| e.to_string())?;

        Ok(())
    }

    /// Generate a JSON report from experiment results.
    ///
    /// # Errors
    /// Returns error if serialization fails.
    pub fn json(result: &ExperimentResult) -> Result<String, String> {
        serde_json::to_string_pretty(result)
            .map_err(|e| format!("Failed to serialize to JSON: {e}"))
    }

    /// Generate a plain text report from experiment results.
    ///
    /// # Errors
    /// Returns error if formatting fails.
    pub fn text(result: &ExperimentResult) -> Result<String, String> {
        let mut report = String::new();

        let status = if result.passed { "PASSED" } else { "FAILED" };
        writeln!(report, "EXPERIMENT REPORT: {}", result.name).map_err(|e| e.to_string())?;
        writeln!(
            report,
            "================================================================================"
        )
        .map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;
        writeln!(report, "ID:     {}", result.experiment_id).map_err(|e| e.to_string())?;
        writeln!(report, "Seed:   {}", result.seed).map_err(|e| e.to_string())?;
        writeln!(report, "Status: {status}").map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        writeln!(report, "VERIFICATION TESTS").map_err(|e| e.to_string())?;
        writeln!(
            report,
            "--------------------------------------------------------------------------------"
        )
        .map_err(|e| e.to_string())?;
        writeln!(report, "Total:  {}", result.verification.total).map_err(|e| e.to_string())?;
        writeln!(report, "Passed: {}", result.verification.passed).map_err(|e| e.to_string())?;
        writeln!(report, "Failed: {}", result.verification.failed).map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        writeln!(report, "FALSIFICATION CRITERIA").map_err(|e| e.to_string())?;
        writeln!(
            report,
            "--------------------------------------------------------------------------------"
        )
        .map_err(|e| e.to_string())?;
        writeln!(report, "Total:     {}", result.falsification.total).map_err(|e| e.to_string())?;
        writeln!(report, "Passed:    {}", result.falsification.passed)
            .map_err(|e| e.to_string())?;
        writeln!(report, "Triggered: {}", result.falsification.triggered)
            .map_err(|e| e.to_string())?;
        writeln!(
            report,
            "Jidoka:    {}",
            if result.falsification.jidoka_triggered {
                "TRIGGERED"
            } else {
                "OK"
            }
        )
        .map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        writeln!(report, "EXECUTION").map_err(|e| e.to_string())?;
        writeln!(
            report,
            "--------------------------------------------------------------------------------"
        )
        .map_err(|e| e.to_string())?;
        writeln!(report, "Duration:     {} ms", result.execution.duration_ms)
            .map_err(|e| e.to_string())?;
        writeln!(report, "Replications: {}", result.execution.replications)
            .map_err(|e| e.to_string())?;
        writeln!(report).map_err(|e| e.to_string())?;

        writeln!(
            report,
            "================================================================================"
        )
        .map_err(|e| e.to_string())?;
        writeln!(report, "RESULT: {status}").map_err(|e| e.to_string())?;

        Ok(report)
    }

    /// Generate a markdown report for EMC compliance.
    ///
    /// # Errors
    /// Returns error if formatting fails.
    pub fn emc_compliance_markdown(report: &EmcComplianceReport) -> Result<String, String> {
        let mut output = String::new();

        writeln!(
            output,
            "# EMC Compliance Report: {}",
            report.experiment_name
        )
        .map_err(|e| e.to_string())?;
        writeln!(output).map_err(|e| e.to_string())?;

        let status = if report.passed {
            "COMPLIANT"
        } else {
            "NON-COMPLIANT"
        };
        writeln!(output, "**Status:** {status}").map_err(|e| e.to_string())?;
        writeln!(output).map_err(|e| e.to_string())?;

        // EDD Compliance Checklist
        writeln!(output, "## EDD Compliance Checklist").map_err(|e| e.to_string())?;
        writeln!(output).map_err(|e| e.to_string())?;
        writeln!(output, "| Requirement | Status |").map_err(|e| e.to_string())?;
        writeln!(output, "|---|---|").map_err(|e| e.to_string())?;

        let check = |b: bool| if b { "PASS" } else { "FAIL" };
        writeln!(
            output,
            "| EDD-01: EMC Reference | {} |",
            check(report.edd_compliance.edd_01_emc_reference)
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            output,
            "| EDD-02: Verification Tests | {} |",
            check(report.edd_compliance.edd_02_verification_tests)
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            output,
            "| EDD-03: Seed Specified | {} |",
            check(report.edd_compliance.edd_03_seed_specified)
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            output,
            "| EDD-04: Falsification Criteria | {} |",
            check(report.edd_compliance.edd_04_falsification_criteria)
        )
        .map_err(|e| e.to_string())?;
        writeln!(
            output,
            "| EDD-05: Hypothesis (Optional) | {} |",
            check(report.edd_compliance.edd_05_hypothesis)
        )
        .map_err(|e| e.to_string())?;
        writeln!(output).map_err(|e| e.to_string())?;

        // Errors
        if !report.schema_errors.is_empty() || !report.emc_errors.is_empty() {
            writeln!(output, "## Errors").map_err(|e| e.to_string())?;
            writeln!(output).map_err(|e| e.to_string())?;

            for err in &report.schema_errors {
                writeln!(output, "- Schema: {err}").map_err(|e| e.to_string())?;
            }
            for err in &report.emc_errors {
                writeln!(output, "- EMC: {err}").map_err(|e| e.to_string())?;
            }
            writeln!(output).map_err(|e| e.to_string())?;
        }

        // Warnings
        if !report.warnings.is_empty() {
            writeln!(output, "## Warnings").map_err(|e| e.to_string())?;
            writeln!(output).map_err(|e| e.to_string())?;
            for warning in &report.warnings {
                writeln!(output, "- {warning}").map_err(|e| e.to_string())?;
            }
            writeln!(output).map_err(|e| e.to_string())?;
        }

        // Footer
        writeln!(output, "---").map_err(|e| e.to_string())?;
        writeln!(
            output,
            "*Generated by simular v{}*",
            env!("CARGO_PKG_VERSION")
        )
        .map_err(|e| e.to_string())?;

        Ok(output)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::edd::runner::{
        EddComplianceChecklist, FalsificationCriterionResult, VerificationTestSummary,
    };

    fn sample_result() -> ExperimentResult {
        ExperimentResult {
            name: "Test Experiment".to_string(),
            experiment_id: "EXP-001".to_string(),
            seed: 42,
            passed: true,
            verification: VerificationSummary {
                total: 2,
                passed: 2,
                failed: 0,
                tests: vec![VerificationTestSummary {
                    id: "VT-001".to_string(),
                    name: "Basic test".to_string(),
                    passed: true,
                    expected: Some(10.0),
                    actual: Some(10.0),
                    tolerance: Some(0.001),
                    error: None,
                }],
            },
            falsification: FalsificationSummary {
                total: 1,
                passed: 1,
                triggered: 0,
                jidoka_triggered: false,
                criteria: vec![FalsificationCriterionResult {
                    id: "FC-001".to_string(),
                    name: "Error bound".to_string(),
                    triggered: false,
                    condition: "error < 0.01".to_string(),
                    severity: "critical".to_string(),
                    value: None,
                    threshold: Some(0.01),
                }],
            },
            reproducibility: Some(ReproducibilitySummary {
                passed: true,
                runs: 3,
                identical: true,
                reference_hash: "abc123".to_string(),
                run_hashes: vec!["abc123".to_string(); 3],
                platform: "x86_64".to_string(),
            }),
            execution: ExecutionMetrics {
                duration_ms: 100,
                steps: 1000,
                replications: 30,
                peak_memory_bytes: Some(1024 * 1024),
            },
            artifacts: Vec::new(),
            warnings: vec!["Test warning".to_string()],
        }
    }

    #[test]
    fn test_markdown_report() {
        let result = sample_result();
        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.expect("markdown generation should succeed");
        assert!(report.contains("# Experiment Report: Test Experiment"));
        assert!(report.contains("PASSED"));
        assert!(report.contains("42"));
        assert!(report.contains("VT-001"));
    }

    #[test]
    fn test_json_report() {
        let result = sample_result();
        let report = ReportGenerator::json(&result);
        assert!(report.is_ok());
        let report = report.expect("json generation should succeed");
        assert!(report.contains("\"name\": \"Test Experiment\""));
        assert!(report.contains("\"seed\": 42"));
    }

    #[test]
    fn test_text_report() {
        let result = sample_result();
        let report = ReportGenerator::text(&result);
        assert!(report.is_ok());
        let report = report.expect("text generation should succeed");
        assert!(report.contains("EXPERIMENT REPORT: Test Experiment"));
        assert!(report.contains("RESULT: PASSED"));
    }

    #[test]
    fn test_emc_compliance_markdown() {
        let report = EmcComplianceReport {
            experiment_name: "Test".to_string(),
            passed: true,
            schema_errors: Vec::new(),
            emc_errors: Vec::new(),
            warnings: Vec::new(),
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: true,
                edd_02_verification_tests: true,
                edd_03_seed_specified: true,
                edd_04_falsification_criteria: true,
                edd_05_hypothesis: true,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.expect("compliance markdown should succeed");
        assert!(output.contains("COMPLIANT"));
        assert!(output.contains("EDD-01"));
    }

    #[test]
    fn test_failed_report() {
        let mut result = sample_result();
        result.passed = false;
        result.verification.failed = 1;
        result.verification.passed = 1;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.expect("markdown for failed result should succeed");
        assert!(report.contains("FAILED"));
    }

    #[test]
    fn test_report_format_enum() {
        let markdown = ReportFormat::Markdown;
        let json = ReportFormat::Json;
        let text = ReportFormat::Text;

        assert_eq!(markdown, ReportFormat::Markdown);
        assert_ne!(json, ReportFormat::Markdown);
        assert_ne!(text, ReportFormat::Json);
    }

    #[test]
    fn test_markdown_report_no_reproducibility() {
        let mut result = sample_result();
        result.reproducibility = None;
        result.warnings.clear();

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        // Should not contain Reproducibility section
        assert!(!report.contains("## Reproducibility"));
        // Should not contain Warnings section
        assert!(!report.contains("## Warnings"));
    }

    #[test]
    fn test_markdown_report_with_memory() {
        let result = sample_result();
        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        // Should contain memory info
        assert!(report.contains("1048576")); // 1024*1024
    }

    #[test]
    fn test_text_report_with_jidoka() {
        let mut result = sample_result();
        result.falsification.jidoka_triggered = true;

        let report = ReportGenerator::text(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("TRIGGERED"));
    }

    #[test]
    fn test_markdown_verification_with_no_expected() {
        let mut result = sample_result();
        result.verification.tests = vec![VerificationTestSummary {
            id: "VT-002".to_string(),
            name: "No expected".to_string(),
            passed: true,
            expected: None,
            actual: None,
            tolerance: None,
            error: None,
        }];

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
    }

    #[test]
    fn test_markdown_falsification_with_triggered() {
        let mut result = sample_result();
        result.falsification.criteria[0].triggered = true;
        result.falsification.triggered = 1;
        result.falsification.passed = 0;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("YES"));
    }

    #[test]
    fn test_markdown_jidoka_triggered() {
        let mut result = sample_result();
        result.falsification.jidoka_triggered = true;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("Jidoka"));
        assert!(report.contains("TRIGGERED"));
    }

    #[test]
    fn test_emc_compliance_with_errors() {
        let report = EmcComplianceReport {
            experiment_name: "Error Test".to_string(),
            passed: false,
            schema_errors: vec!["Schema error 1".to_string()],
            emc_errors: vec!["EMC error 1".to_string()],
            warnings: vec!["Warning 1".to_string()],
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: false,
                edd_02_verification_tests: false,
                edd_03_seed_specified: true,
                edd_04_falsification_criteria: false,
                edd_05_hypothesis: false,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.ok().unwrap();
        assert!(output.contains("NON-COMPLIANT"));
        assert!(output.contains("Schema: Schema error 1"));
        assert!(output.contains("EMC: EMC error 1"));
        assert!(output.contains("Warning 1"));
        assert!(output.contains("FAIL"));
    }

    #[test]
    fn test_markdown_execution_no_memory() {
        let mut result = sample_result();
        result.execution.peak_memory_bytes = None;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        // Should not contain Peak Memory line since it's None
        assert!(!report.contains("Peak Memory"));
    }

    #[test]
    fn test_verification_empty_tests() {
        let mut result = sample_result();
        result.verification.tests.clear();
        result.verification.total = 0;
        result.verification.passed = 0;
        result.verification.failed = 0;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("0 passed, 0 failed out of 0 total"));
    }

    #[test]
    fn test_falsification_empty_criteria() {
        let mut result = sample_result();
        result.falsification.criteria.clear();
        result.falsification.total = 0;
        result.falsification.passed = 0;
        result.falsification.triggered = 0;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("0 passed, 0 triggered out of 0 total"));
    }

    #[test]
    fn test_compliance_no_errors_no_warnings() {
        let report = EmcComplianceReport {
            experiment_name: "Clean".to_string(),
            passed: true,
            schema_errors: Vec::new(),
            emc_errors: Vec::new(),
            warnings: Vec::new(),
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: true,
                edd_02_verification_tests: true,
                edd_03_seed_specified: true,
                edd_04_falsification_criteria: true,
                edd_05_hypothesis: true,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.ok().unwrap();
        assert!(output.contains("COMPLIANT"));
        // Should not contain Errors or Warnings sections
        assert!(!output.contains("## Errors"));
        assert!(!output.contains("## Warnings"));
    }

    #[test]
    fn test_report_format_debug() {
        let format = ReportFormat::Markdown;
        let debug_str = format!("{format:?}");
        assert!(debug_str.contains("Markdown"));
    }

    #[test]
    fn test_report_format_clone() {
        let format = ReportFormat::Json;
        let cloned = format;
        assert_eq!(cloned, ReportFormat::Json);
    }

    #[test]
    fn test_report_format_copy() {
        let format = ReportFormat::Text;
        let copied = format;
        assert_eq!(format, copied);
    }

    #[test]
    fn test_text_report_without_jidoka() {
        let result = sample_result();
        let report = ReportGenerator::text(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("Jidoka:    OK"));
    }

    #[test]
    fn test_markdown_report_content_details() {
        let result = sample_result();
        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();

        // Check metadata table
        assert!(report.contains("| Field | Value |"));
        assert!(report.contains("| Experiment ID |"));
        assert!(report.contains("| Seed |"));
        assert!(report.contains("| Status |"));

        // Check verification section
        assert!(report.contains("## Verification Tests"));
        assert!(report.contains("**Summary:**"));

        // Check falsification section
        assert!(report.contains("## Falsification Criteria"));

        // Check reproducibility section (sample_result has it)
        assert!(report.contains("## Reproducibility"));

        // Check execution section
        assert!(report.contains("## Execution Metrics"));
        assert!(report.contains("| Duration |"));
        assert!(report.contains("| Steps |"));
        assert!(report.contains("| Replications |"));
    }

    #[test]
    fn test_json_report_deserialization() {
        let result = sample_result();
        let json = ReportGenerator::json(&result);
        assert!(json.is_ok());
        let json = json.ok().unwrap();

        // Should be valid JSON
        let parsed: Result<serde_json::Value, _> = serde_json::from_str(&json);
        assert!(parsed.is_ok());
    }

    #[test]
    fn test_text_report_full_content() {
        let result = sample_result();
        let report = ReportGenerator::text(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();

        assert!(report.contains("EXPERIMENT REPORT:"));
        assert!(report.contains("ID:"));
        assert!(report.contains("Seed:"));
        assert!(report.contains("VERIFICATION TESTS"));
        assert!(report.contains("FALSIFICATION CRITERIA"));
        assert!(report.contains("EXECUTION"));
        assert!(report.contains("Duration:"));
        assert!(report.contains("Replications:"));
    }

    #[test]
    fn test_emc_compliance_only_schema_errors() {
        let report = EmcComplianceReport {
            experiment_name: "Schema Error".to_string(),
            passed: false,
            schema_errors: vec!["Schema error only".to_string()],
            emc_errors: Vec::new(),
            warnings: Vec::new(),
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: true,
                edd_02_verification_tests: true,
                edd_03_seed_specified: true,
                edd_04_falsification_criteria: true,
                edd_05_hypothesis: true,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.ok().unwrap();
        assert!(output.contains("Schema: Schema error only"));
    }

    #[test]
    fn test_emc_compliance_only_emc_errors() {
        let report = EmcComplianceReport {
            experiment_name: "EMC Error".to_string(),
            passed: false,
            schema_errors: Vec::new(),
            emc_errors: vec!["EMC error only".to_string()],
            warnings: Vec::new(),
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: true,
                edd_02_verification_tests: true,
                edd_03_seed_specified: true,
                edd_04_falsification_criteria: true,
                edd_05_hypothesis: true,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.ok().unwrap();
        assert!(output.contains("EMC: EMC error only"));
    }

    #[test]
    fn test_verification_with_error_field() {
        let mut result = sample_result();
        result.verification.tests = vec![VerificationTestSummary {
            id: "VT-ERR".to_string(),
            name: "Test with error".to_string(),
            passed: false,
            expected: Some(10.0),
            actual: Some(15.0),
            tolerance: Some(0.001),
            error: Some("Out of tolerance".to_string()),
        }];
        result.verification.passed = 0;
        result.verification.failed = 1;

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("VT-ERR"));
        assert!(report.contains("FAIL"));
    }

    #[test]
    fn test_reproducibility_not_passed() {
        let mut result = sample_result();
        result.reproducibility = Some(ReproducibilitySummary {
            passed: false,
            runs: 3,
            identical: false,
            reference_hash: "abc123".to_string(),
            run_hashes: vec![
                "abc123".to_string(),
                "def456".to_string(),
                "ghi789".to_string(),
            ],
            platform: "x86_64".to_string(),
        });

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("| Passed | NO |"));
        assert!(report.contains("| Identical | false |"));
    }

    #[test]
    fn test_multiple_verification_tests() {
        let mut result = sample_result();
        result.verification.tests = vec![
            VerificationTestSummary {
                id: "VT-001".to_string(),
                name: "Test 1".to_string(),
                passed: true,
                expected: Some(1.0),
                actual: Some(1.0),
                tolerance: Some(0.01),
                error: None,
            },
            VerificationTestSummary {
                id: "VT-002".to_string(),
                name: "Test 2".to_string(),
                passed: true,
                expected: Some(2.0),
                actual: Some(2.0),
                tolerance: Some(0.01),
                error: None,
            },
            VerificationTestSummary {
                id: "VT-003".to_string(),
                name: "Test 3".to_string(),
                passed: false,
                expected: Some(3.0),
                actual: Some(3.5),
                tolerance: Some(0.01),
                error: Some("Test 3 failed".to_string()),
            },
        ];

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("VT-001"));
        assert!(report.contains("VT-002"));
        assert!(report.contains("VT-003"));
    }

    #[test]
    fn test_multiple_falsification_criteria() {
        let mut result = sample_result();
        result.falsification.criteria = vec![
            FalsificationCriterionResult {
                id: "FC-001".to_string(),
                name: "Criterion 1".to_string(),
                triggered: false,
                condition: "x < 1".to_string(),
                severity: "warning".to_string(),
                value: Some(0.5),
                threshold: Some(1.0),
            },
            FalsificationCriterionResult {
                id: "FC-002".to_string(),
                name: "Criterion 2".to_string(),
                triggered: true,
                condition: "y > 10".to_string(),
                severity: "critical".to_string(),
                value: Some(15.0),
                threshold: Some(10.0),
            },
        ];

        let report = ReportGenerator::markdown(&result);
        assert!(report.is_ok());
        let report = report.ok().unwrap();
        assert!(report.contains("FC-001"));
        assert!(report.contains("FC-002"));
    }

    #[test]
    fn test_all_edd_compliance_fail() {
        let report = EmcComplianceReport {
            experiment_name: "All Fail".to_string(),
            passed: false,
            schema_errors: Vec::new(),
            emc_errors: Vec::new(),
            warnings: Vec::new(),
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: false,
                edd_02_verification_tests: false,
                edd_03_seed_specified: false,
                edd_04_falsification_criteria: false,
                edd_05_hypothesis: false,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.ok().unwrap();

        // Should contain FAIL for all checklist items
        let fail_count = output.matches("| FAIL |").count();
        assert_eq!(fail_count, 5, "All 5 EDD checks should fail");
    }

    #[test]
    fn test_emc_compliance_footer() {
        let report = EmcComplianceReport {
            experiment_name: "Footer Test".to_string(),
            passed: true,
            schema_errors: Vec::new(),
            emc_errors: Vec::new(),
            warnings: Vec::new(),
            edd_compliance: EddComplianceChecklist {
                edd_01_emc_reference: true,
                edd_02_verification_tests: true,
                edd_03_seed_specified: true,
                edd_04_falsification_criteria: true,
                edd_05_hypothesis: true,
            },
        };

        let output = ReportGenerator::emc_compliance_markdown(&report);
        assert!(output.is_ok());
        let output = output.ok().unwrap();
        assert!(output.contains("---"));
        assert!(output.contains("*Generated by simular v"));
    }
}