hl7v2 1.5.0

HL7 v2 message parser and processor for Rust
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
//! Evidence bundle and replay helpers.
//!
//! These helpers back evidence-grade workflows that combine redaction,
//! profile validation, artifact manifests, and replay verification.

use crate::conformance::profile::{load_profile_checked, validate};
use crate::conformance::validation::ValidationReport;
use crate::model::{Atom, Field, Message};
use crate::parser::parse;
use crate::redact::{RedactionAction, RedactionError, RedactionReceipt, redact_hl7_safe_analysis};
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Component, Path, PathBuf};

const BUNDLE_VERSION: &str = "1";
const REPLAY_VERSION: &str = "1";
const REPLAY_COMMAND: &str = "hl7v2 replay . --format json";
const BUNDLE_ARTIFACT_SPECS: [(&str, &str); 9] = [
    ("message.redacted.hl7", "redacted_message"),
    ("validation-report.json", "validation_report"),
    ("field-paths.json", "field_path_trace"),
    ("profile.yaml", "profile"),
    ("redaction-receipt.json", "redaction_receipt"),
    ("environment.json", "environment"),
    ("replay.sh", "replay_shell_script"),
    ("replay.ps1", "replay_powershell_script"),
    ("README.md", "bundle_readme"),
];

/// Machine-readable summary returned after writing an evidence bundle.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleSummary {
    /// Evidence bundle contract version.
    pub bundle_version: String,
    /// Bundle output directory label. This is `.` for local Python-created bundles.
    pub output_dir: String,
    /// Message type from the raw input message.
    pub message_type: String,
    /// Whether validation passed after redaction.
    pub validation_valid: bool,
    /// Number of validation issues generated from the redacted message.
    pub validation_issue_count: usize,
    /// Whether the redaction policy removed or hashed PHI-bearing fields.
    pub redaction_phi_removed: bool,
    /// Bundle-relative artifact names written by this helper.
    pub artifacts: Vec<String>,
}

impl EvidenceBundleSummary {
    /// Convert this v1 bundle summary into the explicit v2 evidence contract shape.
    ///
    /// This preserves the default serialized form of [`EvidenceBundleSummary`].
    /// Producers opt into v2 when they are ready to emit embedded provenance.
    #[must_use]
    pub fn to_v2(
        &self,
        tool_name: impl Into<String>,
        tool_version: impl Into<String>,
    ) -> EvidenceBundleSummaryV2 {
        EvidenceBundleSummaryV2 {
            schema_version: "2".to_string(),
            tool_name: tool_name.into(),
            tool_version: tool_version.into(),
            summary: self.clone(),
        }
    }
}

/// Evidence bundle summary v2 with embedded evidence provenance.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleSummaryV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// Producer surface that generated this bundle summary.
    pub tool_name: String,
    /// Producer package version.
    pub tool_version: String,
    /// V1 bundle summary fields.
    #[serde(flatten)]
    pub summary: EvidenceBundleSummary,
}

/// Evidence bundle manifest written inside the bundle directory.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleManifest {
    /// Evidence bundle contract version.
    pub bundle_version: String,
    /// Tool that generated this bundle.
    pub tool_name: String,
    /// Tool version that generated this bundle.
    pub tool_version: String,
    /// Bundle-relative artifact entries.
    pub artifacts: Vec<EvidenceBundleManifestArtifact>,
}

impl EvidenceBundleManifest {
    /// Convert this v1 bundle manifest into the explicit v2 evidence contract shape.
    #[must_use]
    pub fn to_v2(&self) -> EvidenceBundleManifestV2 {
        EvidenceBundleManifestV2 {
            schema_version: "2".to_string(),
            manifest: self.clone(),
        }
    }
}

/// Evidence bundle manifest v2 with embedded schema provenance.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleManifestV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// V1 bundle manifest fields.
    #[serde(flatten)]
    pub manifest: EvidenceBundleManifest,
}

/// Evidence bundle manifest artifact entry.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleManifestArtifact {
    /// Bundle-relative artifact path.
    pub path: String,
    /// Stable artifact role.
    pub role: String,
    /// SHA-256 digest of the artifact bytes.
    pub sha256: String,
}

/// Environment metadata written inside an evidence bundle.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleEnvironment {
    /// Evidence bundle contract version.
    pub bundle_version: String,
    /// Tool that generated this bundle.
    pub tool_name: String,
    /// Tool version that generated this bundle.
    pub tool_version: String,
    /// Message type from the raw message.
    pub message_type: String,
    /// SHA-256 digest of the raw input message.
    pub input_sha256: String,
    /// SHA-256 digest of the profile YAML.
    pub profile_sha256: String,
    /// SHA-256 digest of the redaction policy TOML.
    pub redaction_policy_sha256: String,
    /// Whether validation passed after redaction.
    pub validation_valid: bool,
    /// Number of validation issues generated from the redacted message.
    pub validation_issue_count: usize,
    /// Replay command for validating the bundled artifacts.
    pub replay_command: String,
}

impl EvidenceBundleEnvironment {
    /// Convert this v1 bundle environment into the explicit v2 evidence contract shape.
    #[must_use]
    pub fn to_v2(&self) -> EvidenceBundleEnvironmentV2 {
        EvidenceBundleEnvironmentV2 {
            schema_version: "2".to_string(),
            environment: self.clone(),
        }
    }
}

