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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
//! Provenance Validation (PMAT-PROV-001)
//!
//! Ensures all derived formats come from the same SafeTensors source.
//! Prevents the critical error of comparing models from different sources.
//!
//! See: docs/specifications/certified-testing.md Section 7.5

use crate::error::{Error, Result};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::fs::File;
use std::io::{BufReader, Read as IoRead};
use std::path::Path;

/// Source model provenance information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SourceProvenance {
    /// Format of source file (must be "safetensors" per spec 7.4)
    pub format: String,
    /// Relative path to source file
    pub path: String,
    /// SHA256 hash of source file
    pub sha256: String,
    /// HuggingFace repository ID (e.g., "Qwen/Qwen2.5-Coder-0.5B-Instruct")
    pub hf_repo: String,
    /// ISO 8601 timestamp of download
    pub downloaded_at: String,
}

/// Derived format provenance information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DerivedProvenance {
    /// Format of derived file (e.g., "gguf", "apr")
    pub format: String,
    /// Relative path to derived file
    pub path: String,
    /// SHA256 hash of derived file
    pub sha256: String,
    /// Converter used (must be "apr-cli" per spec 7.5.2)
    pub converter: String,
    /// Version of converter
    pub converter_version: String,
    /// Quantization applied (null for unquantized)
    pub quantization: Option<String>,
    /// ISO 8601 timestamp of conversion
    pub created_at: String,
}

/// Complete provenance record for a model directory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Provenance {
    /// Source model information
    pub source: SourceProvenance,
    /// Derived formats
    pub derived: Vec<DerivedProvenance>,
}

/// Provenance validation errors (PMAT-PROV-001)
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProvenanceError {
    /// PROV-001: Source hashes don't match across formats
    SourceMismatch {
        /// Expected source hash
        expected: String,
        /// Actual source hash found
        actual: String,
        /// Format with mismatched source
        format: String,
    },
    /// PROV-002: Derived file not created by apr-cli
    InvalidConverter {
        /// Format with invalid converter
        format: String,
        /// Converter that was used
        converter: String,
    },
    /// PROV-003: Source is not SafeTensors
    InvalidSourceFormat {
        /// Invalid source format found
        format: String,
    },
    /// PROV-004: Missing provenance file
    MissingProvenance {
        /// Path where provenance was expected
        path: String,
    },
    /// PROV-005: Quantization levels don't match
    QuantizationMismatch {
        /// First format in comparison
        format_a: String,
        /// Quantization of first format
        quant_a: Option<String>,
        /// Second format in comparison
        format_b: String,
        /// Quantization of second format
        quant_b: Option<String>,
    },
    /// PROV-006: File hash doesn't match recorded hash (integrity violation)
    HashMismatch {
        /// Path to file with mismatched hash
        path: String,
        /// Expected hash from provenance
        expected: String,
        /// Actual hash computed from file
        actual: String,
    },
    /// PROV-007: Referenced file does not exist (ghost file)
    FileMissing {
        /// Path to missing file
        path: String,
    },
    /// PROV-008: Duplicate derived format entry
    DuplicateDerived {
        /// Format that already exists
        format: String,
        /// Quantization level (if any)
        quantization: Option<String>,
    },
    /// PROV-009: Format not found in derived list
    FormatNotFound {
        /// Format that was requested but not found
        format: String,
    },
}

impl std::fmt::Display for ProvenanceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::SourceMismatch {
                expected,
                actual,
                format,
            } => {
                write!(
                    f,
                    "PROV-001: Source hash mismatch for {format}: expected {expected}, got {actual}"
                )
            }
            Self::InvalidConverter { format, converter } => {
                write!(
                    f,
                    "PROV-002: Invalid converter for {format}: {converter} (must be apr-cli)"
                )
            }
            Self::InvalidSourceFormat { format } => {
                write!(
                    f,
                    "PROV-003: Invalid source format: {format} (must be safetensors)"
                )
            }
            Self::MissingProvenance { path } => {
                write!(f, "PROV-004: Missing provenance file: {path}")
            }
            Self::QuantizationMismatch {
                format_a,
                quant_a,
                format_b,
                quant_b,
            } => {
                write!(
                    f,
                    "PROV-005: Quantization mismatch: {format_a}={quant_a:?} vs {format_b}={quant_b:?}"
                )
            }
            Self::HashMismatch {
                path,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "PROV-006: Hash mismatch for {path}: expected {expected}, got {actual}"
                )
            }
            Self::FileMissing { path } => {
                write!(f, "PROV-007: Referenced file missing: {path}")
            }
            Self::DuplicateDerived {
                format,
                quantization,
            } => {
                write!(
                    f,
                    "PROV-008: Duplicate derived format: {format} (quantization: {quantization:?})"
                )
            }
            Self::FormatNotFound { format } => {
                write!(f, "PROV-009: Format not found in derived list: {format}")
            }
        }
    }
}

impl std::error::Error for ProvenanceError {}

/// Load provenance from a model directory
///
/// # Errors
///
/// Returns error if provenance file is missing or malformed.
pub fn load_provenance(model_dir: &Path) -> Result<Provenance> {
    let provenance_path = model_dir.join(".provenance.json");
    if !provenance_path.exists() {
        return Err(Error::Provenance(ProvenanceError::MissingProvenance {
            path: provenance_path.display().to_string(),
        }));
    }

    let content = std::fs::read_to_string(&provenance_path)?;
    let provenance: Provenance = serde_json::from_str(&content)?;
    Ok(provenance)
}

