aprender-verify-ml 0.30.0

Synthetic Data Factory for Domain-Specific Code Intelligence
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
//! Verification Audit Trail
//!
//! Provides tamper-evident audit logging for test verification decisions.
//!
//! # Features
//!
//! - **Decision Path Tracking**: Record verification decisions with full context
//! - **Hash Chain Provenance**: Tamper-evident audit trails for compliance
//! - **Verdict Analysis**: Track pass/fail patterns and flaky tests
//!
//! # Toyota Way: 失敗を隠さない (Shippai wo kakusanai)
//! Never hide failures - every verification decision is auditable.
//!
//! # Example
//!
//! ```rust,ignore
//! use verificar::audit::{AuditCollector, VerificationPath};
//! use verificar::oracle::Verdict;
//!
//! let mut collector = AuditCollector::new("test-suite-001");
//!
//! let path = VerificationPath::new("test_addition")
//!     .with_verdict(Verdict::Pass)
//!     .with_duration(std::time::Duration::from_millis(50));
//!
//! collector.record(path);
//!
//! assert!(collector.verify_chain().valid);
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::time::{Duration, Instant};

use crate::oracle::{ExecutionResult, Verdict, VerificationResult};
use crate::Language;

// =============================================================================
// Verification Decision Path
// =============================================================================

/// Decision path for a verification execution.
///
/// Captures all relevant information for auditing a test verification decision.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct VerificationPath {
    /// Test case identifier
    pub test_id: String,

    /// Source language
    pub source_language: Option<Language>,

    /// Target language
    pub target_language: Option<Language>,

    /// Verification verdict
    pub verdict: Option<Verdict>,

    /// Execution duration in nanoseconds
    pub duration_ns: u64,

    /// Source execution result summary
    pub source_result: Option<ExecutionSummary>,

    /// Target execution result summary
    pub target_result: Option<ExecutionSummary>,

    /// Feature contributions (for ML-enhanced verification)
    contributions: Vec<f32>,

    /// Confidence score for this decision
    confidence: f32,

    /// Additional metadata
    pub metadata: HashMap<String, serde_json::Value>,
}

/// Summary of an execution result for audit purposes.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ExecutionSummary {
    /// Exit code
    pub exit_code: i32,

    /// Output length in bytes
    pub stdout_len: usize,

    /// Error output length in bytes
    pub stderr_len: usize,

    /// Execution duration in milliseconds
    pub duration_ms: u64,

    /// Hash of stdout content (for integrity)
    pub stdout_hash: u64,
}

impl From<&ExecutionResult> for ExecutionSummary {
    fn from(result: &ExecutionResult) -> Self {
        Self {
            exit_code: result.exit_code,
            stdout_len: result.stdout.len(),
            stderr_len: result.stderr.len(),
            duration_ms: result.duration_ms,
            stdout_hash: hash_string(&result.stdout),
        }
    }
}

impl VerificationPath {
    /// Create a new verification path for a test case.
    pub fn new(test_id: impl Into<String>) -> Self {
        Self {
            test_id: test_id.into(),
            source_language: None,
            target_language: None,
            verdict: None,
            duration_ns: 0,
            source_result: None,
            target_result: None,
            contributions: Vec::new(),
            confidence: 1.0,
            metadata: HashMap::new(),
        }
    }

    /// Set the verification verdict.
    #[must_use]
    pub fn with_verdict(mut self, verdict: Verdict) -> Self {
        // Adjust confidence based on verdict
        self.confidence = match &verdict {
            Verdict::Pass => 1.0,
            Verdict::OutputMismatch { .. } => 0.0,
            Verdict::Timeout { .. } => 0.3,
            Verdict::RuntimeError { .. } => 0.0,
        };
        self.verdict = Some(verdict);
        self
    }

