apr-qa-runner 0.1.0

Playbook executor for APR model qualification testing
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
//! Fail-Fast Diagnostic Report Generation (FF-REPORT-001)
//!
//! Generates comprehensive diagnostic reports on test failure using apr's rich tooling.
//! Reports are designed for immediate GitHub issue creation with full reproduction context.

use crate::evidence::Evidence;
use serde::{Deserialize, Serialize};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};

/// Timeout for each diagnostic command
const CHECK_TIMEOUT: Duration = Duration::from_secs(30);
const INSPECT_TIMEOUT: Duration = Duration::from_secs(10);
const TRACE_TIMEOUT: Duration = Duration::from_secs(60);
const TENSORS_TIMEOUT: Duration = Duration::from_secs(10);
const EXPLAIN_TIMEOUT: Duration = Duration::from_secs(5);

/// Result of a diagnostic command
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticResult {
    /// Command that was run
    pub command: String,
    /// Whether the command succeeded
    pub success: bool,
    /// Stdout output
    pub stdout: String,
    /// Stderr output
    pub stderr: String,
    /// Duration in milliseconds
    pub duration_ms: u64,
    /// Whether the command timed out
    pub timed_out: bool,
}

/// Environment context for the report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnvironmentContext {
    /// Operating system (e.g., "linux", "macos", "windows")
    pub os: String,
    /// CPU architecture (e.g., "x86_64", "aarch64")
    pub arch: String,
    /// apr-qa version
    pub apr_qa_version: String,
    /// apr CLI version
    pub apr_cli_version: String,
    /// Git commit hash (short form)
    pub git_commit: String,
    /// Git branch name
    pub git_branch: String,
    /// Whether working directory has uncommitted changes
    pub git_dirty: bool,
    /// Rust compiler version
    pub rustc_version: String,
}

impl EnvironmentContext {
    /// Collect environment context
    #[must_use]
    pub fn collect() -> Self {
        Self {
            os: std::env::consts::OS.to_string(),
            arch: std::env::consts::ARCH.to_string(),
            apr_qa_version: env!("CARGO_PKG_VERSION").to_string(),
            apr_cli_version: get_apr_version(),
            git_commit: get_git_commit(),
            git_branch: get_git_branch(),
            git_dirty: get_git_dirty(),
            rustc_version: get_rustc_version(),
        }
    }
}

/// Failure details from the evidence
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailureDetails {
    /// Gate ID that failed (e.g., "G3-STABLE")
    pub gate_id: String,
    /// Model identifier (HuggingFace repo path)
    pub model: String,
    /// Model format (e.g., "Apr", "SafeTensors", "Gguf")
    pub format: String,
    /// Backend used (e.g., "Cpu", "Metal", "Cuda")
    pub backend: String,
    /// Test outcome (e.g., "Crashed", "Falsified", "Timeout")
    pub outcome: String,
    /// Human-readable failure reason
    pub reason: String,
    /// Process exit code if available
    pub exit_code: Option<i32>,
    /// Test duration in milliseconds
    pub duration_ms: u64,
    /// Standard error output if captured
    pub stderr: Option<String>,
}

impl From<&Evidence> for FailureDetails {
    fn from(evidence: &Evidence) -> Self {
        Self {
            gate_id: evidence.gate_id.clone(),
            model: evidence.scenario.model.hf_repo(),
            format: format!("{:?}", evidence.scenario.format),
            backend: format!("{:?}", evidence.scenario.backend),
            outcome: format!("{:?}", evidence.outcome),
            reason: evidence.reason.clone(),
            exit_code: evidence.exit_code,
            duration_ms: evidence.metrics.duration_ms,
            stderr: evidence.stderr.clone(),
        }
    }
}

/// Complete fail-fast diagnostic report
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FailFastReport {
    /// Report version
    pub version: String,
    /// Timestamp
    pub timestamp: String,
    /// Failure details
    pub failure: FailureDetails,
    /// Environment context
    pub environment: EnvironmentContext,
    /// Diagnostic results
    pub diagnostics: DiagnosticsBundle,
    /// Reproduction information
    pub reproduction: ReproductionInfo,
}