/// Validate provenance for certification (PMAT-PROV-001)
///
/// Checks all rules from spec section 7.5.2:
/// - PROV-001: All formats share same source hash
/// - PROV-002: All derived files use apr-cli
/// - PROV-003: Source is safetensors
/// - PROV-004: Provenance file exists (checked by load_provenance)
/// - PROV-005: Quantization matches for comparisons
///
/// # Errors
///
/// Returns the first validation error encountered.
pub fn validate_provenance(provenance: &Provenance) -> std::result::Result<(), ProvenanceError> {
    // PROV-003: Source must be safetensors
    if provenance.source.format != "safetensors" {
        return Err(ProvenanceError::InvalidSourceFormat {
            format: provenance.source.format.clone(),
        });
    }

    // PROV-002: All derived files must use apr-cli
    for derived in &provenance.derived {
        if derived.converter != "apr-cli" {
            return Err(ProvenanceError::InvalidConverter {
                format: derived.format.clone(),
                converter: derived.converter.clone(),
            });
        }
    }

    Ok(())
}

/// Validate that two formats can be compared (same source, same quantization)
///
/// # Errors
///
/// Returns error if formats don't exist or have different quantization.
pub fn validate_comparison(
    provenance: &Provenance,
    format_a: &str,
    format_b: &str,
) -> std::result::Result<(), ProvenanceError> {
    // PROV-009: Both formats must exist in derived list
    let derived_a = provenance
        .derived
        .iter()
        .find(|d| d.format == format_a)
        .ok_or_else(|| ProvenanceError::FormatNotFound {
            format: format_a.to_string(),
        })?;

    let derived_b = provenance
        .derived
        .iter()
        .find(|d| d.format == format_b)
        .ok_or_else(|| ProvenanceError::FormatNotFound {
            format: format_b.to_string(),
        })?;

    // PROV-005: Quantization must match
    if derived_a.quantization != derived_b.quantization {
        return Err(ProvenanceError::QuantizationMismatch {
            format_a: format_a.to_string(),
            quant_a: derived_a.quantization.clone(),
            format_b: format_b.to_string(),
            quant_b: derived_b.quantization.clone(),
        });
    }

    Ok(())
}

/// Verify provenance integrity by re-hashing all files (PROV-006, PROV-007)
///
/// This function performs deep verification:
/// - Checks that all referenced files exist
/// - Re-computes SHA256 hashes and compares to recorded values
///
/// # Arguments
///
/// * `provenance` - The provenance record to verify
/// * `model_dir` - Base directory containing model files
///
/// # Errors
///
/// Returns error if any file is missing or hash doesn't match.
pub fn verify_provenance_integrity(
    provenance: &Provenance,
    model_dir: &Path,
) -> std::result::Result<(), ProvenanceError> {
    // Verify source file
    let source_path = model_dir.join(&provenance.source.path);
    if !source_path.exists() {
        return Err(ProvenanceError::FileMissing {
            path: provenance.source.path.clone(),
        });
    }

    let source_hash = compute_sha256(&source_path).map_err(|_| ProvenanceError::FileMissing {
        path: provenance.source.path.clone(),
    })?;

    if source_hash != provenance.source.sha256 {
        return Err(ProvenanceError::HashMismatch {
            path: provenance.source.path.clone(),
            expected: provenance.source.sha256.clone(),
            actual: source_hash,
        });
    }

    // Verify all derived files
    for derived in &provenance.derived {
        let derived_path = model_dir.join(&derived.path);
        if !derived_path.exists() {
            return Err(ProvenanceError::FileMissing {
                path: derived.path.clone(),
            });
        }

        let derived_hash =
            compute_sha256(&derived_path).map_err(|_| ProvenanceError::FileMissing {
                path: derived.path.clone(),
            })?;

        if derived_hash != derived.sha256 {
            return Err(ProvenanceError::HashMismatch {
                path: derived.path.clone(),
                expected: derived.sha256.clone(),
                actual: derived_hash,
            });
        }
    }

    Ok(())
}

/// Quick check that all referenced files exist (PROV-007)
///
/// Lighter than `verify_provenance_integrity` - only checks existence, not hashes.
///
/// # Errors
///
/// Returns error if any referenced file is missing.
pub fn verify_files_exist(
    provenance: &Provenance,
    model_dir: &Path,
) -> std::result::Result<(), ProvenanceError> {
    // Check source file
    let source_path = model_dir.join(&provenance.source.path);
    if !source_path.exists() {
        return Err(ProvenanceError::FileMissing {
            path: provenance.source.path.clone(),
        });
    }

    // Check all derived files
    for derived in &provenance.derived {
        let derived_path = model_dir.join(&derived.path);
        if !derived_path.exists() {
            return Err(ProvenanceError::FileMissing {
                path: derived.path.clone(),
            });
        }
    }

    Ok(())
}

// ============================================================================
// Provenance Generation (PMAT-PROV-001)
// ============================================================================