/// Evidence bundle environment v2 with embedded schema provenance.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceBundleEnvironmentV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// V1 bundle environment fields.
    #[serde(flatten)]
    pub environment: EvidenceBundleEnvironment,
}

/// Field-path trace written inside an evidence bundle.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FieldPathTraceReport {
    /// HL7 trigger event from `MSH.9`, such as `ADT^A01`.
    pub message_type: String,
    /// Number of field entries included in the trace.
    pub field_count: usize,
    /// Field path trace records.
    pub fields: Vec<FieldPathTrace>,
}

impl FieldPathTraceReport {
    /// Convert this v1 field-path trace into the explicit v2 evidence contract shape.
    #[must_use]
    pub fn to_v2(
        &self,
        tool_name: impl Into<String>,
        tool_version: impl Into<String>,
    ) -> FieldPathTraceReportV2 {
        FieldPathTraceReportV2 {
            schema_version: "2".to_string(),
            tool_name: tool_name.into(),
            tool_version: tool_version.into(),
            trace: self.clone(),
        }
    }
}

/// Field-path trace v2 with embedded schema and tool provenance.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FieldPathTraceReportV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// Producer surface that generated this trace.
    pub tool_name: String,
    /// Producer package version.
    pub tool_version: String,
    /// V1 field-path trace fields.
    #[serde(flatten)]
    pub trace: FieldPathTraceReport,
}

/// Field path trace record.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FieldPathTrace {
    /// Segment-position-qualified path.
    pub path: String,
    /// Segment and HL7 field path, such as `PID.3`.
    pub canonical_path: String,
    /// One-based segment index.
    pub segment_index: usize,
    /// One-based HL7 field index.
    pub field_index: usize,
    /// Whether the field value is present after redaction.
    pub present: bool,
    /// Shape of the redacted field value.
    pub value_shape: FieldValueShape,
    /// Redaction action associated with this path, when configured.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub redaction_action: Option<RedactionAction>,
}

/// Redacted field value shape.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldValueShape {
    /// Empty field after redaction or original content.
    Empty,
    /// Non-empty value not matching a known redaction marker.
    Present,
    /// SHA-256 redaction marker.
    HashedSha256,
}

/// Machine-readable report returned by evidence bundle replay.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceReplayReport {
    /// Evidence replay contract version.
    pub replay_version: String,
    /// Bundle version from the manifest or environment, when available.
    pub bundle_version: Option<String>,
    /// Tool that generated this replay report.
    pub tool_name: String,
    /// Tool version that generated this replay report.
    pub tool_version: String,
    /// Message type inferred from replay artifacts.
    pub message_type: Option<String>,
    /// Whether every replay verification check passed.
    pub reproduced: bool,
    /// Whether regenerated validation passed, when regeneration was possible.
    pub validation_valid: Option<bool>,
    /// Number of regenerated validation issues, when regeneration was possible.
    pub validation_issue_count: Option<usize>,
    /// Replay verification checks.
    pub checks: Vec<EvidenceReplayCheck>,
    /// Regenerated validation report when replay reached validation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_report: Option<ValidationReport>,
}

impl EvidenceReplayReport {
    /// Convert this v1 replay report into the explicit v2 evidence contract shape.
    ///
    /// This preserves the default serialized form of [`EvidenceReplayReport`].
    /// Producers opt into v2 when they are ready to emit embedded provenance.
    #[must_use]
    pub fn to_v2(&self) -> EvidenceReplayReportV2 {
        EvidenceReplayReportV2 {
            schema_version: "2".to_string(),
            report: self.clone(),
        }
    }
}

/// Evidence replay report v2 with embedded evidence schema version.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceReplayReportV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// V1 replay report fields.
    #[serde(flatten)]
    pub report: EvidenceReplayReport,
}

/// One replay verification check.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct EvidenceReplayCheck {
    /// Stable check name.
    pub name: String,
    /// Check status.
    pub status: EvidenceReplayCheckStatus,
    /// Human-readable check result.
    pub message: String,
}

/// Evidence replay check status.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceReplayCheckStatus {
    /// Check passed.
    Pass,
    /// Check failed.
    Fail,
}