    /// Set execution duration.
    #[must_use]
    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration_ns = duration.as_nanos() as u64;
        self
    }

    /// Set source and target languages.
    #[must_use]
    pub fn with_languages(mut self, source: Language, target: Language) -> Self {
        self.source_language = Some(source);
        self.target_language = Some(target);
        self
    }

    /// Set source execution result.
    #[must_use]
    pub fn with_source_result(mut self, result: &ExecutionResult) -> Self {
        self.source_result = Some(ExecutionSummary::from(result));
        self
    }

    /// Set target execution result.
    #[must_use]
    pub fn with_target_result(mut self, result: &ExecutionResult) -> Self {
        self.target_result = Some(ExecutionSummary::from(result));
        self
    }

    /// Add metadata entry.
    #[must_use]
    pub fn with_metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata.insert(key.into(), value);
        self
    }

    /// Set feature contributions (for ML analysis).
    #[must_use]
    pub fn with_contributions(mut self, contributions: Vec<f32>) -> Self {
        self.contributions = contributions;
        self
    }

    /// Get feature contributions.
    pub fn feature_contributions(&self) -> &[f32] {
        &self.contributions
    }

    /// Get confidence score.
    pub fn confidence(&self) -> f32 {
        self.confidence
    }

    /// Check if this verification passed.
    pub fn passed(&self) -> bool {
        matches!(self.verdict, Some(Verdict::Pass))
    }

    /// Serialize to bytes for hashing.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::new();

        // Test ID
        bytes.extend_from_slice(self.test_id.as_bytes());
        bytes.push(0);

        // Duration
        bytes.extend_from_slice(&self.duration_ns.to_le_bytes());

        // Confidence
        bytes.extend_from_slice(&self.confidence.to_le_bytes());

        // Verdict indicator
        let verdict_byte = match &self.verdict {
            Some(Verdict::Pass) => 1u8,
            Some(Verdict::OutputMismatch { .. }) => 2u8,
            Some(Verdict::Timeout { .. }) => 3u8,
            Some(Verdict::RuntimeError { .. }) => 4u8,
            None => 0u8,
        };
        bytes.push(verdict_byte);

        bytes
    }

    /// Generate a text explanation of the verification.
    pub fn explain(&self) -> String {
        use std::fmt::Write;

        let mut explanation = format!("Test: {}\n", self.test_id);

        if let Some(src) = &self.source_language {
            let _ = writeln!(explanation, "Source: {src:?}");
        }
        if let Some(tgt) = &self.target_language {
            let _ = writeln!(explanation, "Target: {tgt:?}");
        }

        let _ = writeln!(
            explanation,
            "Duration: {:.2}ms",
            self.duration_ns as f64 / 1_000_000.0
        );

        if let Some(ref verdict) = self.verdict {
            let _ = writeln!(explanation, "Verdict: {verdict:?}");
        }

        let _ = write!(explanation, "Confidence: {:.1}%", self.confidence * 100.0);

        explanation
    }
}

impl From<&VerificationResult> for VerificationPath {
    fn from(result: &VerificationResult) -> Self {
        let mut path = Self::new(format!(
            "{}-to-{}",
            result.source_language, result.target_language
        ))
        .with_languages(result.source_language, result.target_language)
        .with_verdict(result.verdict.clone());

        if let Some(ref src) = result.source_result {
            path = path.with_source_result(src);
        }
        if let Some(ref tgt) = result.target_result {
            path = path.with_target_result(tgt);
        }

        path
    }
}

// =============================================================================
// Audit Trace Entry
// =============================================================================

/// A single audit trace entry.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AuditTrace {
    /// Sequence number
    pub sequence: u64,

    /// Timestamp in nanoseconds since epoch
    pub timestamp_ns: u64,

    /// The verification path
    pub path: VerificationPath,
}

/// Hash chain entry for tamper-evident audit.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HashChainEntry {
    /// Sequence number
    pub sequence: u64,

    /// SHA-256 hash of previous entry (zeros for genesis)
    pub prev_hash: [u8; 32],

    /// Hash of this entry
    pub hash: [u8; 32],

    /// The audit trace
    pub trace: AuditTrace,
}