/// Compute SHA256 hash of a file
///
/// # Errors
///
/// Returns error if file cannot be read.
pub fn compute_sha256(path: &Path) -> Result<String> {
    let file = File::open(path)?;
    let mut reader = BufReader::new(file);
    let mut hasher = Sha256::new();

    let mut buffer = [0u8; 8192];
    loop {
        let bytes_read = reader.read(&mut buffer)?;
        if bytes_read == 0 {
            break;
        }
        hasher.update(&buffer[..bytes_read]);
    }

    let result = hasher.finalize();
    Ok(format!("{result:x}"))
}

/// Create initial provenance for a SafeTensors source file
///
/// # Errors
///
/// Returns error if file cannot be read or hashed.
pub fn create_source_provenance(safetensors_path: &Path, hf_repo: &str) -> Result<Provenance> {
    let sha256 = compute_sha256(safetensors_path)?;
    let now = chrono::Utc::now().to_rfc3339();

    Ok(Provenance {
        source: SourceProvenance {
            format: "safetensors".to_string(),
            path: safetensors_path.file_name().map_or_else(
                || safetensors_path.display().to_string(),
                |n| n.to_string_lossy().to_string(),
            ),
            sha256,
            hf_repo: hf_repo.to_string(),
            downloaded_at: now,
        },
        derived: Vec::new(),
    })
}

/// Add a derived format to provenance
///
/// Checks for duplicate entries (same format + quantization) before adding.
///
/// # Errors
///
/// Returns error if:
/// - Derived file cannot be read or hashed
/// - Duplicate format+quantization already exists (PROV-008)
pub fn add_derived(
    provenance: &mut Provenance,
    format: &str,
    derived_path: &Path,
    quantization: Option<&str>,
    converter_version: &str,
) -> Result<()> {
    // PROV-008: Check for duplicate format+quantization
    let exists = provenance
        .derived
        .iter()
        .any(|d| d.format == format && d.quantization.as_deref() == quantization);

    if exists {
        return Err(Error::Provenance(ProvenanceError::DuplicateDerived {
            format: format.to_string(),
            quantization: quantization.map(String::from),
        }));
    }

    let sha256 = compute_sha256(derived_path)?;
    let now = chrono::Utc::now().to_rfc3339();

    provenance.derived.push(DerivedProvenance {
        format: format.to_string(),
        path: derived_path.file_name().map_or_else(
            || derived_path.display().to_string(),
            |n| n.to_string_lossy().to_string(),
        ),
        sha256,
        converter: "apr-cli".to_string(),
        converter_version: converter_version.to_string(),
        quantization: quantization.map(String::from),
        created_at: now,
    });

    Ok(())
}

/// Save provenance to a model directory
///
/// # Errors
///
/// Returns error if provenance cannot be serialized or written.
pub fn save_provenance(model_dir: &Path, provenance: &Provenance) -> Result<()> {
    let provenance_path = model_dir.join(".provenance.json");
    let content = serde_json::to_string_pretty(provenance)?;
    std::fs::write(provenance_path, content)?;
    Ok(())
}