/// Evidence bundle write or replay error.
#[derive(Debug, thiserror::Error)]
pub enum EvidenceError {
    /// Input message could not be parsed.
    #[error("parse error: {0}")]
    Parse(String),
    /// Profile YAML could not be loaded.
    #[error("profile load error: {0}")]
    Profile(String),
    /// Safe-analysis redaction failed.
    #[error("redaction error: {0}")]
    Redaction(#[from] RedactionError),
    /// Redacted output could not be parsed.
    #[error("redacted message parse error: {0}")]
    RedactedParse(String),
    /// Bundle request or producer option is invalid.
    #[error("invalid evidence bundle input: {0}")]
    InvalidInput(String),
    /// Bundle output already exists.
    #[error("bundle output directory already exists")]
    OutputExists,
    /// Filesystem failure.
    #[error("bundle IO error: {0}")]
    Io(String),
    /// JSON serialization or parsing failure.
    #[error("bundle JSON error: {0}")]
    Json(String),
}

/// Write a redacted evidence bundle from raw HL7, profile YAML, and policy TOML.
///
/// The bundle contains only redacted HL7 plus structured evidence artifacts. It
/// intentionally writes `profile.yaml` as supplied by the caller; callers should
/// review profile content before sharing a bundle.
///
/// # Errors
///
/// Returns [`EvidenceError`] when parsing, profile loading, redaction,
/// validation setup, JSON serialization, or filesystem writes fail. Existing
/// output directories are rejected.
pub fn write_safe_analysis_bundle(
    content: impl AsRef<[u8]>,
    profile_yaml: &str,
    policy_text: &str,
    out: impl AsRef<Path>,
    tool_name: &str,
) -> Result<EvidenceBundleSummary, EvidenceError> {
    write_safe_analysis_bundle_with_schema_version(
        content,
        profile_yaml,
        policy_text,
        out,
        tool_name,
        1,
    )
}

/// Write a safe-analysis evidence bundle with an explicit internal artifact schema version.
///
/// `artifact_schema_version = 1` preserves the original bundle-internal
/// artifact shapes. `artifact_schema_version = 2` writes v2
/// `validation-report.json`, `manifest.json`, `environment.json`,
/// `field-paths.json`, and `redaction-receipt.json` artifacts with embedded
/// schema/tool provenance.
///
/// # Errors
///
/// Returns [`EvidenceError`] when `artifact_schema_version` is unsupported, or
/// when parsing, profile loading, redaction, validation setup, JSON
/// serialization, or filesystem writes fail. Existing output directories are
/// rejected.
pub fn write_safe_analysis_bundle_with_schema_version(
    content: impl AsRef<[u8]>,
    profile_yaml: &str,
    policy_text: &str,
    out: impl AsRef<Path>,
    tool_name: &str,
    artifact_schema_version: u8,
) -> Result<EvidenceBundleSummary, EvidenceError> {
    if !matches!(artifact_schema_version, 1 | 2) {
        return Err(EvidenceError::InvalidInput(
            "evidence bundle artifact schema version must be 1 or 2".to_string(),
        ));
    }

    let content = content.as_ref();
    let out = out.as_ref();
    if out.exists() {
        return Err(EvidenceError::OutputExists);
    }

    let redaction_output = redact_hl7_safe_analysis(content, policy_text)?;
    let redacted_message = parse(redaction_output.redacted_hl7.as_bytes())
        .map_err(|error| EvidenceError::RedactedParse(error.to_string()))?;
    let profile = load_profile_checked(profile_yaml)
        .map_err(|error| EvidenceError::Profile(error.to_string()))?;
    let validation_report = ValidationReport::from_issues(
        &redacted_message,
        Some("profile.yaml".to_string()),
        validate(&redacted_message, &profile),
    );
    let field_trace = build_field_path_trace(&redacted_message, &redaction_output.receipt);
    let environment = EvidenceBundleEnvironment {
        bundle_version: BUNDLE_VERSION.to_string(),
        tool_name: tool_name.to_string(),
        tool_version: env!("CARGO_PKG_VERSION").to_string(),
        message_type: validation_report.message_type.clone(),
        input_sha256: redaction_output.input_sha256,
        profile_sha256: compute_sha256(profile_yaml),
        redaction_policy_sha256: redaction_output.policy_sha256,
        validation_valid: validation_report.valid,
        validation_issue_count: validation_report.issue_count,
        replay_command: REPLAY_COMMAND.to_string(),
    };

    fs::create_dir(out).map_err(|error| EvidenceError::Io(error.to_string()))?;
    fs::write(
        out.join("message.redacted.hl7"),
        redaction_output.redacted_hl7,
    )
    .map_err(|error| EvidenceError::Io(error.to_string()))?;
    fs::write(out.join("profile.yaml"), profile_yaml)
        .map_err(|error| EvidenceError::Io(error.to_string()))?;
    if artifact_schema_version == 2 {
        write_json_file(
            &out.join("validation-report.json"),
            &validation_report.to_v2(
                tool_name.to_string(),
                env!("CARGO_PKG_VERSION").to_string(),
                None,
            ),
        )?;
        write_json_file(
            &out.join("redaction-receipt.json"),
            &redaction_output
                .receipt
                .to_v2(tool_name.to_string(), env!("CARGO_PKG_VERSION").to_string()),
        )?;
        write_json_file(
            &out.join("field-paths.json"),
            &field_trace.to_v2(tool_name.to_string(), env!("CARGO_PKG_VERSION").to_string()),
        )?;
        write_json_file(&out.join("environment.json"), &environment.to_v2())?;
    } else {
        write_json_file(
            &out.join("redaction-receipt.json"),
            &redaction_output.receipt,
        )?;
        write_json_file(&out.join("validation-report.json"), &validation_report)?;
        write_json_file(&out.join("field-paths.json"), &field_trace)?;
        write_json_file(&out.join("environment.json"), &environment)?;
    }
    fs::write(out.join("replay.sh"), replay_shell_script())
        .map_err(|error| EvidenceError::Io(error.to_string()))?;
    fs::write(out.join("replay.ps1"), replay_powershell_script())
        .map_err(|error| EvidenceError::Io(error.to_string()))?;
    fs::write(out.join("README.md"), bundle_readme(tool_name))
        .map_err(|error| EvidenceError::Io(error.to_string()))?;

    let manifest = EvidenceBundleManifest {
        bundle_version: BUNDLE_VERSION.to_string(),
        tool_name: tool_name.to_string(),
        tool_version: env!("CARGO_PKG_VERSION").to_string(),
        artifacts: BUNDLE_ARTIFACT_SPECS
            .iter()
            .map(|(path, role)| bundle_manifest_artifact(out, path, role))
            .collect::<Result<_, _>>()?,
    };
    if artifact_schema_version == 2 {
        write_json_file(&out.join("manifest.json"), &manifest.to_v2())?;
    } else {
        write_json_file(&out.join("manifest.json"), &manifest)?;
    }

    let mut artifacts = BUNDLE_ARTIFACT_SPECS
        .iter()
        .map(|(path, _role)| (*path).to_string())
        .collect::<Vec<_>>();
    artifacts.push("manifest.json".to_string());

    Ok(EvidenceBundleSummary {
        bundle_version: BUNDLE_VERSION.to_string(),
        output_dir: ".".to_string(),
        message_type: validation_report.message_type.clone(),
        validation_valid: validation_report.valid,
        validation_issue_count: validation_report.issue_count,
        redaction_phi_removed: redaction_output.receipt.phi_removed,
        artifacts,
    })
}

/// Replay and verify an evidence bundle directory.
///
/// Replay reports fail closed: malformed manifests, unsafe manifest paths,
/// missing artifacts, hash mismatches, parse failures, profile failures, and
/// validation-report drift all produce a report with `reproduced = false`.
pub fn replay_evidence_bundle(bundle: impl AsRef<Path>, tool_name: &str) -> EvidenceReplayReport {
    build_replay_report(bundle.as_ref(), tool_name)
}

fn build_replay_report(bundle: &Path, tool_name: &str) -> EvidenceReplayReport {
    let mut checks = Vec::new();
    let required_artifacts = [
        "manifest.json",
        "message.redacted.hl7",
        "validation-report.json",
        "field-paths.json",
        "profile.yaml",
        "redaction-receipt.json",
        "environment.json",
        "replay.sh",
        "replay.ps1",
    ];

    let missing_artifacts: Vec<&str> = required_artifacts
        .iter()
        .copied()
        .filter(|artifact| !bundle.join(artifact).is_file())
        .collect();
    if missing_artifacts.is_empty() {
        checks.push(replay_check(
            "bundle-layout",
            EvidenceReplayCheckStatus::Pass,
            "all expected bundle artifacts are present",
        ));
    } else {
        checks.push(replay_check(
            "bundle-layout",
            EvidenceReplayCheckStatus::Fail,
            format!(
                "missing expected bundle artifact(s): {}",
                missing_artifacts.join(", ")
            ),
        ));
    }

    let manifest = match read_bundle_manifest(bundle) {
        Ok(manifest) => {
            checks.push(replay_check(
                "manifest",
                EvidenceReplayCheckStatus::Pass,
                "manifest.json parsed",
            ));
            Some(manifest)
        }
        Err(error) => {
            checks.push(replay_check(
                "manifest",
                EvidenceReplayCheckStatus::Fail,
                error,
            ));
            None
        }
    };
    let manifest_bundle_version = manifest
        .as_ref()
        .map(|manifest| manifest.bundle_version.clone());
    let manifest_catalog_ok = manifest
        .as_ref()
        .is_some_and(|manifest| verify_bundle_manifest_catalog(manifest, &mut checks));
    let manifest_hashes_ok = manifest_catalog_ok
        && manifest
            .as_ref()
            .is_some_and(|manifest| verify_bundle_manifest_hashes(bundle, manifest, &mut checks));

    if !manifest_hashes_ok {
        return EvidenceReplayReport {
            replay_version: REPLAY_VERSION.to_string(),
            bundle_version: manifest_bundle_version,
            tool_name: tool_name.to_string(),
            tool_version: env!("CARGO_PKG_VERSION").to_string(),
            message_type: None,
            reproduced: false,
            validation_valid: None,
            validation_issue_count: None,
            checks,
            validation_report: None,
        };
    }

    let environment = match read_bundle_json_value(bundle, "environment.json") {
        Ok(environment) => {
            checks.push(replay_check(
                "environment",
                EvidenceReplayCheckStatus::Pass,
                "environment.json parsed",
            ));
            Some(environment)
        }
        Err(error) => {
            checks.push(replay_check(
                "environment",
                EvidenceReplayCheckStatus::Fail,
                error,
            ));
            None
        }
    };

    let stored_report = match read_bundle_validation_report(bundle, "validation-report.json") {
        Ok(report) => {
            checks.push(replay_check(
                "stored-validation-report",
                EvidenceReplayCheckStatus::Pass,
                "validation-report.json parsed",
            ));
            Some(report)
        }
        Err(error) => {
            checks.push(replay_check(
                "stored-validation-report",
                EvidenceReplayCheckStatus::Fail,
                error,
            ));
            None
        }
    };

    let redacted_message = match read_bundle_artifact(bundle, "message.redacted.hl7") {
        Ok(contents) => match parse(&contents) {
            Ok(message) => {
                checks.push(replay_check(
                    "parse-redacted-message",
                    EvidenceReplayCheckStatus::Pass,
                    "message.redacted.hl7 parsed",
                ));
                Some(message)
            }
            Err(error) => {
                checks.push(replay_check(
                    "parse-redacted-message",
                    EvidenceReplayCheckStatus::Fail,
                    format!("message.redacted.hl7 did not parse: {error}"),
                ));
                None
            }
        },
        Err(error) => {
            checks.push(replay_check(
                "parse-redacted-message",
                EvidenceReplayCheckStatus::Fail,
                error,
            ));
            None
        }
    };

    let loaded_profile = match read_bundle_string(bundle, "profile.yaml") {
        Ok(profile_yaml) => match load_profile_checked(&profile_yaml) {
            Ok(profile) => {
                checks.push(replay_check(
                    "load-profile",
                    EvidenceReplayCheckStatus::Pass,
                    "profile.yaml loaded",
                ));
                Some(profile)
            }
            Err(error) => {
                checks.push(replay_check(
                    "load-profile",
                    EvidenceReplayCheckStatus::Fail,
                    format!("profile.yaml did not load: {error}"),
                ));
                None
            }
        },
        Err(error) => {
            checks.push(replay_check(
                "load-profile",
                EvidenceReplayCheckStatus::Fail,
                error,
            ));
            None
        }
    };

    let actual_report = match (redacted_message.as_ref(), loaded_profile.as_ref()) {
        (Some(message), Some(profile)) => {
            let report = ValidationReport::from_issues(
                message,
                Some("profile.yaml".to_string()),
                validate(message, profile),
            );
            checks.push(replay_check(
                "generate-validation-report",
                EvidenceReplayCheckStatus::Pass,
                "validation report regenerated from bundled message and profile",
            ));
            Some(report)
        }
        _ => {
            checks.push(replay_check(
                "generate-validation-report",
                EvidenceReplayCheckStatus::Fail,
                "validation report could not be regenerated",
            ));
            None
        }
    };

    match (actual_report.as_ref(), stored_report.as_ref()) {
        (Some(actual), Some(stored)) if actual == stored => checks.push(replay_check(
            "report-match",
            EvidenceReplayCheckStatus::Pass,
            "regenerated validation report matches validation-report.json",
        )),
        (Some(_), Some(_)) => checks.push(replay_check(
            "report-match",
            EvidenceReplayCheckStatus::Fail,
            "regenerated validation report differs from validation-report.json",
        )),
        _ => checks.push(replay_check(
            "report-match",
            EvidenceReplayCheckStatus::Fail,
            "validation report comparison could not be completed",
        )),
    }

    if let (Some(environment), Some(actual)) = (environment.as_ref(), actual_report.as_ref()) {
        let mut mismatches = Vec::new();
        if json_string(environment, "message_type").as_deref() != Some(actual.message_type.as_str())
        {
            mismatches.push("message_type");
        }
        if json_bool(environment, "validation_valid") != Some(actual.valid) {
            mismatches.push("validation_valid");
        }
        if json_usize(environment, "validation_issue_count") != Some(actual.issue_count) {
            mismatches.push("validation_issue_count");
        }

        if mismatches.is_empty() {
            checks.push(replay_check(
                "environment-match",
                EvidenceReplayCheckStatus::Pass,
                "environment metadata matches regenerated validation report",
            ));
        } else {
            checks.push(replay_check(
                "environment-match",
                EvidenceReplayCheckStatus::Fail,
                format!("environment metadata mismatch: {}", mismatches.join(", ")),
            ));
        }
    } else {
        checks.push(replay_check(
            "environment-match",
            EvidenceReplayCheckStatus::Fail,
            "environment metadata comparison could not be completed",
        ));
    }

    let reproduced = checks
        .iter()
        .all(|check| check.status == EvidenceReplayCheckStatus::Pass);
    let bundle_version = environment
        .as_ref()
        .and_then(|value| json_string(value, "bundle_version"))
        .or(manifest_bundle_version);
    let message_type = actual_report
        .as_ref()
        .map(|report| report.message_type.clone())
        .or_else(|| {
            stored_report
                .as_ref()
                .map(|report| report.message_type.clone())
        })
        .or_else(|| {
            environment
                .as_ref()
                .and_then(|value| json_string(value, "message_type"))
        });
    let validation_valid = actual_report.as_ref().map(|report| report.valid);
    let validation_issue_count = actual_report.as_ref().map(|report| report.issue_count);

    EvidenceReplayReport {
        replay_version: REPLAY_VERSION.to_string(),
        bundle_version,
        tool_name: tool_name.to_string(),
        tool_version: env!("CARGO_PKG_VERSION").to_string(),
        message_type,
        reproduced,
        validation_valid,
        validation_issue_count,
        checks,
        validation_report: actual_report,
    }
}

fn write_json_file<T: serde::Serialize>(path: &Path, value: &T) -> Result<(), EvidenceError> {
    let bytes =
        serde_json::to_vec_pretty(value).map_err(|error| EvidenceError::Json(error.to_string()))?;
    fs::write(path, bytes).map_err(|error| EvidenceError::Io(error.to_string()))
}

fn bundle_manifest_artifact(
    bundle_dir: &Path,
    path: &str,
    role: &str,
) -> Result<EvidenceBundleManifestArtifact, EvidenceError> {
    let bytes =
        fs::read(bundle_dir.join(path)).map_err(|error| EvidenceError::Io(error.to_string()))?;
    Ok(EvidenceBundleManifestArtifact {
        path: path.to_string(),
        role: role.to_string(),
        sha256: compute_sha256_bytes(&bytes),
    })
}

fn build_field_path_trace(message: &Message, receipt: &RedactionReceipt) -> FieldPathTraceReport {
    let redaction_actions: BTreeMap<&str, RedactionAction> = receipt
        .actions
        .iter()
        .map(|action| (action.path.as_str(), action.action))
        .collect();
    let mut fields = Vec::new();

    for (segment_position, segment) in message.segments.iter().enumerate() {
        let segment_index = segment_position.saturating_add(1);
        for (modeled_index, field) in segment.fields.iter().enumerate() {
            let field_index = hl7_field_index(segment.id_str(), modeled_index);
            let canonical_path = format!("{}.{}", segment.id_str(), field_index);
            let field_text = field_to_text(field, &message.delims);
            fields.push(FieldPathTrace {
                path: format!("{}[{}].{}", segment.id_str(), segment_index, field_index),
                canonical_path: canonical_path.clone(),
                segment_index,
                field_index,
                present: !field_text.is_empty(),
                value_shape: field_value_shape(&field_text),
                redaction_action: redaction_actions.get(canonical_path.as_str()).copied(),
            });
        }
    }

    FieldPathTraceReport {
        message_type: message_type(message),
        field_count: fields.len(),
        fields,
    }
}

fn message_type(message: &Message) -> String {
    crate::get(message, "MSH.9")
        .unwrap_or("unknown")
        .to_string()
}

fn hl7_field_index(segment_id: &str, modeled_index: usize) -> usize {
    if segment_id == "MSH" {
        modeled_index.saturating_add(2)
    } else {
        modeled_index.saturating_add(1)
    }
}

fn field_value_shape(field_text: &str) -> FieldValueShape {
    if field_text.is_empty() {
        FieldValueShape::Empty
    } else if field_text.starts_with("hash:sha256:") {
        FieldValueShape::HashedSha256
    } else {
        FieldValueShape::Present
    }
}

fn field_to_text(field: &Field, delims: &crate::Delims) -> String {
    field
        .reps
        .iter()
        .map(|rep| {
            rep.comps
                .iter()
                .map(|comp| {
                    comp.subs
                        .iter()
                        .map(|atom| match atom {
                            Atom::Text(text) => text.as_str(),
                            Atom::Null => "\"\"",
                        })
                        .collect::<Vec<_>>()
                        .join(&delims.sub.to_string())
                })
                .collect::<Vec<_>>()
                .join(&delims.comp.to_string())
        })
        .collect::<Vec<_>>()
        .join(&delims.rep.to_string())
}

fn read_bundle_manifest(bundle: &Path) -> Result<EvidenceBundleManifest, String> {
    let contents = read_bundle_string(bundle, "manifest.json")?;
    serde_json::from_str(&contents)
        .map_err(|error| format!("manifest.json is invalid JSON: {error}"))
}

fn verify_bundle_manifest_catalog(
    manifest: &EvidenceBundleManifest,
    checks: &mut Vec<EvidenceReplayCheck>,
) -> bool {
    let expected = BUNDLE_ARTIFACT_SPECS;
    let mut errors = Vec::new();
    let mut seen_paths = BTreeSet::new();

    for artifact in &manifest.artifacts {
        if !seen_paths.insert(artifact.path.clone()) {
            errors.push("duplicate artifact path".to_string());
        }
        if safe_bundle_relative_path(&artifact.path).is_err() {
            errors.push("unsafe artifact path".to_string());
            continue;
        }
        if !is_lower_sha256_hex(&artifact.sha256) {
            errors.push(format!("{} has invalid sha256", artifact.path));
        }
        if !expected
            .iter()
            .any(|(path, role)| *path == artifact.path.as_str() && *role == artifact.role.as_str())
        {
            errors.push(format!(
                "{} has unexpected role {}",
                artifact.path, artifact.role
            ));
        }
    }

    for (expected_path, expected_role) in expected {
        if !manifest
            .artifacts
            .iter()
            .any(|artifact| artifact.path == expected_path && artifact.role == expected_role)
        {
            errors.push(format!("missing manifest entry for {expected_path}"));
        }
    }

    if errors.is_empty() {
        checks.push(replay_check(
            "manifest-artifacts",
            EvidenceReplayCheckStatus::Pass,
            "manifest lists expected bundle artifacts",
        ));
        true
    } else {
        checks.push(replay_check(
            "manifest-artifacts",
            EvidenceReplayCheckStatus::Fail,
            format!("manifest artifact catalog invalid: {}", errors.join(", ")),
        ));
        false
    }
}

fn verify_bundle_manifest_hashes(
    bundle: &Path,
    manifest: &EvidenceBundleManifest,
    checks: &mut Vec<EvidenceReplayCheck>,
) -> bool {
    let mut errors = Vec::new();

    for artifact in &manifest.artifacts {
        let relative_path = match safe_bundle_relative_path(&artifact.path) {
            Ok(relative_path) => relative_path,
            Err(error) => {
                errors.push(error);
                continue;
            }
        };
        match fs::read(bundle.join(relative_path)) {
            Ok(bytes) => {
                let actual = compute_sha256_bytes(&bytes);
                if actual != artifact.sha256 {
                    errors.push(format!("{} hash mismatch", artifact.path));
                }
            }
            Err(error) => {
                errors.push(format!("could not read {}: {error}", artifact.path));
            }
        }
    }

    if errors.is_empty() {
        checks.push(replay_check(
            "manifest-hashes",
            EvidenceReplayCheckStatus::Pass,
            "manifest artifact hashes match bundle contents",
        ));
        true
    } else {
        checks.push(replay_check(
            "manifest-hashes",
            EvidenceReplayCheckStatus::Fail,
            format!("manifest hash verification failed: {}", errors.join(", ")),
        ));
        false
    }
}

fn safe_bundle_relative_path(path: &str) -> Result<PathBuf, String> {
    if path.is_empty() || path.contains('\\') {
        return Err("manifest artifact path must be bundle-relative".to_string());
    }

    let relative_path = Path::new(path);
    if relative_path.is_absolute()
        || relative_path.components().any(|component| {
            matches!(
                component,
                Component::ParentDir | Component::Prefix(_) | Component::RootDir
            )
        })
    {
        return Err("manifest artifact path must be bundle-relative".to_string());
    }

    Ok(relative_path.to_path_buf())
}

fn is_lower_sha256_hex(value: &str) -> bool {
    value.len() == 64
        && value
            .bytes()
            .all(|byte| matches!(byte, b'0'..=b'9' | b'a'..=b'f'))
}

fn read_bundle_artifact(bundle: &Path, artifact: &str) -> Result<Vec<u8>, String> {
    fs::read(bundle.join(artifact)).map_err(|error| format!("could not read {artifact}: {error}"))
}

fn read_bundle_string(bundle: &Path, artifact: &str) -> Result<String, String> {
    fs::read_to_string(bundle.join(artifact))
        .map_err(|error| format!("could not read {artifact}: {error}"))
}

fn read_bundle_json_value(bundle: &Path, artifact: &str) -> Result<serde_json::Value, String> {
    let contents = read_bundle_string(bundle, artifact)?;
    serde_json::from_str(&contents).map_err(|error| format!("{artifact} is invalid JSON: {error}"))
}

fn read_bundle_validation_report(
    bundle: &Path,
    artifact: &str,
) -> Result<ValidationReport, String> {
    let contents = read_bundle_string(bundle, artifact)?;
    serde_json::from_str(&contents).map_err(|error| format!("{artifact} is invalid JSON: {error}"))
}

fn json_string(value: &serde_json::Value, key: &str) -> Option<String> {
    value.get(key)?.as_str().map(ToOwned::to_owned)
}

fn json_bool(value: &serde_json::Value, key: &str) -> Option<bool> {
    value.get(key)?.as_bool()
}

fn json_usize(value: &serde_json::Value, key: &str) -> Option<usize> {
    value
        .get(key)?
        .as_u64()
        .and_then(|count| usize::try_from(count).ok())
}

fn replay_check(
    name: impl Into<String>,
    status: EvidenceReplayCheckStatus,
    message: impl Into<String>,
) -> EvidenceReplayCheck {
    EvidenceReplayCheck {
        name: name.into(),
        status,
        message: message.into(),
    }
}

fn compute_sha256(value: &str) -> String {
    compute_sha256_bytes(value.as_bytes())
}

fn compute_sha256_bytes(bytes: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(bytes);
    format!("{:x}", hasher.finalize())
}

fn replay_shell_script() -> &'static str {
    "#!/usr/bin/env sh\nset -eu\ncd \"$(dirname \"$0\")\"\nhl7v2 replay . --format json > replay-report.json\n"
}