/// Bundle of all diagnostic results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DiagnosticsBundle {
    /// Results from `apr check` - pipeline integrity
    pub check: Option<DiagnosticResult>,
    /// Results from `apr inspect` - model metadata
    pub inspect: Option<DiagnosticResult>,
    /// Results from `apr trace` - layer-by-layer analysis
    pub trace: Option<DiagnosticResult>,
    /// Results from `apr tensors` - tensor names and shapes
    pub tensors: Option<DiagnosticResult>,
    /// Results from `apr explain` - error code explanation
    pub explain: Option<DiagnosticResult>,
}

/// Information for reproducing the failure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReproductionInfo {
    /// Command to reproduce the failure
    pub command: String,
    /// Path to the model file used
    pub model_path: String,
    /// Path to the playbook file if applicable
    pub playbook: Option<String>,
}

/// Fail-fast diagnostic reporter
pub struct FailFastReporter {
    output_dir: PathBuf,
    binary: String,
}

impl FailFastReporter {
    /// Create a new reporter
    #[must_use]
    pub fn new(output_dir: &Path) -> Self {
        Self {
            output_dir: output_dir.to_path_buf(),
            binary: "apr".to_string(),
        }
    }

    /// Create with custom binary path
    #[must_use]
    pub fn with_binary(mut self, binary: &str) -> Self {
        self.binary = binary.to_string();
        self
    }

    /// Generate full diagnostic report on failure
    ///
    /// # Errors
    ///
    /// Returns an error if report generation fails.
    pub fn generate_report(
        &self,
        evidence: &Evidence,
        model_path: &Path,
        playbook: Option<&str>,
    ) -> std::io::Result<FailFastReport> {
        let report_dir = self.output_dir.join("fail-fast-report");
        std::fs::create_dir_all(&report_dir)?;

        eprintln!("[FAIL-FAST] Generating diagnostic report...");

        // Collect diagnostics
        let check = self.run_check(model_path);
        let inspect = self.run_inspect(model_path);
        let trace = self.run_trace(model_path);
        let tensors = self.run_tensors(model_path);
        let explain = self.run_explain(&evidence.gate_id);

        // Save individual diagnostic files first (before moving into report)
        if let Some(ref c) = check {
            self.save_json(&report_dir.join("check.json"), c)?;
        }
        if let Some(ref i) = inspect {
            self.save_json(&report_dir.join("inspect.json"), i)?;
        }
        if let Some(ref t) = trace {
            self.save_json(&report_dir.join("trace.json"), t)?;
        }
        if let Some(ref t) = tensors {
            self.save_json(&report_dir.join("tensors.json"), t)?;
        }

        // Build report (moves diagnostic values)
        let report = FailFastReport {
            version: "1.0.0".to_string(),
            timestamp: chrono::Utc::now().to_rfc3339(),
            failure: FailureDetails::from(evidence),
            environment: EnvironmentContext::collect(),
            diagnostics: DiagnosticsBundle {
                check,
                inspect,
                trace,
                tensors,
                explain,
            },
            reproduction: ReproductionInfo {
                command: format!(
                    "apr-qa run {} --fail-fast",
                    playbook.unwrap_or("playbook.yaml")
                ),
                model_path: model_path.to_string_lossy().to_string(),
                playbook: playbook.map(String::from),
            },
        };

        // Save full diagnostics JSON
        self.save_json(&report_dir.join("diagnostics.json"), &report)?;

        // Save environment
        self.save_json(&report_dir.join("environment.json"), &report.environment)?;

        // Save stderr log
        if let Some(ref stderr) = evidence.stderr {
            std::fs::write(report_dir.join("stderr.log"), stderr)?;
        }

        // Generate markdown summary
        let summary = self.generate_markdown(&report);
        std::fs::write(report_dir.join("summary.md"), &summary)?;

        eprintln!("[FAIL-FAST] Report saved to: {}", report_dir.display());
        eprintln!("[FAIL-FAST] Summary: {}/summary.md", report_dir.display());
        eprintln!("[FAIL-FAST] GitHub issue body ready for paste");

        Ok(report)
    }

    /// Run apr check and capture output
    fn run_check(&self, model_path: &Path) -> Option<DiagnosticResult> {
        eprint!("[FAIL-FAST] Running apr check... ");
        let result = self.run_command_with_timeout(
            &[
                &self.binary,
                "check",
                &model_path.to_string_lossy(),
                "--json",
            ],
            CHECK_TIMEOUT,
        );
        eprintln!(
            "done ({:.1}s){}",
            result.duration_ms as f64 / 1000.0,
            if result.timed_out { " [TIMEOUT]" } else { "" }
        );
        Some(result)
    }