// =============================================================================
// Audit Collector
// =============================================================================

/// Collector for verification audit trails.
#[derive(Debug)]
pub struct AuditCollector {
    /// Hash chain entries
    entries: Vec<HashChainEntry>,

    /// Next sequence number
    next_sequence: u64,

    /// Suite identifier
    suite_id: String,

    /// Statistics
    stats: AuditStats,
}

/// Statistics for audit trail.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct AuditStats {
    /// Total verifications
    pub total: usize,

    /// Passed verifications
    pub passed: usize,

    /// Failed verifications
    pub failed: usize,

    /// Timeout count
    pub timeouts: usize,

    /// Runtime errors
    pub errors: usize,

    /// Total duration in nanoseconds
    pub total_duration_ns: u64,
}

impl AuditCollector {
    /// Create a new audit collector for a test suite.
    pub fn new(suite_id: impl Into<String>) -> Self {
        Self {
            entries: Vec::new(),
            next_sequence: 0,
            suite_id: suite_id.into(),
            stats: AuditStats::default(),
        }
    }

    /// Get the suite identifier.
    pub fn suite_id(&self) -> &str {
        &self.suite_id
    }

    /// Record a verification decision.
    pub fn record(&mut self, path: VerificationPath) -> &HashChainEntry {
        // Update statistics
        self.stats.total += 1;
        self.stats.total_duration_ns += path.duration_ns;

        match &path.verdict {
            Some(Verdict::Pass) => self.stats.passed += 1,
            Some(Verdict::OutputMismatch { .. }) => self.stats.failed += 1,
            Some(Verdict::Timeout { .. }) => self.stats.timeouts += 1,
            Some(Verdict::RuntimeError { .. }) => self.stats.errors += 1,
            None => {}
        }

        let timestamp_ns = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0);

        let trace = AuditTrace {
            sequence: self.next_sequence,
            timestamp_ns,
            path,
        };

        // Get previous hash
        let prev_hash = self.entries.last().map_or([0u8; 32], |e| e.hash);

        // Compute hash
        let hash = self.compute_hash(&trace, &prev_hash);

        let entry = HashChainEntry {
            sequence: self.next_sequence,
            prev_hash,
            hash,
            trace,
        };

        self.entries.push(entry);
        self.next_sequence += 1;

        // SAFETY: We just pushed an entry, so the vector is guaranteed to be non-empty.
        // Using index access to avoid expect() which is denied by clippy configuration.
        &self.entries[self.entries.len() - 1]
    }

    /// Compute hash for an entry.
    fn compute_hash(&self, trace: &AuditTrace, prev_hash: &[u8; 32]) -> [u8; 32] {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();

        prev_hash.hash(&mut hasher);
        trace.sequence.hash(&mut hasher);
        trace.timestamp_ns.hash(&mut hasher);
        trace.path.test_id.hash(&mut hasher);
        trace.path.duration_ns.hash(&mut hasher);

        let hash_value = hasher.finish();

        let mut result = [0u8; 32];
        for i in 0..4 {
            result[i * 8..(i + 1) * 8].copy_from_slice(&hash_value.to_le_bytes());
        }

        result
    }

    /// Get all entries.
    pub fn entries(&self) -> &[HashChainEntry] {
        &self.entries
    }

    /// Get entry count.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Check if empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// Get statistics.
    pub fn stats(&self) -> &AuditStats {
        &self.stats
    }

    /// Verify hash chain integrity.
    pub fn verify_chain(&self) -> ChainVerification {
        contract_pre_oracle_verdict!(input);
        let mut entries_verified = 0;

        for (i, entry) in self.entries.iter().enumerate() {
            // Verify prev_hash linkage
            if i == 0 {
                if entry.prev_hash != [0u8; 32] {
                    return ChainVerification {
                        valid: false,
                        entries_verified,
                        first_break: Some(0),
                    };
                }
            } else {
                let expected_prev = self.entries[i - 1].hash;
                if entry.prev_hash != expected_prev {
                    return ChainVerification {
                        valid: false,
                        entries_verified,
                        first_break: Some(i),
                    };
                }
            }

            // Verify entry hash
            let computed_hash = self.compute_hash(&entry.trace, &entry.prev_hash);
            if entry.hash != computed_hash {
                return ChainVerification {
                    valid: false,
                    entries_verified,
                    first_break: Some(i),
                };
            }

            entries_verified += 1;
        }

        ChainVerification {
            valid: true,
            entries_verified,
            first_break: None,
        }
    }

    /// Get recent entries.
    pub fn recent(&self, n: usize) -> Vec<&HashChainEntry> {
        self.entries.iter().rev().take(n).collect()
    }

    /// Get failed verifications.
    pub fn failures(&self) -> Vec<&HashChainEntry> {
        self.entries
            .iter()
            .filter(|e| !e.trace.path.passed())
            .collect()
    }

    /// Export to JSON.
    ///
    /// # Errors
    ///
    /// Returns an error if JSON serialization fails.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        #[derive(Serialize)]
        struct Export<'a> {
            suite_id: &'a str,
            chain_length: usize,
            verified: bool,
            stats: &'a AuditStats,
            entries: &'a [HashChainEntry],
        }

        let verification = self.verify_chain();

        let export = Export {
            suite_id: &self.suite_id,
            chain_length: self.entries.len(),
            verified: verification.valid,
            stats: &self.stats,
            entries: &self.entries,
        };

        serde_json::to_string_pretty(&export)
    }
}