fn replay_powershell_script() -> &'static str {
    "$ErrorActionPreference = 'Stop'\nSet-Location $PSScriptRoot\nhl7v2 replay . --format json > .\\replay-report.json\n"
}

fn bundle_readme(tool_name: &str) -> String {
    format!(
        "# HL7v2 Evidence Bundle\n\n\
This directory contains a redacted, replayable evidence packet generated by `{tool_name}`.\n\n\
## Contents\n\n\
- `message.redacted.hl7`: redacted HL7 message used for replay.\n\
- `validation-report.json`: validation report generated from the redacted message.\n\
- `field-paths.json`: field-path trace and redaction action metadata.\n\
- `profile.yaml`: profile used for replay validation.\n\
- `redaction-receipt.json`: receipt describing retained, hashed, dropped, or missing fields.\n\
- `environment.json`: tool version, bundle metadata, and input/profile/policy hashes.\n\
- `manifest.json`: bundle-relative artifact paths, roles, and SHA-256 hashes.\n\
- `replay.sh` and `replay.ps1`: shell helpers that replay the bundle.\n\n\
## Replay\n\n\
Run `hl7v2 replay . --format json` from this directory, or run the generated script for your shell.\n\n\
## Safety Notes\n\n\
This bundle is intended for support and debugging after safe-analysis redaction. It should not contain raw message PHI in reports, receipts, traces, manifests, or replay output. The profile is user-authored and included as supplied; review it before sharing. Redaction receipts prove configured actions were applied, but they are not a general PHI detector.\n"
    )
}