    /// Run apr inspect and capture output
    fn run_inspect(&self, model_path: &Path) -> Option<DiagnosticResult> {
        eprint!("[FAIL-FAST] Running apr inspect... ");
        let result = self.run_command_with_timeout(
            &[
                &self.binary,
                "inspect",
                &model_path.to_string_lossy(),
                "--json",
            ],
            INSPECT_TIMEOUT,
        );
        eprintln!(
            "done ({:.1}s){}",
            result.duration_ms as f64 / 1000.0,
            if result.timed_out { " [TIMEOUT]" } else { "" }
        );
        Some(result)
    }

    /// Run apr trace and capture output
    fn run_trace(&self, model_path: &Path) -> Option<DiagnosticResult> {
        // Only run trace for .apr files
        if model_path.extension().is_none_or(|e| e != "apr") {
            return None;
        }

        eprint!("[FAIL-FAST] Running apr trace... ");
        let result = self.run_command_with_timeout(
            &[
                &self.binary,
                "trace",
                &model_path.to_string_lossy(),
                "--payload",
                "--json",
            ],
            TRACE_TIMEOUT,
        );
        eprintln!(
            "done ({:.1}s){}",
            result.duration_ms as f64 / 1000.0,
            if result.timed_out { " [TIMEOUT]" } else { "" }
        );
        Some(result)
    }

    /// Run apr tensors and capture output
    fn run_tensors(&self, model_path: &Path) -> Option<DiagnosticResult> {
        eprint!("[FAIL-FAST] Running apr tensors... ");
        let result = self.run_command_with_timeout(
            &[
                &self.binary,
                "tensors",
                &model_path.to_string_lossy(),
                "--json",
            ],
            TENSORS_TIMEOUT,
        );
        eprintln!(
            "done ({:.1}s){}",
            result.duration_ms as f64 / 1000.0,
            if result.timed_out { " [TIMEOUT]" } else { "" }
        );
        Some(result)
    }

    /// Run apr explain for the error code
    fn run_explain(&self, error_code: &str) -> Option<DiagnosticResult> {
        // Extract error code pattern (e.g., "G3-STABLE" -> try explaining common errors)
        eprint!("[FAIL-FAST] Running apr explain... ");
        let result =
            self.run_command_with_timeout(&[&self.binary, "explain", error_code], EXPLAIN_TIMEOUT);
        eprintln!(
            "done ({:.1}s){}",
            result.duration_ms as f64 / 1000.0,
            if result.timed_out { " [TIMEOUT]" } else { "" }
        );
        Some(result)
    }

    /// Run a command with timeout
    fn run_command_with_timeout(&self, args: &[&str], timeout: Duration) -> DiagnosticResult {
        let start = Instant::now();
        let command_str = args.join(" ");

        let output = Command::new(args[0]).args(&args[1..]).output();

        let duration = start.elapsed();
        let timed_out = duration > timeout;

        match output {
            Ok(out) => DiagnosticResult {
                command: command_str,
                success: out.status.success(),
                stdout: String::from_utf8_lossy(&out.stdout).to_string(),
                stderr: String::from_utf8_lossy(&out.stderr).to_string(),
                duration_ms: duration.as_millis() as u64,
                timed_out,
            },
            Err(e) => DiagnosticResult {
                command: command_str,
                success: false,
                stdout: String::new(),
                stderr: format!("Failed to execute: {e}"),
                duration_ms: duration.as_millis() as u64,
                timed_out,
            },
        }
    }

    /// Save JSON to file
    fn save_json<T: Serialize>(&self, path: &Path, data: &T) -> std::io::Result<()> {
        let json = serde_json::to_string_pretty(data).map_err(std::io::Error::other)?;
        std::fs::write(path, json)
    }