/// Result of hash chain verification.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChainVerification {
    /// Whether the chain is valid
    pub valid: bool,

    /// Number of entries verified
    pub entries_verified: usize,

    /// Index of first broken link (if any)
    pub first_break: Option<usize>,
}

// =============================================================================
// Verification Timer
// =============================================================================

/// Timer for measuring verification duration.
#[derive(Debug)]
pub struct VerificationTimer {
    start: Instant,
    test_id: String,
}

impl VerificationTimer {
    /// Start timing a verification.
    pub fn start(test_id: impl Into<String>) -> Self {
        Self {
            start: Instant::now(),
            test_id: test_id.into(),
        }
    }

    /// Stop timing and create a verification path.
    pub fn stop(self) -> VerificationPath {
        let duration = self.start.elapsed();
        VerificationPath::new(self.test_id).with_duration(duration)
    }

    /// Stop timing with a verdict.
    pub fn stop_with_verdict(self, verdict: Verdict) -> VerificationPath {
        let duration = self.start.elapsed();
        VerificationPath::new(self.test_id)
            .with_duration(duration)
            .with_verdict(verdict)
    }
}

// =============================================================================
// Helper Functions
// =============================================================================

/// Simple string hash for integrity checking.
fn hash_string(s: &str) -> u64 {
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    s.hash(&mut hasher);
    hasher.finish()
}