#[cfg(test)]
mod tests {
    use super::{
        EvidenceReplayCheckStatus, json_string, read_bundle_json_value, replay_evidence_bundle,
        write_safe_analysis_bundle, write_safe_analysis_bundle_with_schema_version,
    };

    fn raw_message() -> &'static str {
        "MSH|^~\\&|SENDAPP|SENDFAC|RECVAPP|RECVFAC|202605080101||ADT^A01^ADT_A01|CTRL123|P|2.5\rPID|1||123456^^^HOSP^MR||Doe^John||19700101|M"
    }

    fn profile_yaml() -> &'static str {
        r#"
message_structure: ADT_A01
version: "2.5.1"
segments:
  - id: MSH
  - id: PID
constraints:
  - path: MSH.9
    required: true
  - path: PID.3
    required: true
"#
    }

    fn policy_toml() -> &'static str {
        r#"
[[rules]]
path = "PID.3"
action = "hash"
reason = "Patient identifier"

[[rules]]
path = "PID.5"
action = "drop"
reason = "Patient name"

[[rules]]
path = "PID.7"
action = "drop"
reason = "Date of birth"
"#
    }

    fn ensure(condition: bool, message: &'static str) -> Result<(), Box<dyn std::error::Error>> {
        if condition {
            Ok(())
        } else {
            Err(std::io::Error::other(message).into())
        }
    }

    #[test]
    fn bundle_and_replay_keep_phi_out_of_reports() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let bundle_dir = temp.path().join("bundle");
        let summary = write_safe_analysis_bundle(
            raw_message(),
            profile_yaml(),
            policy_toml(),
            &bundle_dir,
            "hl7v2-python",
        )?;

        ensure(summary.bundle_version == "1", "expected bundle version")?;
        ensure(summary.output_dir == ".", "expected local output label")?;
        ensure(summary.message_type == "ADT^A01", "expected message type")?;
        ensure(summary.validation_valid, "expected valid redacted message")?;
        ensure(summary.redaction_phi_removed, "expected PHI removal")?;
        ensure(
            summary
                .artifacts
                .iter()
                .any(|artifact| artifact == "manifest.json"),
            "expected manifest artifact",
        )?;
        let summary_v2 = summary.to_v2("hl7v2-python", "1.3.0");
        ensure(
            summary_v2.schema_version == "2",
            "expected bundle summary v2 schema version",
        )?;
        ensure(
            summary_v2.tool_name == "hl7v2-python",
            "expected bundle summary producer",
        )?;
        ensure(
            summary_v2.summary.bundle_version == "1",
            "expected v2 summary to preserve bundle version",
        )?;

        let replay = replay_evidence_bundle(&bundle_dir, "hl7v2-python");
        ensure(replay.reproduced, "expected replay to reproduce")?;
        ensure(
            replay.tool_name == "hl7v2-python",
            "expected Python replay tool name",
        )?;
        let replay_v2 = replay.to_v2();
        ensure(
            replay_v2.schema_version == "2",
            "expected replay v2 schema version",
        )?;
        ensure(
            replay_v2.report.replay_version == "1",
            "expected replay v2 to preserve replay version",
        )?;
        ensure(
            replay
                .checks
                .iter()
                .all(|check| check.status == EvidenceReplayCheckStatus::Pass),
            "expected all replay checks to pass",
        )?;

        let mut artifact_text = String::new();
        for artifact in [
            "validation-report.json",
            "field-paths.json",
            "redaction-receipt.json",
            "environment.json",
            "manifest.json",
        ] {
            artifact_text.push_str(&std::fs::read_to_string(bundle_dir.join(artifact))?);
        }
        let replay_json = serde_json::to_string(&replay)?;
        artifact_text.push_str(&replay_json);
        for sentinel in ["Doe^John", "123456", "19700101"] {
            ensure(
                !artifact_text.contains(sentinel),
                "raw PHI sentinel leaked into evidence artifacts",
            )?;
        }

        Ok(())
    }

    #[test]
    fn bundle_schema_version_two_writes_v2_internal_artifacts()
    -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let bundle_dir = temp.path().join("bundle-v2");
        let summary = write_safe_analysis_bundle_with_schema_version(
            raw_message(),
            profile_yaml(),
            policy_toml(),
            &bundle_dir,
            "hl7v2-python",
            2,
        )?;

        ensure(
            summary.bundle_version == "1",
            "expected bundle summary v1 fields",
        )?;
        for artifact in [
            "validation-report.json",
            "manifest.json",
            "field-paths.json",
            "redaction-receipt.json",
            "environment.json",
        ] {
            let json = read_bundle_json_value(&bundle_dir, artifact)?;
            ensure(
                json_string(&json, "schema_version").as_deref() == Some("2"),
                "expected v2 internal bundle artifact",
            )?;
            ensure(
                json_string(&json, "tool_name").as_deref() == Some("hl7v2-python"),
                "expected v2 artifact producer",
            )?;
        }

        let replay = replay_evidence_bundle(&bundle_dir, "hl7v2-python");
        ensure(replay.reproduced, "expected v2 bundle artifacts to replay")?;

        Ok(())
    }

    #[test]
    fn replay_fails_closed_when_manifest_hash_is_wrong() -> Result<(), Box<dyn std::error::Error>> {
        let temp = tempfile::tempdir()?;
        let bundle_dir = temp.path().join("bundle");
        write_safe_analysis_bundle(
            raw_message(),
            profile_yaml(),
            policy_toml(),
            &bundle_dir,
            "hl7v2-python",
        )?;
        std::fs::write(
            bundle_dir.join("message.redacted.hl7"),
            "MSH|^~\\&|SEND|FAC|RECV|FAC|202605080101||ADT^A01|TAMPER|P|2.5",
        )?;

        let replay = replay_evidence_bundle(&bundle_dir, "hl7v2-python");
        ensure(
            !replay.reproduced,
            "expected tampered bundle to fail replay",
        )?;
        ensure(
            replay.checks.iter().any(|check| {
                check.name == "manifest-hashes" && check.status == EvidenceReplayCheckStatus::Fail
            }),
            "expected manifest hash failure",
        )?;
        Ok(())
    }
}