    /// Generate markdown summary
    #[must_use]
    #[allow(clippy::too_many_lines)]
    pub fn generate_markdown(&self, report: &FailFastReport) -> String {
        let mut md = String::new();

        // Header
        let _ = writeln!(md, "# Fail-Fast Report: {}\n", report.failure.gate_id);

        // Failure Summary Table
        md.push_str("## Failure Summary\n\n");
        md.push_str("| Field | Value |\n");
        md.push_str("|-------|-------|\n");
        let _ = writeln!(md, "| Gate | `{}` |", report.failure.gate_id);
        let _ = writeln!(md, "| Model | `{}` |", report.failure.model);
        let _ = writeln!(md, "| Format | {} |", report.failure.format);
        let _ = writeln!(md, "| Backend | {} |", report.failure.backend);
        let _ = writeln!(md, "| Outcome | {} |", report.failure.outcome);
        if let Some(code) = report.failure.exit_code {
            let _ = writeln!(md, "| Exit Code | {code} |");
        }
        let _ = writeln!(md, "| Duration | {}ms |", report.failure.duration_ms);
        md.push('\n');

        // Reason
        md.push_str("### Reason\n\n");
        let _ = writeln!(md, "{}\n", report.failure.reason);

        // Environment Table
        md.push_str("## Environment\n\n");
        md.push_str("| Field | Value |\n");
        md.push_str("|-------|-------|\n");
        let _ = writeln!(
            md,
            "| OS | {} {} |",
            report.environment.os, report.environment.arch
        );
        let _ = writeln!(md, "| apr-qa | {} |", report.environment.apr_qa_version);
        let _ = writeln!(md, "| apr-cli | {} |", report.environment.apr_cli_version);
        let _ = writeln!(
            md,
            "| Git | {} ({}){}|",
            report.environment.git_commit,
            report.environment.git_branch,
            if report.environment.git_dirty {
                " [dirty]"
            } else {
                ""
            }
        );
        let _ = writeln!(md, "| Rust | {} |", report.environment.rustc_version);
        md.push('\n');

        // Pipeline Check Results
        if let Some(ref check) = report.diagnostics.check {
            md.push_str("## Pipeline Check Results\n\n");
            if check.success {
                md.push_str("All pipeline checks passed.\n\n");
            } else {
                md.push_str("**Pipeline check failed:**\n\n");
                md.push_str("```\n");
                md.push_str(&check.stderr);
                md.push_str("\n```\n\n");
            }
        }

        // Model Metadata
        if let Some(ref inspect) = report.diagnostics.inspect {
            md.push_str("## Model Metadata\n\n");
            md.push_str("<details>\n<summary>apr inspect output</summary>\n\n");
            md.push_str("```json\n");
            md.push_str(&inspect.stdout);
            md.push_str("\n```\n\n");
            md.push_str("</details>\n\n");
        }

        // Tensor Info
        if let Some(ref tensors) = report.diagnostics.tensors {
            md.push_str("## Tensor Inventory\n\n");
            md.push_str("<details>\n<summary>apr tensors output</summary>\n\n");
            md.push_str("```json\n");
            md.push_str(&tensors.stdout);
            md.push_str("\n```\n\n");
            md.push_str("</details>\n\n");
        }

        // Trace (if available)
        if let Some(ref trace) = report.diagnostics.trace {
            md.push_str("## Layer Trace\n\n");
            md.push_str("<details>\n<summary>apr trace output</summary>\n\n");
            md.push_str("```json\n");
            md.push_str(&trace.stdout);
            md.push_str("\n```\n\n");
            md.push_str("</details>\n\n");
        }

        // Error Explanation
        if let Some(ref explain) = report.diagnostics.explain {
            if !explain.stdout.is_empty() {
                md.push_str("## Error Analysis\n\n");
                md.push_str(&explain.stdout);
                md.push_str("\n\n");
            }
        }

        // Stderr Capture
        if let Some(ref stderr) = report.failure.stderr {
            if !stderr.is_empty() {
                md.push_str("## Stderr Capture\n\n");
                md.push_str("<details>\n<summary>Full stderr output</summary>\n\n");
                md.push_str("```\n");
                md.push_str(stderr);
                md.push_str("\n```\n\n");
                md.push_str("</details>\n\n");
            }
        }

        // Reproduction
        md.push_str("## Reproduction\n\n");
        md.push_str("```bash\n");
        md.push_str("# Reproduce this failure\n");
        let _ = writeln!(md, "{}\n", report.reproduction.command);
        md.push_str("# Run diagnostics manually\n");
        let _ = writeln!(md, "apr check {}", report.reproduction.model_path);
        let _ = writeln!(
            md,
            "apr trace {} --payload -v",
            report.reproduction.model_path
        );
        let _ = writeln!(md, "apr explain {}", report.failure.gate_id);
        md.push_str("```\n");

        md
    }
}