/// Get apr-cli version by running `apr --version`
///
/// Returns "unknown" if command fails.
#[must_use]
pub fn get_apr_cli_version() -> String {
    std::process::Command::new("apr")
        .arg("--version")
        .output()
        .ok()
        .and_then(|output| {
            if output.status.success() {
                String::from_utf8(output.stdout)
                    .ok()
                    .and_then(|s| s.split_whitespace().nth(1).map(String::from))
            } else {
                None
            }
        })
        .unwrap_or_else(|| "unknown".to_string())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn sample_provenance() -> Provenance {
        Provenance {
            source: SourceProvenance {
                format: "safetensors".to_string(),
                path: "model.safetensors".to_string(),
                sha256: "a1b2c3d4e5f6".to_string(),
                hf_repo: "Qwen/Qwen2.5-Coder-0.5B-Instruct".to_string(),
                downloaded_at: "2026-02-01T12:00:00Z".to_string(),
            },
            derived: vec![
                DerivedProvenance {
                    format: "gguf".to_string(),
                    path: "model.gguf".to_string(),
                    sha256: "f6e5d4c3b2a1".to_string(),
                    converter: "apr-cli".to_string(),
                    converter_version: "0.2.12".to_string(),
                    quantization: None,
                    created_at: "2026-02-01T12:05:00Z".to_string(),
                },
                DerivedProvenance {
                    format: "apr".to_string(),
                    path: "model.apr".to_string(),
                    sha256: "1a2b3c4d5e6f".to_string(),
                    converter: "apr-cli".to_string(),
                    converter_version: "0.2.12".to_string(),
                    quantization: None,
                    created_at: "2026-02-01T12:06:00Z".to_string(),
                },
            ],
        }
    }

    // PMAT-PROV-001: Reject certification with mismatched sources
    #[test]
    fn test_reject_mismatched_source_hash() {
        // This would be detected by comparing provenance files
        // from different model directories
        let prov_a = sample_provenance();
        let mut prov_b = sample_provenance();
        prov_b.source.sha256 = "different_hash".to_string();

        // Different source hashes should fail comparison
        assert_ne!(prov_a.source.sha256, prov_b.source.sha256);
    }

    // PMAT-PROV-002: Reject third-party files without provenance
    #[test]
    fn test_reject_third_party_gguf() {
        let mut prov = sample_provenance();
        prov.derived[0].converter = "bartowski".to_string(); // Third-party

        let result = validate_provenance(&prov);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ProvenanceError::InvalidConverter { .. }));
    }

    // PMAT-PROV-003: Accept only SafeTensors as source
    #[test]
    fn test_reject_gguf_as_source() {
        let mut prov = sample_provenance();
        prov.source.format = "gguf".to_string(); // Wrong source format

        let result = validate_provenance(&prov);
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ProvenanceError::InvalidSourceFormat { .. }));
    }

    // PMAT-PROV-004: Reject quantization mismatch
    #[test]
    fn test_reject_quantization_mismatch() {
        let mut prov = sample_provenance();
        prov.derived[0].quantization = Some("q4_k_m".to_string()); // GGUF quantized
        prov.derived[1].quantization = None; // APR unquantized

        let result = validate_comparison(&prov, "gguf", "apr");
        assert!(result.is_err());

        let err = result.unwrap_err();
        assert!(matches!(err, ProvenanceError::QuantizationMismatch { .. }));
    }

    #[test]
    fn test_valid_provenance_passes() {
        let prov = sample_provenance();
        assert!(validate_provenance(&prov).is_ok());
    }

    #[test]
    fn test_valid_comparison_same_quantization() {
        let prov = sample_provenance();
        assert!(validate_comparison(&prov, "gguf", "apr").is_ok());
    }

    #[test]
    fn test_valid_comparison_both_quantized() {
        let mut prov = sample_provenance();
        prov.derived[0].quantization = Some("q4_k_m".to_string());
        prov.derived[1].quantization = Some("q4_k_m".to_string());

        assert!(validate_comparison(&prov, "gguf", "apr").is_ok());
    }

    #[test]
    fn test_provenance_error_display() {
        let err = ProvenanceError::InvalidSourceFormat {
            format: "gguf".to_string(),
        };
        assert!(err.to_string().contains("PROV-003"));
        assert!(err.to_string().contains("safetensors"));
    }

    #[test]
    fn test_source_mismatch_error_display() {
        let err = ProvenanceError::SourceMismatch {
            expected: "abc123".to_string(),
            actual: "def456".to_string(),
            format: "apr".to_string(),
        };
        assert!(err.to_string().contains("PROV-001"));
        assert!(err.to_string().contains("abc123"));
    }

    // ========================================================================
    // Provenance Generation Tests
    // ========================================================================

    #[test]
    fn test_compute_sha256() {
        let dir = tempfile::tempdir().unwrap();
        let test_file = dir.path().join("test.txt");
        std::fs::write(&test_file, "hello world\n").unwrap();

        let hash = compute_sha256(&test_file).unwrap();
        // SHA256 of "hello world\n"
        assert_eq!(
            hash,
            "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447"
        );
    }

    #[test]
    fn test_compute_sha256_empty_file() {
        let dir = tempfile::tempdir().unwrap();
        let test_file = dir.path().join("empty.txt");
        std::fs::write(&test_file, "").unwrap();

        let hash = compute_sha256(&test_file).unwrap();
        // SHA256 of empty string
        assert_eq!(
            hash,
            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
        );
    }

    #[test]
    fn test_compute_sha256_missing_file() {
        let result = compute_sha256(Path::new("/nonexistent/file.bin"));
        assert!(result.is_err());
    }

    #[test]
    fn test_create_source_provenance() {
        let dir = tempfile::tempdir().unwrap();
        let safetensors = dir.path().join("model.safetensors");
        std::fs::write(&safetensors, "fake safetensors content").unwrap();

        let prov =
            create_source_provenance(&safetensors, "Qwen/Qwen2.5-Coder-0.5B-Instruct").unwrap();

        assert_eq!(prov.source.format, "safetensors");
        assert_eq!(prov.source.path, "model.safetensors");
        assert_eq!(prov.source.hf_repo, "Qwen/Qwen2.5-Coder-0.5B-Instruct");
        assert!(!prov.source.sha256.is_empty());
        assert!(!prov.source.downloaded_at.is_empty());
        assert!(prov.derived.is_empty());
    }

    #[test]
    fn test_add_derived() {
        let dir = tempfile::tempdir().unwrap();
        let safetensors = dir.path().join("model.safetensors");
        let gguf = dir.path().join("model.gguf");
        std::fs::write(&safetensors, "safetensors content").unwrap();
        std::fs::write(&gguf, "gguf content").unwrap();

        let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();
        add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();

        assert_eq!(prov.derived.len(), 1);
        assert_eq!(prov.derived[0].format, "gguf");
        assert_eq!(prov.derived[0].path, "model.gguf");
        assert_eq!(prov.derived[0].converter, "apr-cli");
        assert_eq!(prov.derived[0].converter_version, "0.2.12");
        assert!(prov.derived[0].quantization.is_none());
    }

    #[test]
    fn test_add_derived_with_quantization() {
        let dir = tempfile::tempdir().unwrap();
        let safetensors = dir.path().join("model.safetensors");
        let gguf_q4 = dir.path().join("model-q4_k_m.gguf");
        std::fs::write(&safetensors, "safetensors content").unwrap();
        std::fs::write(&gguf_q4, "quantized gguf content").unwrap();

        let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();
        add_derived(&mut prov, "gguf", &gguf_q4, Some("q4_k_m"), "0.2.12").unwrap();

        assert_eq!(prov.derived[0].quantization, Some("q4_k_m".to_string()));
    }

    #[test]
    fn test_save_and_load_provenance() {
        let dir = tempfile::tempdir().unwrap();
        let safetensors = dir.path().join("model.safetensors");
        std::fs::write(&safetensors, "content").unwrap();

        let prov = create_source_provenance(&safetensors, "test/model").unwrap();
        save_provenance(dir.path(), &prov).unwrap();

        let loaded = load_provenance(dir.path()).unwrap();
        assert_eq!(loaded.source.hf_repo, "test/model");
        assert_eq!(loaded.source.sha256, prov.source.sha256);
    }

    #[test]
    fn test_save_provenance_creates_json() {
        let dir = tempfile::tempdir().unwrap();
        let safetensors = dir.path().join("model.safetensors");
        std::fs::write(&safetensors, "content").unwrap();

        let prov = create_source_provenance(&safetensors, "test/model").unwrap();
        save_provenance(dir.path(), &prov).unwrap();

        let prov_path = dir.path().join(".provenance.json");
        assert!(prov_path.exists());

        let content = std::fs::read_to_string(&prov_path).unwrap();
        assert!(content.contains("\"format\": \"safetensors\""));
        assert!(content.contains("test/model"));
    }

    #[test]
    fn test_full_provenance_workflow() {
        let dir = tempfile::tempdir().unwrap();

        // Create source
        let safetensors = dir.path().join("model.safetensors");
        std::fs::write(&safetensors, "source content").unwrap();

        // Create derived formats
        let gguf = dir.path().join("model.gguf");
        let apr = dir.path().join("model.apr");
        std::fs::write(&gguf, "gguf content").unwrap();
        std::fs::write(&apr, "apr content").unwrap();

        // Build provenance
        let mut prov =
            create_source_provenance(&safetensors, "Qwen/Qwen2.5-Coder-0.5B-Instruct").unwrap();
        add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();
        add_derived(&mut prov, "apr", &apr, None, "0.2.12").unwrap();

        // Validate provenance
        assert!(validate_provenance(&prov).is_ok());

        // Validate comparison
        assert!(validate_comparison(&prov, "gguf", "apr").is_ok());

        // Save and reload
        save_provenance(dir.path(), &prov).unwrap();
        let loaded = load_provenance(dir.path()).unwrap();

        // Revalidate after reload
        assert!(validate_provenance(&loaded).is_ok());
    }

    #[test]
    fn test_get_apr_cli_version_returns_string() {
        // This test just verifies the function doesn't panic
        // In CI where apr isn't installed, it returns "unknown"
        let version = get_apr_cli_version();
        assert!(!version.is_empty());
    }

    // ========================================================================
    // FALSIFICATION TESTS (PMAT-PROV-001)
    // Operation "Trust No One" - Popperian Falsification
    // ========================================================================

    mod falsification {
        use super::*;

        // ====================================================================
        // Vector A: Integrity Attacks (Physical Artifacts)
        // ====================================================================

        /// F-PROV-IO-001: The "Bit Flip" - corrupt SHA256 hash
        /// Expected: verify_provenance_integrity() MUST detect mismatch (PROV-006)
        #[test]
        fn f_prov_io_001_bit_flip_hash() {
            let dir = tempfile::tempdir().unwrap();

            // Create real files and valid provenance
            let safetensors = dir.path().join("model.safetensors");
            std::fs::write(&safetensors, "source content").unwrap();
            let prov = create_source_provenance(&safetensors, "test/model").unwrap();
            save_provenance(dir.path(), &prov).unwrap();

            // Manually corrupt the hash in the file
            let prov_path = dir.path().join(".provenance.json");
            let content = std::fs::read_to_string(&prov_path).unwrap();
            let corrupted = content.replace(&prov.source.sha256, "CORRUPTED_HASH");
            std::fs::write(&prov_path, corrupted).unwrap();

            // Load provenance (JSON is valid, just hash is wrong)
            let loaded = load_provenance(dir.path()).unwrap();

            // Basic validation still passes (format/converter checks)
            assert!(validate_provenance(&loaded).is_ok());

            // FIX VERIFIED: verify_provenance_integrity() detects the corruption
            let integrity_result = verify_provenance_integrity(&loaded, dir.path());
            assert!(integrity_result.is_err());
            assert!(matches!(
                integrity_result.unwrap_err(),
                ProvenanceError::HashMismatch { .. }
            ));
        }

        /// F-PROV-IO-002: The "Truncation" - partial JSON
        /// Expected: load_provenance() returns robust error, no panic
        #[test]
        fn f_prov_io_002_truncated_json() {
            let dir = tempfile::tempdir().unwrap();
            let prov_path = dir.path().join(".provenance.json");

            // Write truncated JSON (simulate power loss)
            std::fs::write(&prov_path, r#"{"source": {"format": "safetens"#).unwrap();

            let result = load_provenance(dir.path());

            // CORROBORATED: Returns error, does not panic
            assert!(result.is_err());
            // Verify it's a serialization error, not a panic
            let err = result.unwrap_err();
            assert!(matches!(err, Error::SerializationError(_)));
        }

        /// F-PROV-IO-003: The "Ghost File" - model file deleted but provenance exists
        /// Expected: verify_files_exist() detects missing file (PROV-007)
        #[test]
        fn f_prov_io_003_ghost_file() {
            let dir = tempfile::tempdir().unwrap();

            // Create source file and provenance
            let safetensors = dir.path().join("model.safetensors");
            std::fs::write(&safetensors, "content").unwrap();
            let prov = create_source_provenance(&safetensors, "test/model").unwrap();
            save_provenance(dir.path(), &prov).unwrap();

            // Delete the model file (ghost it)
            std::fs::remove_file(&safetensors).unwrap();

            // Load provenance - still works (JSON exists)
            let loaded = load_provenance(dir.path()).unwrap();

            // Basic validation still passes (format/converter checks)
            assert!(validate_provenance(&loaded).is_ok());

            // FIX VERIFIED: verify_files_exist() detects the ghost
            let exist_result = verify_files_exist(&loaded, dir.path());
            assert!(exist_result.is_err());
            assert!(matches!(
                exist_result.unwrap_err(),
                ProvenanceError::FileMissing { .. }
            ));

            // FIX VERIFIED: verify_provenance_integrity() also detects it
            let integrity_result = verify_provenance_integrity(&loaded, dir.path());
            assert!(integrity_result.is_err());
            assert!(matches!(
                integrity_result.unwrap_err(),
                ProvenanceError::FileMissing { .. }
            ));
        }

        /// F-PROV-IO-004: The "Hash Collision" - empty file hash
        /// Expected: Correct hash for empty file, no panic
        #[test]
        fn f_prov_io_004_empty_file_hash() {
            let dir = tempfile::tempdir().unwrap();
            let empty_file = dir.path().join("empty.bin");
            std::fs::write(&empty_file, "").unwrap();

            let hash = compute_sha256(&empty_file).unwrap();

            // CORROBORATED: Returns correct SHA256 for empty file
            assert_eq!(
                hash,
                "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
            );
        }

        // ====================================================================
        // Vector B: Logic Bypass (Validation Rules)
        // ====================================================================

        /// F-PROV-LOGIC-001: The "Imposter Source" - GGUF as source format
        /// Expected: Validation fails (Ground Truth Policy 7.4)
        #[test]
        fn f_prov_logic_001_imposter_source() {
            let mut prov = sample_provenance();
            prov.source.format = "gguf".to_string(); // Violate 7.4

            let result = validate_provenance(&prov);

            // CORROBORATED: Correctly rejects GGUF as source
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                ProvenanceError::InvalidSourceFormat { .. }
            ));
        }

        /// F-PROV-LOGIC-002: The "Rogue Converter"
        /// Expected: validate_provenance() fails (PROV-002)
        #[test]
        fn f_prov_logic_002_rogue_converter() {
            let mut prov = sample_provenance();
            prov.derived[0].converter = "suspicious-script v0.1".to_string();

            let result = validate_provenance(&prov);

            // CORROBORATED: Correctly rejects non-apr-cli converter
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                ProvenanceError::InvalidConverter { .. }
            ));
        }

        /// F-PROV-LOGIC-003: The "Quantization Lie"
        /// Expected: If we lie in JSON, can we compare apples to oranges?
        #[test]
        fn f_prov_logic_003_quantization_lie() {
            let mut prov = sample_provenance();

            // Lie: Say both are Q4_K_M but actual files would be different
            prov.derived[0].quantization = Some("q4_k_m".to_string());
            prov.derived[1].quantization = Some("q4_k_m".to_string());

            // System only checks JSON, not actual file headers
            let result = validate_comparison(&prov, "gguf", "apr");

            // OBSERVATION: Comparison passes because JSON claims match
            assert!(result.is_ok());

            // FALSIFIED: We can lie in metadata and bypass quantization check
            // The system does NOT verify actual file quantization headers
            // P0 TICKET REQUIRED: No verification of claimed vs actual quantization
        }

        /// F-PROV-LOGIC-004: Case sensitivity attack on format
        #[test]
        fn f_prov_logic_004_case_sensitivity() {
            let mut prov = sample_provenance();
            prov.source.format = "SafeTensors".to_string(); // Wrong case

            let result = validate_provenance(&prov);

            // CORROBORATED: Correctly rejects wrong case
            // (string comparison is case-sensitive)
            assert!(result.is_err());
        }

        /// F-PROV-LOGIC-005: Empty converter string
        #[test]
        fn f_prov_logic_005_empty_converter() {
            let mut prov = sample_provenance();
            prov.derived[0].converter = String::new();

            let result = validate_provenance(&prov);

            // CORROBORATED: Empty string != "apr-cli"
            assert!(result.is_err());
        }

        /// F-PROV-LOGIC-006: Converter with whitespace prefix
        #[test]
        fn f_prov_logic_006_whitespace_converter() {
            let mut prov = sample_provenance();
            prov.derived[0].converter = " apr-cli".to_string(); // Leading space

            let result = validate_provenance(&prov);

            // CORROBORATED: " apr-cli" != "apr-cli"
            assert!(result.is_err());
        }

        // ====================================================================
        // Vector C: Workflow Sabotage
        // ====================================================================

        /// F-PROV-FLOW-001: The "Time Traveler" - future timestamp
        #[test]
        fn f_prov_flow_001_future_timestamp() {
            let mut prov = sample_provenance();
            prov.source.downloaded_at = "2099-12-31T23:59:59Z".to_string();

            // OBSERVATION: No timestamp validation exists
            let result = validate_provenance(&prov);
            assert!(result.is_ok());

            // FALSIFIED: Future timestamps accepted without warning
            // Minor issue - could indicate clock manipulation
        }

        /// F-PROV-FLOW-002: The "Race Condition" - concurrent writes
        #[test]
        fn f_prov_flow_002_race_condition() {
            use std::sync::Arc;
            use std::thread;

            let dir = tempfile::tempdir().unwrap();
            let dir_path = Arc::new(dir.path().to_path_buf());

            let mut handles = vec![];

            for i in 0..10 {
                let path = Arc::clone(&dir_path);
                handles.push(thread::spawn(move || {
                    let mut prov = sample_provenance();
                    prov.source.sha256 = format!("hash_{i}");
                    save_provenance(&path, &prov).unwrap();
                }));
            }

            for handle in handles {
                handle.join().unwrap();
            }

            // Load and verify - should have ONE consistent state
            let loaded = load_provenance(&dir_path).unwrap();

            // OBSERVATION: No file locking, last writer wins
            // Result is non-deterministic but at least valid JSON
            assert!(validate_provenance(&loaded).is_ok());

            // CORROBORATED (with caveat): No corruption, but no atomicity guarantee
            // Recommend: atomic write (write to .tmp, then rename)
        }

        /// F-PROV-FLOW-003: The "Version Spoof" - empty version
        #[test]
        fn f_prov_flow_003_empty_version() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let derived = dir.path().join("model.gguf");
            std::fs::write(&safetensors, "source").unwrap();
            std::fs::write(&derived, "derived").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();

            // Add derived with empty version
            add_derived(&mut prov, "gguf", &derived, None, "").unwrap();

            // OBSERVATION: Empty version string is accepted
            assert!(validate_provenance(&prov).is_ok());
            assert!(prov.derived[0].converter_version.is_empty());

            // FALSIFIED: No validation that version is non-empty
            // Minor issue - could indicate tampering
        }

        // ====================================================================
        // Vector D: Code Mutation (White Box)
        // ====================================================================

        /// F-PROV-CODE-001: Add same derived model twice
        /// Expected: add_derived() rejects duplicate (PROV-008)
        #[test]
        fn f_prov_code_001_duplicate_derived() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let gguf = dir.path().join("model.gguf");
            std::fs::write(&safetensors, "source").unwrap();
            std::fs::write(&gguf, "derived").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();

            // Add GGUF first time - succeeds
            add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();
            assert_eq!(prov.derived.len(), 1);

            // FIX VERIFIED: Second add fails with DuplicateDerived error
            let result = add_derived(&mut prov, "gguf", &gguf, None, "0.2.12");
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                Error::Provenance(ProvenanceError::DuplicateDerived { .. })
            ));

            // Still only one entry
            assert_eq!(prov.derived.len(), 1);
        }

        /// F-PROV-CODE-001b: Different quantization = not a duplicate
        #[test]
        fn f_prov_code_001b_different_quantization_allowed() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let gguf = dir.path().join("model.gguf");
            let gguf_q4 = dir.path().join("model-q4.gguf");
            std::fs::write(&safetensors, "source").unwrap();
            std::fs::write(&gguf, "derived").unwrap();
            std::fs::write(&gguf_q4, "derived q4").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();

            // Add unquantized GGUF
            add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();

            // Add quantized GGUF - different quantization = allowed
            add_derived(&mut prov, "gguf", &gguf_q4, Some("q4_k_m"), "0.2.12").unwrap();

            // Both entries exist
            assert_eq!(prov.derived.len(), 2);
        }

        /// F-PROV-CODE-002: Feed non-provenance JSON
        #[test]
        fn f_prov_code_002_wrong_json_schema() {
            let dir = tempfile::tempdir().unwrap();
            let prov_path = dir.path().join(".provenance.json");

            // Write valid JSON but wrong schema
            std::fs::write(&prov_path, r#"{"hello": "world"}"#).unwrap();

            let result = load_provenance(dir.path());

            // CORROBORATED: Returns deserialization error
            assert!(result.is_err());
            assert!(matches!(result.unwrap_err(), Error::SerializationError(_)));
        }

        /// F-PROV-CODE-003: Unicode in fields
        #[test]
        fn f_prov_code_003_unicode_injection() {
            let mut prov = sample_provenance();
            prov.source.hf_repo = "test/模型".to_string(); // Chinese characters
            prov.derived[0].path = "model_مدل.gguf".to_string(); // Arabic

            // Should handle unicode gracefully
            let result = validate_provenance(&prov);
            assert!(result.is_ok());

            // Serialize and deserialize
            let json = serde_json::to_string(&prov).unwrap();
            let loaded: Provenance = serde_json::from_str(&json).unwrap();
            assert_eq!(loaded.source.hf_repo, "test/模型");

            // CORROBORATED: Unicode handled correctly
        }

        /// F-PROV-CODE-004: Very long strings (buffer overflow attempt)
        #[test]
        fn f_prov_code_004_long_strings() {
            let mut prov = sample_provenance();
            prov.source.sha256 = "a".repeat(1_000_000); // 1MB hash string

            // Should not panic or OOM on validation
            let result = validate_provenance(&prov);
            assert!(result.is_ok());

            // CORROBORATED: Long strings handled (though invalid hash)
            // Note: No hash format validation exists
        }

        /// F-PROV-CODE-005: Null bytes in strings
        #[test]
        fn f_prov_code_005_null_bytes() {
            let mut prov = sample_provenance();
            prov.source.path = "model\0.safetensors".to_string();

            // Should handle embedded nulls
            let result = validate_provenance(&prov);
            assert!(result.is_ok());

            let json = serde_json::to_string(&prov).unwrap();
            let loaded: Provenance = serde_json::from_str(&json).unwrap();
            assert!(loaded.source.path.contains('\0'));

            // CORROBORATED: Null bytes preserved (could be path traversal risk)
        }

        /// F-PROV-CODE-006: Empty derived list
        /// Expected: validate_comparison() fails for missing formats (PROV-009)
        #[test]
        fn f_prov_code_006_empty_derived() {
            let mut prov = sample_provenance();
            prov.derived.clear();

            // Provenance with no derived formats is valid (source only)
            let result = validate_provenance(&prov);
            assert!(result.is_ok());

            // FIX VERIFIED: Comparison fails when formats don't exist
            let cmp_result = validate_comparison(&prov, "gguf", "apr");
            assert!(cmp_result.is_err());
            assert!(matches!(
                cmp_result.unwrap_err(),
                ProvenanceError::FormatNotFound { .. }
            ));
        }

        /// F-PROV-CODE-007: Comparison with non-existent format
        /// Expected: validate_comparison() fails with FormatNotFound (PROV-009)
        #[test]
        fn f_prov_code_007_phantom_format_comparison() {
            let prov = sample_provenance();

            // Compare format that doesn't exist
            let result = validate_comparison(&prov, "gguf", "phantom_format");

            // FIX VERIFIED: Returns FormatNotFound error
            assert!(result.is_err());
            let err = result.unwrap_err();
            assert!(
                matches!(err, ProvenanceError::FormatNotFound { format } if format == "phantom_format")
            );
        }

        // ====================================================================
        // New Tests for Verification Functions
        // ====================================================================

        /// Test verify_provenance_integrity with valid files
        #[test]
        fn test_verify_integrity_valid() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let gguf = dir.path().join("model.gguf");
            std::fs::write(&safetensors, "source content").unwrap();
            std::fs::write(&gguf, "gguf content").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();
            add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();

            // All files exist and hashes match
            let result = verify_provenance_integrity(&prov, dir.path());
            assert!(result.is_ok());
        }

        /// Test verify_provenance_integrity detects modified source
        #[test]
        fn test_verify_integrity_modified_source() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            std::fs::write(&safetensors, "original content").unwrap();

            let prov = create_source_provenance(&safetensors, "test/model").unwrap();

            // Modify the source file after provenance creation
            std::fs::write(&safetensors, "MODIFIED content").unwrap();

            // Integrity check fails
            let result = verify_provenance_integrity(&prov, dir.path());
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                ProvenanceError::HashMismatch { .. }
            ));
        }

        /// Test verify_provenance_integrity detects modified derived file
        #[test]
        fn test_verify_integrity_modified_derived() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let gguf = dir.path().join("model.gguf");
            std::fs::write(&safetensors, "source").unwrap();
            std::fs::write(&gguf, "original gguf").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();
            add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();

            // Modify derived file
            std::fs::write(&gguf, "TAMPERED gguf").unwrap();

            let result = verify_provenance_integrity(&prov, dir.path());
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                ProvenanceError::HashMismatch { .. }
            ));
        }

        /// Test verify_files_exist with all files present
        #[test]
        fn test_verify_files_exist_valid() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let gguf = dir.path().join("model.gguf");
            std::fs::write(&safetensors, "source").unwrap();
            std::fs::write(&gguf, "gguf").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();
            add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();

            assert!(verify_files_exist(&prov, dir.path()).is_ok());
        }

        /// Test verify_files_exist detects missing derived file
        #[test]
        fn test_verify_files_exist_missing_derived() {
            let dir = tempfile::tempdir().unwrap();
            let safetensors = dir.path().join("model.safetensors");
            let gguf = dir.path().join("model.gguf");
            std::fs::write(&safetensors, "source").unwrap();
            std::fs::write(&gguf, "gguf").unwrap();

            let mut prov = create_source_provenance(&safetensors, "test/model").unwrap();
            add_derived(&mut prov, "gguf", &gguf, None, "0.2.12").unwrap();

            // Delete derived file
            std::fs::remove_file(&gguf).unwrap();

            let result = verify_files_exist(&prov, dir.path());
            assert!(result.is_err());
            assert!(matches!(
                result.unwrap_err(),
                ProvenanceError::FileMissing { .. }
            ));
        }

        /// Test new error display messages
        #[test]
        fn test_new_error_displays() {
            let err = ProvenanceError::HashMismatch {
                path: "model.gguf".to_string(),
                expected: "abc123".to_string(),
                actual: "def456".to_string(),
            };
            assert!(err.to_string().contains("PROV-006"));

            let err = ProvenanceError::FileMissing {
                path: "model.safetensors".to_string(),
            };
            assert!(err.to_string().contains("PROV-007"));

            let err = ProvenanceError::DuplicateDerived {
                format: "gguf".to_string(),
                quantization: Some("q4_k_m".to_string()),
            };
            assert!(err.to_string().contains("PROV-008"));

            let err = ProvenanceError::FormatNotFound {
                format: "phantom".to_string(),
            };
            assert!(err.to_string().contains("PROV-009"));
        }
    }
}