/// Create a new audit collector with generated suite ID.
#[must_use]
pub fn new_audit_collector() -> AuditCollector {
    let suite_id = format!(
        "suite-{}",
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis())
            .unwrap_or(0)
    );
    AuditCollector::new(suite_id)
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::oracle::Phase;

    #[test]
    fn test_verification_path_creation() {
        let path = VerificationPath::new("test_001");
        assert_eq!(path.test_id, "test_001");
        assert_eq!(path.confidence(), 1.0);
        assert!(path.verdict.is_none());
    }

    #[test]
    fn test_verification_path_with_verdict_pass() {
        let path = VerificationPath::new("test").with_verdict(Verdict::Pass);
        assert!(path.passed());
        assert_eq!(path.confidence(), 1.0);
    }

    #[test]
    fn test_verification_path_with_verdict_mismatch() {
        let path = VerificationPath::new("test").with_verdict(Verdict::OutputMismatch {
            expected: "a".into(),
            actual: "b".into(),
        });
        assert!(!path.passed());
        assert_eq!(path.confidence(), 0.0);
    }

    #[test]
    fn test_verification_path_with_verdict_timeout() {
        let path = VerificationPath::new("test").with_verdict(Verdict::Timeout {
            phase: Phase::Source,
            limit_ms: 5000,
        });
        assert!(!path.passed());
        assert_eq!(path.confidence(), 0.3);
    }

    #[test]
    fn test_verification_path_with_verdict_error() {
        let path = VerificationPath::new("test").with_verdict(Verdict::RuntimeError {
            phase: Phase::Target,
            error: "error".into(),
        });
        assert!(!path.passed());
        assert_eq!(path.confidence(), 0.0);
    }

    #[test]
    fn test_verification_path_with_duration() {
        let path = VerificationPath::new("test").with_duration(Duration::from_millis(100));
        assert_eq!(path.duration_ns, 100_000_000);
    }

    #[test]
    fn test_verification_path_with_languages() {
        let path = VerificationPath::new("test").with_languages(Language::Python, Language::Rust);
        assert_eq!(path.source_language, Some(Language::Python));
        assert_eq!(path.target_language, Some(Language::Rust));
    }

    #[test]
    fn test_verification_path_explain() {
        let path = VerificationPath::new("test_001")
            .with_duration(Duration::from_millis(50))
            .with_verdict(Verdict::Pass);
        let explanation = path.explain();
        assert!(explanation.contains("test_001"));
        assert!(explanation.contains("50.00ms"));
        assert!(explanation.contains("Pass"));
    }

    #[test]
    fn test_verification_path_to_bytes() {
        let path = VerificationPath::new("test");
        let bytes = path.to_bytes();
        assert!(!bytes.is_empty());
    }

    #[test]
    fn test_execution_summary_from_result() {
        let result = ExecutionResult {
            stdout: "hello".to_string(),
            stderr: "err".to_string(),
            exit_code: 0,
            duration_ms: 100,
        };
        let summary = ExecutionSummary::from(&result);
        assert_eq!(summary.exit_code, 0);
        assert_eq!(summary.stdout_len, 5);
        assert_eq!(summary.stderr_len, 3);
        assert_eq!(summary.duration_ms, 100);
    }

    #[test]
    fn test_audit_collector_creation() {
        let collector = AuditCollector::new("suite-001");
        assert_eq!(collector.suite_id(), "suite-001");
        assert!(collector.is_empty());
    }

    #[test]
    fn test_audit_collector_record() {
        let mut collector = AuditCollector::new("suite");
        let path = VerificationPath::new("test_001").with_verdict(Verdict::Pass);

        let entry = collector.record(path);

        assert_eq!(entry.sequence, 0);
        assert_eq!(entry.prev_hash, [0u8; 32]);
        assert_eq!(collector.len(), 1);
    }

    #[test]
    fn test_audit_collector_stats() {
        let mut collector = AuditCollector::new("suite");

        collector.record(VerificationPath::new("t1").with_verdict(Verdict::Pass));
        collector.record(VerificationPath::new("t2").with_verdict(Verdict::Pass));
        collector.record(
            VerificationPath::new("t3").with_verdict(Verdict::OutputMismatch {
                expected: "a".into(),
                actual: "b".into(),
            }),
        );
        collector.record(VerificationPath::new("t4").with_verdict(Verdict::Timeout {
            phase: Phase::Source,
            limit_ms: 5000,
        }));

        let stats = collector.stats();
        assert_eq!(stats.total, 4);
        assert_eq!(stats.passed, 2);
        assert_eq!(stats.failed, 1);
        assert_eq!(stats.timeouts, 1);
    }

    #[test]
    fn test_audit_collector_hash_chain_linkage() {
        let mut collector = AuditCollector::new("suite");

        collector.record(VerificationPath::new("t1"));
        collector.record(VerificationPath::new("t2"));
        collector.record(VerificationPath::new("t3"));

        let entries = collector.entries();

        assert_eq!(entries[0].prev_hash, [0u8; 32]);
        assert_eq!(entries[1].prev_hash, entries[0].hash);
        assert_eq!(entries[2].prev_hash, entries[1].hash);
    }

    #[test]
    fn test_audit_collector_verify_chain() {
        let mut collector = AuditCollector::new("suite");

        collector.record(VerificationPath::new("t1").with_verdict(Verdict::Pass));
        collector.record(VerificationPath::new("t2").with_verdict(Verdict::Pass));

        let verification = collector.verify_chain();
        assert!(verification.valid);
        assert_eq!(verification.entries_verified, 2);
        assert!(verification.first_break.is_none());
    }

    #[test]
    fn test_audit_collector_recent() {
        let mut collector = AuditCollector::new("suite");

        for i in 0..5 {
            collector.record(VerificationPath::new(format!("t{}", i)));
        }

        let recent = collector.recent(3);
        assert_eq!(recent.len(), 3);
        assert_eq!(recent[0].sequence, 4);
        assert_eq!(recent[1].sequence, 3);
        assert_eq!(recent[2].sequence, 2);
    }

    #[test]
    fn test_audit_collector_failures() {
        let mut collector = AuditCollector::new("suite");

        collector.record(VerificationPath::new("t1").with_verdict(Verdict::Pass));
        collector.record(
            VerificationPath::new("t2").with_verdict(Verdict::OutputMismatch {
                expected: "a".into(),
                actual: "b".into(),
            }),
        );
        collector.record(VerificationPath::new("t3").with_verdict(Verdict::Pass));

        let failures = collector.failures();
        assert_eq!(failures.len(), 1);
        assert_eq!(failures[0].trace.path.test_id, "t2");
    }

    #[test]
    fn test_audit_collector_to_json() {
        let mut collector = AuditCollector::new("suite");
        collector.record(VerificationPath::new("t1").with_verdict(Verdict::Pass));

        let json = collector.to_json().unwrap();
        assert!(json.contains("suite"));
        assert!(json.contains("verified"));
        assert!(json.contains("stats"));
    }

    #[test]
    fn test_verification_timer() {
        let timer = VerificationTimer::start("test");
        std::thread::sleep(Duration::from_millis(10));
        let path = timer.stop();

        assert_eq!(path.test_id, "test");
        assert!(path.duration_ns > 0);
    }

    #[test]
    fn test_verification_timer_with_verdict() {
        let timer = VerificationTimer::start("test");
        let path = timer.stop_with_verdict(Verdict::Pass);

        assert!(path.passed());
    }

    #[test]
    fn test_new_audit_collector() {
        let collector = new_audit_collector();
        assert!(collector.suite_id().starts_with("suite-"));
    }

    #[test]
    fn test_verification_path_with_metadata() {
        let path = VerificationPath::new("test").with_metadata("key", serde_json::json!("value"));
        assert_eq!(path.metadata.len(), 1);
    }

    #[test]
    fn test_verification_path_with_contributions() {
        let contributions = vec![0.1, 0.2, 0.3];
        let path = VerificationPath::new("test").with_contributions(contributions.clone());
        assert_eq!(path.feature_contributions(), &contributions);
    }

    #[test]
    fn test_verification_path_with_source_result() {
        let result = ExecutionResult {
            stdout: "out".to_string(),
            stderr: "".to_string(),
            exit_code: 0,
            duration_ms: 10,
        };
        let path = VerificationPath::new("test").with_source_result(&result);
        assert!(path.source_result.is_some());
    }

    #[test]
    fn test_verification_path_with_target_result() {
        let result = ExecutionResult {
            stdout: "out".to_string(),
            stderr: "".to_string(),
            exit_code: 0,
            duration_ms: 10,
        };
        let path = VerificationPath::new("test").with_target_result(&result);
        assert!(path.target_result.is_some());
    }

    #[test]
    fn test_verification_path_from_result() {
        let result = VerificationResult {
            source_code: "print(1)".to_string(),
            source_language: Language::Python,
            target_code: "fn main() {}".to_string(),
            target_language: Language::Rust,
            verdict: Verdict::Pass,
            source_result: None,
            target_result: None,
        };

        let path = VerificationPath::from(&result);
        assert!(path.passed());
        assert_eq!(path.source_language, Some(Language::Python));
        assert_eq!(path.target_language, Some(Language::Rust));
    }

    #[test]
    fn test_chain_verification_serialization() {
        let verification = ChainVerification {
            valid: true,
            entries_verified: 5,
            first_break: None,
        };

        let json = serde_json::to_string(&verification).unwrap();
        let deserialized: ChainVerification = serde_json::from_str(&json).unwrap();

        assert_eq!(verification.valid, deserialized.valid);
        assert_eq!(verification.entries_verified, deserialized.entries_verified);
    }

    #[test]
    fn test_hash_string() {
        let hash1 = hash_string("hello");
        let hash2 = hash_string("hello");
        let hash3 = hash_string("world");

        assert_eq!(hash1, hash2);
        assert_ne!(hash1, hash3);
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use crate::oracle::Phase;
    use proptest::prelude::*;

    proptest! {
        #![proptest_config(ProptestConfig::with_cases(100))]

        #[test]
        fn prop_hash_chain_always_valid(n in 1usize..20) {
            let mut collector = AuditCollector::new("prop-test");

            for i in 0..n {
                collector.record(
                    VerificationPath::new(format!("t{}", i))
                        .with_verdict(Verdict::Pass)
                );
            }

            let verification = collector.verify_chain();
            prop_assert!(verification.valid);
            prop_assert_eq!(verification.entries_verified, n);
        }

        #[test]
        fn prop_sequence_numbers_monotonic(n in 2usize..20) {
            let mut collector = AuditCollector::new("test");

            for i in 0..n {
                collector.record(VerificationPath::new(format!("t{}", i)));
            }

            let entries = collector.entries();
            for i in 1..entries.len() {
                prop_assert!(entries[i].sequence > entries[i-1].sequence);
            }
        }

        #[test]
        fn prop_stats_consistent(
            passed in 0usize..10,
            failed in 0usize..10
        ) {
            let mut collector = AuditCollector::new("test");

            for i in 0..passed {
                collector.record(
                    VerificationPath::new(format!("pass{}", i))
                        .with_verdict(Verdict::Pass)
                );
            }

            for i in 0..failed {
                collector.record(
                    VerificationPath::new(format!("fail{}", i))
                        .with_verdict(Verdict::OutputMismatch {
                            expected: "a".into(),
                            actual: "b".into(),
                        })
                );
            }

            let stats = collector.stats();
            prop_assert_eq!(stats.total, passed + failed);
            prop_assert_eq!(stats.passed, passed);
            prop_assert_eq!(stats.failed, failed);
        }

        #[test]
        fn prop_to_bytes_deterministic(test_id in "[a-z]{1,20}") {
            let path1 = VerificationPath::new(&test_id);
            let path2 = VerificationPath::new(&test_id);

            let bytes1 = path1.to_bytes();
            let bytes2 = path2.to_bytes();

            prop_assert_eq!(bytes1, bytes2);
        }

        #[test]
        fn prop_confidence_bounded(verdict_type in 0u8..4) {
            let verdict = match verdict_type {
                0 => Verdict::Pass,
                1 => Verdict::OutputMismatch { expected: "a".into(), actual: "b".into() },
                2 => Verdict::Timeout { phase: Phase::Source, limit_ms: 5000 },
                _ => Verdict::RuntimeError { phase: Phase::Target, error: "err".into() },
            };

            let path = VerificationPath::new("test").with_verdict(verdict);
            let confidence = path.confidence();

            prop_assert!(confidence >= 0.0);
            prop_assert!(confidence <= 1.0);
        }
    }
}