// Helper functions for environment collection

fn get_apr_version() -> String {
    Command::new("apr")
        .arg("--version")
        .output()
        .ok()
        .and_then(|o| {
            String::from_utf8_lossy(&o.stdout)
                .lines()
                .next()
                .map(|s| s.replace("apr ", "").trim().to_string())
        })
        .unwrap_or_else(|| "unknown".to_string())
}

fn get_git_commit() -> String {
    Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .ok()
        .map_or_else(
            || "unknown".to_string(),
            |o| String::from_utf8_lossy(&o.stdout).trim().to_string(),
        )
}

fn get_git_branch() -> String {
    Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .output()
        .ok()
        .map_or_else(
            || "unknown".to_string(),
            |o| String::from_utf8_lossy(&o.stdout).trim().to_string(),
        )
}

fn get_git_dirty() -> bool {
    Command::new("git")
        .args(["status", "--porcelain"])
        .output()
        .ok()
        .is_some_and(|o| !o.stdout.is_empty())
}

fn get_rustc_version() -> String {
    Command::new("rustc")
        .arg("--version")
        .output()
        .ok()
        .map_or_else(
            || "unknown".to_string(),
            |o| {
                String::from_utf8_lossy(&o.stdout)
                    .trim()
                    .replace("rustc ", "")
            },
        )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::evidence::{HostInfo, Outcome, PerformanceMetrics};
    use apr_qa_gen::{Backend, Format, Modality, ModelId, QaScenario};
    use chrono::Utc;
    use std::collections::HashMap;

    fn test_evidence() -> Evidence {
        Evidence {
            id: "test-evidence-001".to_string(),
            gate_id: "G3-STABLE".to_string(),
            scenario: QaScenario::new(
                ModelId::new("Qwen", "Qwen2.5-Coder-0.5B-Instruct"),
                Modality::Run,
                Backend::Cpu,
                Format::Apr,
                "What is 2+2?".to_string(),
                0,
            ),
            outcome: Outcome::Crashed,
            reason: "Process crashed with exit code -1".to_string(),
            output: String::new(),
            stderr: Some("SIGSEGV at 0x12345".to_string()),
            exit_code: Some(-1),
            metrics: PerformanceMetrics {
                duration_ms: 52740,
                ..Default::default()
            },
            timestamp: Utc::now(),
            host: HostInfo::default(),
            metadata: HashMap::new(),
        }
    }

    #[test]
    fn test_failure_details_from_evidence() {
        let evidence = test_evidence();
        let details = FailureDetails::from(&evidence);

        assert_eq!(details.gate_id, "G3-STABLE");
        assert_eq!(details.model, "Qwen/Qwen2.5-Coder-0.5B-Instruct");
        assert_eq!(details.format, "Apr");
        assert_eq!(details.backend, "Cpu");
        assert_eq!(details.exit_code, Some(-1));
    }

    #[test]
    fn test_environment_context_collect() {
        let ctx = EnvironmentContext::collect();

        assert!(!ctx.os.is_empty());
        assert!(!ctx.arch.is_empty());
        assert!(!ctx.apr_qa_version.is_empty());
    }

    #[test]
    fn test_diagnostic_result_serialization() {
        let result = DiagnosticResult {
            command: "apr check model.apr".to_string(),
            success: true,
            stdout: "{}".to_string(),
            stderr: String::new(),
            duration_ms: 1234,
            timed_out: false,
        };

        let json = serde_json::to_string(&result).unwrap();
        assert!(json.contains("apr check"));
        assert!(json.contains("1234"));
    }

    #[test]
    fn test_generate_markdown() {
        let reporter = FailFastReporter::new(Path::new("output"));
        let evidence = test_evidence();

        let report = FailFastReport {
            version: "1.0.0".to_string(),
            timestamp: "2024-02-04T18:00:00Z".to_string(),
            failure: FailureDetails::from(&evidence),
            environment: EnvironmentContext {
                os: "linux".to_string(),
                arch: "x86_64".to_string(),
                apr_qa_version: "0.1.0".to_string(),
                apr_cli_version: "0.2.12".to_string(),
                git_commit: "abc123".to_string(),
                git_branch: "main".to_string(),
                git_dirty: false,
                rustc_version: "1.93.0".to_string(),
            },
            diagnostics: DiagnosticsBundle {
                check: None,
                inspect: None,
                trace: None,
                tensors: None,
                explain: None,
            },
            reproduction: ReproductionInfo {
                command: "apr-qa run playbook.yaml --fail-fast".to_string(),
                model_path: "/path/to/model.apr".to_string(),
                playbook: Some("playbook.yaml".to_string()),
            },
        };

        let md = reporter.generate_markdown(&report);

        assert!(md.contains("# Fail-Fast Report: G3-STABLE"));
        assert!(md.contains("| Gate | `G3-STABLE` |"));
        assert!(md.contains("| Model | `Qwen/Qwen2.5-Coder-0.5B-Instruct` |"));
        assert!(md.contains("## Reproduction"));
    }

    #[test]
    fn test_reporter_new() {
        let reporter = FailFastReporter::new(Path::new("output"));
        assert_eq!(reporter.output_dir, PathBuf::from("output"));
        assert_eq!(reporter.binary, "apr");
    }

    #[test]
    fn test_reporter_with_binary() {
        let reporter = FailFastReporter::new(Path::new("output")).with_binary("/custom/apr");
        assert_eq!(reporter.binary, "/custom/apr");
    }

    #[test]
    fn test_generate_markdown_with_diagnostics() {
        let reporter = FailFastReporter::new(Path::new("output"));
        let evidence = test_evidence();

        let check_result = DiagnosticResult {
            command: "apr check /model.apr --json".to_string(),
            success: false,
            stdout: "{}".to_string(),
            stderr: "Error: failed to load model".to_string(),
            duration_ms: 500,
            timed_out: false,
        };

        let inspect_result = DiagnosticResult {
            command: "apr inspect /model.apr --json".to_string(),
            success: true,
            stdout: r#"{"architecture": "Qwen2"}"#.to_string(),
            stderr: String::new(),
            duration_ms: 200,
            timed_out: false,
        };

        let tensors_result = DiagnosticResult {
            command: "apr tensors /model.apr --json".to_string(),
            success: true,
            stdout: r#"{"count": 256}"#.to_string(),
            stderr: String::new(),
            duration_ms: 150,
            timed_out: false,
        };

        let trace_result = DiagnosticResult {
            command: "apr trace /model.apr --payload --json".to_string(),
            success: true,
            stdout: r#"{"layers": []}"#.to_string(),
            stderr: String::new(),
            duration_ms: 1000,
            timed_out: false,
        };

        let explain_result = DiagnosticResult {
            command: "apr explain G3-STABLE".to_string(),
            success: true,
            stdout: "G3-STABLE: Model stability gate - ensures no crashes".to_string(),
            stderr: String::new(),
            duration_ms: 50,
            timed_out: false,
        };

        let report = FailFastReport {
            version: "1.0.0".to_string(),
            timestamp: "2024-02-04T18:00:00Z".to_string(),
            failure: FailureDetails::from(&evidence),
            environment: EnvironmentContext {
                os: "linux".to_string(),
                arch: "x86_64".to_string(),
                apr_qa_version: "0.1.0".to_string(),
                apr_cli_version: "0.2.12".to_string(),
                git_commit: "abc123".to_string(),
                git_branch: "main".to_string(),
                git_dirty: true,
                rustc_version: "1.93.0".to_string(),
            },
            diagnostics: DiagnosticsBundle {
                check: Some(check_result),
                inspect: Some(inspect_result),
                trace: Some(trace_result),
                tensors: Some(tensors_result),
                explain: Some(explain_result),
            },
            reproduction: ReproductionInfo {
                command: "apr-qa run playbook.yaml --fail-fast".to_string(),
                model_path: "/path/to/model.apr".to_string(),
                playbook: Some("playbook.yaml".to_string()),
            },
        };

        let md = reporter.generate_markdown(&report);

        // Check diagnostic sections are included
        assert!(md.contains("## Pipeline Check Results"));
        assert!(md.contains("**Pipeline check failed:**"));
        assert!(md.contains("Error: failed to load model"));
        assert!(md.contains("## Model Metadata"));
        assert!(md.contains("apr inspect output"));
        assert!(md.contains("## Tensor Inventory"));
        assert!(md.contains("apr tensors output"));
        assert!(md.contains("## Layer Trace"));
        assert!(md.contains("apr trace output"));
        assert!(md.contains("## Error Analysis"));
        assert!(md.contains("G3-STABLE: Model stability gate"));
        assert!(md.contains("[dirty]")); // git dirty flag
        assert!(md.contains("## Stderr Capture"));
        assert!(md.contains("SIGSEGV at 0x12345"));
    }

    #[test]
    fn test_generate_markdown_successful_check() {
        let reporter = FailFastReporter::new(Path::new("output"));
        let evidence = test_evidence();

        let check_result = DiagnosticResult {
            command: "apr check /model.apr --json".to_string(),
            success: true,
            stdout: "{}".to_string(),
            stderr: String::new(),
            duration_ms: 500,
            timed_out: false,
        };

        let report = FailFastReport {
            version: "1.0.0".to_string(),
            timestamp: "2024-02-04T18:00:00Z".to_string(),
            failure: FailureDetails::from(&evidence),
            environment: EnvironmentContext {
                os: "linux".to_string(),
                arch: "x86_64".to_string(),
                apr_qa_version: "0.1.0".to_string(),
                apr_cli_version: "0.2.12".to_string(),
                git_commit: "abc123".to_string(),
                git_branch: "main".to_string(),
                git_dirty: false,
                rustc_version: "1.93.0".to_string(),
            },
            diagnostics: DiagnosticsBundle {
                check: Some(check_result),
                inspect: None,
                trace: None,
                tensors: None,
                explain: None,
            },
            reproduction: ReproductionInfo {
                command: "apr-qa run playbook.yaml --fail-fast".to_string(),
                model_path: "/path/to/model.apr".to_string(),
                playbook: Some("playbook.yaml".to_string()),
            },
        };

        let md = reporter.generate_markdown(&report);

        assert!(md.contains("## Pipeline Check Results"));
        assert!(md.contains("All pipeline checks passed."));
    }

    #[test]
    fn test_run_trace_skips_non_apr() {
        let reporter = FailFastReporter::new(Path::new("output"));
        // run_trace should return None for non-.apr files
        let result = reporter.run_trace(Path::new("/model.safetensors"));
        assert!(result.is_none());
    }

    #[test]
    fn test_diagnostics_bundle_debug() {
        let bundle = DiagnosticsBundle {
            check: None,
            inspect: None,
            trace: None,
            tensors: None,
            explain: None,
        };
        // Just ensure Debug trait is implemented
        let _ = format!("{:?}", bundle);
    }

    #[test]
    fn test_reproduction_info_debug() {
        let info = ReproductionInfo {
            command: "apr-qa run test.yaml".to_string(),
            model_path: "/test/model.apr".to_string(),
            playbook: None,
        };
        // Just ensure Debug trait is implemented
        let _ = format!("{:?}", info);
    }

    #[test]
    fn test_fail_fast_report_debug() {
        let evidence = test_evidence();
        let report = FailFastReport {
            version: "1.0.0".to_string(),
            timestamp: "2024-02-04T18:00:00Z".to_string(),
            failure: FailureDetails::from(&evidence),
            environment: EnvironmentContext {
                os: "linux".to_string(),
                arch: "x86_64".to_string(),
                apr_qa_version: "0.1.0".to_string(),
                apr_cli_version: "0.2.12".to_string(),
                git_commit: "abc123".to_string(),
                git_branch: "main".to_string(),
                git_dirty: false,
                rustc_version: "1.93.0".to_string(),
            },
            diagnostics: DiagnosticsBundle {
                check: None,
                inspect: None,
                trace: None,
                tensors: None,
                explain: None,
            },
            reproduction: ReproductionInfo {
                command: "apr-qa run playbook.yaml --fail-fast".to_string(),
                model_path: "/path/to/model.apr".to_string(),
                playbook: Some("playbook.yaml".to_string()),
            },
        };
        // Just ensure Debug trait is implemented
        let _ = format!("{:?}", report);
    }
}