rvt 0.4.0

Apache-2.0 clean-room reader for Autodesk Revit files (.rvt, .rfa, .rte, .rft) without Revit: metadata, previews and the embedded schema of 2016-2026 files, and typed elements with measured geometry from Revit 2024 and 2025 projects, exported as IFC4, glTF and plan SVG.
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
//! Write path — round-trip Revit files + stream-level patching.
//!
//! # What works today
//!
//! - **CFB copy**: copy a Revit file from one path to another by
//!   re-reading every OLE stream and re-writing it through a new
//!   `cfb::CompoundFile`. Verified on the 11-release corpus.
//! - **Stream-level patching**: [`write_with_patches`] replaces the
//!   decompressed contents of named streams with caller-provided
//!   bytes, re-compresses with truncated gzip, and writes a new
//!   file. The framing invariants (gzip-truncation, 8-byte prefix
//!   on `Global/*`, Revit wrapper on `RevitPreview4.0` and
//!   `Contents`) are preserved via [`StreamFraming`]. Round-trip
//!   tests cover byte-identical copy, unchanged identity patches,
//!   stream growth, stream shrink, multi-stream patches, missing
//!   stream rejection, corrupt gzip verification, and GUID/history
//!   preservation on real family/project fixtures when the corpora
//!   are available.
//!
//! # What does not work yet
//!
//! - **Field-level semantic editing**: writing NEW values into
//!   Formats/Latest schema fields or Global/Latest instance fields.
//!   Blocked on Phase 7 (per-class encoders) in
//!   `TODO-BLINDSIDE.md`. Stream-level patching + the 100%
//!   classified schema are the pieces that unblock it.
//! - **CFB structural writing at Revit's exact sector layout**:
//!   non-empty patches preserve unpatched stream bytes and identity
//!   metadata, but the raw container bytes can still differ because
//!   the `cfb` crate owns FAT/directory maintenance.
//! # Atomicity
//!
//! [`write_with_patches`] writes to a sibling temp file and renames
//! into place on success. A mid-write failure leaves `dst` either
//! unchanged (if it already existed) or absent. The `TempGuard` RAII
//! handle unlinks the temp file on any early return or panic.

use crate::{Result, RevitFile};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;

/// Copy a Revit file from `src` to `dst`. The output container is a fresh
/// OLE2 CFB written by the `cfb` crate; stream contents are copied
/// byte-for-byte. For equivalence, check byte-level equality of the
/// decompressed streams on both sides — not the raw file bytes, because
/// OLE sector ordering may differ.
pub fn copy_file(src: &Path, dst: &Path) -> Result<()> {
    let mut rf = RevitFile::open(src)?;
    let streams = rf.stream_names();
    let out_file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(dst)?;
    let mut out = cfb::CompoundFile::create(out_file)
        .map_err(|e| crate::Error::Cfb(format!("create dst: {e}")))?;

    // Create parent storages first. OLE2 requires `/Formats`, `/Global`,
    // `/Partitions` to exist as storages before their child streams can
    // be created. Walk the stream list and pre-create every intermediate
    // folder.
    let mut created: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for name in &streams {
        let norm = if name.starts_with('/') {
            name.clone()
        } else {
            format!("/{name}")
        };
        let parts: Vec<&str> = norm.split('/').filter(|s| !s.is_empty()).collect();
        for n in 1..parts.len() {
            let parent = format!("/{}", parts[..n].join("/"));
            if created.insert(parent.clone()) {
                out.create_storage(&parent)
                    .map_err(|e| crate::Error::Cfb(format!("create_storage {parent}: {e}")))?;
            }
        }
    }

    for name in streams {
        let data = rf.read_stream(&name)?;
        let path = if name.starts_with('/') {
            name.clone()
        } else {
            format!("/{name}")
        };
        let mut s = out
            .create_stream(&path)
            .map_err(|e| crate::Error::Cfb(format!("create_stream {path}: {e}")))?;
        s.write_all(&data)
            .map_err(|e| crate::Error::Cfb(format!("write_all {path}: {e}")))?;
    }
    out.flush()
        .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
    Ok(())
}

/// A stream-level patch: replace the decompressed payload of a named OLE
/// stream with new bytes. The writer handles re-compression + re-embedding
/// into the OLE container.
#[derive(Debug, Clone)]
pub struct StreamPatch {
    /// OLE stream name, e.g. `"Formats/Latest"` or `"Global/Latest"`.
    pub stream_name: String,
    /// New decompressed payload.
    pub new_decompressed: Vec<u8>,
    /// Framing to use when re-encoding. See [`StreamFraming`].
    pub framing: StreamFraming,
}

/// How a stream's compressed body should be framed on disk. Revit uses
/// two distinct conventions:
///
/// - `Global/*` streams: 8-byte custom prefix (`00 × 8`), then truncated gzip.
/// - `Formats/Latest` and `Global/ContentDocuments`: gzip from byte 0.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StreamFraming {
    /// Gzip starts at offset 0 (e.g. Formats/Latest).
    RawGzipFromZero,
    /// 8-byte custom prefix + gzip (e.g. Global/Latest).
    CustomPrefix8,
    /// Stream has a completely custom wrapper + embedded gzip, or is
    /// uncompressed. Bytes are written verbatim — caller is responsible
    /// for framing.
    Verbatim,
}

/// Write `src` to `dst`, applying `patches` (by stream name) along the way.
/// Streams not mentioned in `patches` are copied byte-for-byte.
///
/// Success criterion: the round-trip preserves every unpatched stream
/// byte-for-byte; patched streams round-trip with their new content.
///
/// # Validation
///
/// Every `StreamPatch.stream_name` MUST correspond to a stream that
/// exists in the source file. A patch for a non-existent stream (e.g.
/// a typo in the name) returns `Error::StreamNotFound` BEFORE any
/// write begins. This prevents silent-no-op bugs where users think
/// they patched a stream but actually just copied the file unchanged.
///
/// # Atomicity
///
/// The output is written to a sibling temp file (`<dst>.tmp-<pid>`)
/// and renamed to `dst` only after all writes + flushes succeed. A
/// mid-write failure leaves the temp file behind and `dst` either
/// unchanged (if it already existed) or absent. This prevents the
/// previous corrupt-on-mid-write behaviour that a truncating
/// `OpenOptions::truncate(true).open(dst)` call caused.
pub fn write_with_patches(src: &Path, dst: &Path, patches: &[StreamPatch]) -> Result<()> {
    use crate::compression;
    let mut rf = RevitFile::open(src)?;
    let streams = rf.stream_names();

    // Validate patch names against actual stream set. A typo or stale
    // reference should error fast, not silently no-op.
    let stream_set: std::collections::BTreeSet<&str> = streams.iter().map(|s| s.as_str()).collect();
    for p in patches {
        if !stream_set.contains(p.stream_name.as_str()) {
            return Err(crate::Error::StreamNotFound(p.stream_name.clone()));
        }
    }

    // WRT-10.3 fast-path: empty-patch round-trip bypasses CFB
    // round-tripping entirely and copies the source file byte-for-
    // byte. This gives us byte-identical output for the
    // "verify the pipeline" use case (corpus re-emission, canonical
    // form checks, git-friendly diffing) without needing the
    // sector-reordering pass. For non-empty patches, fall through
    // to the CFB rewriter below — sector preservation for patched
    // builds is still pending.
    if patches.is_empty() && src != dst {
        // Atomic copy via temp + rename (same durability contract as
        // the CFB path below).
        let dst_parent = dst.parent().unwrap_or_else(|| Path::new("."));
        let dst_name = dst
            .file_name()
            .ok_or_else(|| crate::Error::Cfb("dst has no filename component".into()))?
            .to_string_lossy()
            .to_string();
        let tmp_name = format!(".{dst_name}.copy-{}", std::process::id());
        let tmp_path = dst_parent.join(&tmp_name);
        std::fs::copy(src, &tmp_path)?;
        std::fs::rename(&tmp_path, dst)?;
        return Ok(());
    }

    // WRT-10.3: non-empty patch sector-preservation path.
    //
    // Strategy: copy src to a temp file, open it with `cfb::open_rw`,
    // and rewrite ONLY the patched streams in-place. The `cfb` crate
    // reuses the stream's existing sector chain when the new content
    // fits (and extends only the tail when it grows), so every
    // unpatched stream's sectors stay physically where they were in
    // the source. This reduces the byte delta from ~94% (full
    // rebuild) to "only the patched streams' sectors and the FAT
    // entries that describe them" — usually well under 5% for a
    // single-stream patch.
    if src != dst {
        drop(rf); // release the read-only handle before we reopen rw.

        let dst_parent = dst.parent().unwrap_or_else(|| Path::new("."));
        let dst_name = dst
            .file_name()
            .ok_or_else(|| crate::Error::Cfb("dst has no filename component".into()))?
            .to_string_lossy()
            .to_string();
        let tmp_name = format!(".{dst_name}.rw-{}", std::process::id());
        let tmp_path = dst_parent.join(&tmp_name);

        struct InplaceGuard {
            path: Option<std::path::PathBuf>,
        }
        impl Drop for InplaceGuard {
            fn drop(&mut self) {
                if let Some(p) = self.path.take() {
                    let _ = std::fs::remove_file(&p);
                }
            }
        }
        let mut guard = InplaceGuard {
            path: Some(tmp_path.clone()),
        };

        std::fs::copy(src, &tmp_path)?;
        {
            let mut rw = cfb::open_rw(&tmp_path)
                .map_err(|e| crate::Error::Cfb(format!("open_rw {}: {e}", tmp_path.display())))?;
            for p in patches {
                let data = match p.framing {
                    StreamFraming::RawGzipFromZero => {
                        compression::truncated_gzip_encode(&p.new_decompressed)?
                    }
                    StreamFraming::CustomPrefix8 => {
                        compression::truncated_gzip_encode_with_prefix8(&p.new_decompressed)?
                    }
                    StreamFraming::Verbatim => p.new_decompressed.clone(),
                };
                let path = if p.stream_name.starts_with('/') {
                    p.stream_name.clone()
                } else {
                    format!("/{}", p.stream_name)
                };
                // `create_stream` truncates + rewrites an existing
                // stream by design, which is what we want. The cfb
                // crate reuses the prior sector chain when content
                // fits and extends only the tail when it grows.
                let mut s = rw
                    .create_stream(&path)
                    .map_err(|e| crate::Error::Cfb(format!("create_stream {path}: {e}")))?;
                s.write_all(&data)
                    .map_err(|e| crate::Error::Cfb(format!("write_all {path}: {e}")))?;
                s.flush()
                    .map_err(|e| crate::Error::Cfb(format!("flush {path}: {e}")))?;
            }
            rw.flush()
                .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
        }
        std::fs::rename(&tmp_path, dst)?;
        guard.path = None;
        return Ok(());
    }

    // Compute a sibling temp path in the same directory as dst so
    // the final rename is atomic on the same filesystem.
    let dst_parent = dst.parent().unwrap_or_else(|| Path::new("."));
    let dst_name = dst
        .file_name()
        .ok_or_else(|| crate::Error::Cfb("dst has no filename component".into()))?
        .to_string_lossy()
        .to_string();
    let tmp_name = format!(".{dst_name}.tmp-{}", std::process::id());
    let tmp_path = dst_parent.join(&tmp_name);

    // Guard that unlinks the temp file on any early return or panic.
    // On success we rename it into place and the guard becomes a
    // no-op (its path field gets cleared).
    struct TempGuard {
        path: Option<std::path::PathBuf>,
    }
    impl Drop for TempGuard {
        fn drop(&mut self) {
            if let Some(p) = self.path.take() {
                let _ = std::fs::remove_file(&p);
            }
        }
    }
    let mut guard = TempGuard {
        path: Some(tmp_path.clone()),
    };

    let out_file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(true)
        .open(&tmp_path)?;
    let mut out = cfb::CompoundFile::create(out_file)
        .map_err(|e| crate::Error::Cfb(format!("create tmp: {e}")))?;

    // Pre-create parent storages (same logic as copy_file).
    let mut created: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    for name in &streams {
        let norm = if name.starts_with('/') {
            name.clone()
        } else {
            format!("/{name}")
        };
        let parts: Vec<&str> = norm.split('/').filter(|s| !s.is_empty()).collect();
        for n in 1..parts.len() {
            let parent = format!("/{}", parts[..n].join("/"));
            if created.insert(parent.clone()) {
                out.create_storage(&parent)
                    .map_err(|e| crate::Error::Cfb(format!("create_storage {parent}: {e}")))?;
            }
        }
    }

    for name in streams {
        let patch = patches.iter().find(|p| p.stream_name == name);
        let data = if let Some(p) = patch {
            match p.framing {
                StreamFraming::RawGzipFromZero => {
                    compression::truncated_gzip_encode(&p.new_decompressed)?
                }
                StreamFraming::CustomPrefix8 => {
                    compression::truncated_gzip_encode_with_prefix8(&p.new_decompressed)?
                }
                StreamFraming::Verbatim => p.new_decompressed.clone(),
            }
        } else {
            rf.read_stream(&name)?
        };
        let path = if name.starts_with('/') {
            name.clone()
        } else {
            format!("/{name}")
        };
        let mut s = out
            .create_stream(&path)
            .map_err(|e| crate::Error::Cfb(format!("create_stream {path}: {e}")))?;
        s.write_all(&data)
            .map_err(|e| crate::Error::Cfb(format!("write_all {path}: {e}")))?;
    }
    out.flush()
        .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
    // Close before rename so Windows doesn't hold the handle.
    drop(out);

    // Atomic rename into place. If rename fails (e.g. cross-device),
    // fall back to copy+remove. On failure both dst and tmp may exist
    // briefly; the guard cleans up tmp.
    std::fs::rename(&tmp_path, dst).map_err(|e| {
        crate::Error::Cfb(format!(
            "rename {} -> {}: {e}",
            tmp_path.display(),
            dst.display()
        ))
    })?;

    // Rename succeeded — temp no longer exists, disarm the guard.
    guard.path = None;
    Ok(())
}

// ---- WRT-05: GUID preservation across write ----

/// Read the BasicFileInfo GUID from a Revit file (WRT-05). Returns
/// `Ok(None)` when the stream exists but no GUID was embedded. Used
/// by the write-path invariant tests to confirm a write cycle
/// preserves the file's identity.
pub fn file_guid(path: &Path) -> Result<Option<String>> {
    let mut rf = RevitFile::open(path)?;
    let stream_name = "BasicFileInfo";
    if !rf.stream_names().iter().any(|s| s == stream_name) {
        return Ok(None);
    }
    let bytes = rf.read_stream(stream_name)?;
    let info = crate::basic_file_info::BasicFileInfo::from_bytes(&bytes)
        .map_err(|e| crate::Error::BasicFileInfo(format!("parse: {e}")))?;
    Ok(info.guid)
}

/// Verify that a write cycle (copy / patch / rewrite) preserved
/// the source file's GUID. Returns `Ok(true)` when both files
/// carry the same GUID, `Ok(false)` when GUIDs diverge, and an
/// error when either file is unreadable.
///
/// This is the primary WRT-05 invariant check — call it right
/// after any [`write_with_patches`] / [`write_with_patches_verified`]
/// to gate deploys on GUID preservation.
pub fn guid_preserved(src: &Path, dst: &Path) -> Result<bool> {
    let a = file_guid(src)?;
    let b = file_guid(dst)?;
    Ok(a == b)
}

// ---- WRT-06: History chain preservation ----

/// Read the document-history entries from a Revit file (WRT-06).
/// Returns the ordered list of Revit-version strings embedded in
/// `Global/Latest` — oldest first, same order as
/// [`crate::object_graph::DocumentHistory::entries`].
///
/// Returns `Ok(Vec::new())` when no Global/Latest stream exists or
/// when the stream has no embedded "Revit …" markers. Err when the
/// stream read or decompression fails.
pub fn file_history_entries(path: &Path) -> Result<Vec<String>> {
    let mut rf = RevitFile::open(path)?;
    let stream_name = crate::streams::GLOBAL_LATEST;
    if !rf.stream_names().iter().any(|s| s == stream_name) {
        return Ok(Vec::new());
    }
    match crate::object_graph::DocumentHistory::from_revit_file(&mut rf) {
        Ok(h) => Ok(h.entries),
        Err(_) => Ok(Vec::new()),
    }
}

/// Verify that a write cycle preserved the document-history chain
/// (WRT-06). Returns `Ok(true)` when src and dst share the exact
/// same ordered entry list, `Ok(false)` on divergence, and Err
/// when either file is unreadable.
///
/// Pair with [`guid_preserved`] for a two-value "file-identity
/// preserved" predicate after any [`write_with_patches`] cycle.
pub fn history_entries_preserved(src: &Path, dst: &Path) -> Result<bool> {
    let a = file_history_entries(src)?;
    let b = file_history_entries(dst)?;
    Ok(a == b)
}

// ---- WRT-13: Stream hash verification per write ----

/// Per-stream verification outcome (WRT-13). One entry per
/// expected stream; the `match_`/`first_diff_at` pair distinguishes
/// clean success from a specific byte position where the written
/// stream diverged from expectations.
#[derive(Debug, Clone)]
pub struct StreamVerification {
    /// OLE stream name, e.g. `"Formats/Latest"`.
    pub stream_name: String,
    /// `true` when the stream's decompressed bytes in the written
    /// file exactly equal the expected decompressed bytes.
    pub match_: bool,
    /// When `match_ == false`, the first byte offset where the
    /// decompressed output differs from expected. `None` on
    /// success or when the decompression itself failed.
    pub first_diff_at: Option<usize>,
    /// When decompression failed, the error message. `None` on
    /// clean read (whether or not bytes matched).
    pub decompress_error: Option<String>,
    /// Length of the decompressed bytes actually read from `dst`
    /// (0 when decompression failed entirely).
    pub actual_len: usize,
    /// Length of the expected decompressed bytes (what
    /// [`StreamPatch::new_decompressed`] carried).
    pub expected_len: usize,
}

/// Aggregate result of verifying every patched stream (WRT-13).
#[derive(Debug, Clone, Default)]
pub struct StreamVerificationReport {
    /// Per-stream outcomes in the same order as the input patches.
    pub streams: Vec<StreamVerification>,
}

impl StreamVerificationReport {
    /// `true` when every stream verified cleanly.
    pub fn all_matched(&self) -> bool {
        !self.streams.is_empty() && self.streams.iter().all(|s| s.match_)
    }

    /// Count of streams that failed verification (mismatch or
    /// decompression error).
    pub fn failure_count(&self) -> usize {
        self.streams.iter().filter(|s| !s.match_).count()
    }

    /// Iterator over just the failing streams.
    pub fn failures(&self) -> impl Iterator<Item = &StreamVerification> {
        self.streams.iter().filter(|s| !s.match_)
    }
}

/// Decompress a named stream from `dst` using the given framing.
/// Returns `Ok(decompressed_bytes)` or an error message if any
/// step failed. Used internally by [`verify_patches_applied`]; pub
/// so corpus audits can call it too.
///
/// # Checksum-page policy (Finding 1 / #151)
///
/// The writer re-encodes patches with `truncated_gzip_encode` /
/// `truncated_gzip_encode_with_prefix8` — **strip-clean** truncated-gzip,
/// not Revit's stored checksum-paged layout. Verification therefore uses
/// bare [`crate::compression::inflate_at`], not
/// [`crate::compression::inflate_stream_at`]: blindly stripping every
/// 65_249-byte boundary would corrupt writer-produced streams that happen
/// to be ≥ one stored page. Identity copies (`read_stream` / empty-patch)
/// remain stored-byte accurate; a paged encoder is still out of scope.
pub fn decompress_stream(dst: &Path, name: &str, framing: StreamFraming) -> Result<Vec<u8>> {
    let mut rf = RevitFile::open(dst)?;
    let raw = rf.read_stream(name)?;
    match framing {
        StreamFraming::RawGzipFromZero => crate::compression::inflate_at(&raw, 0),
        StreamFraming::CustomPrefix8 => {
            // 8-byte custom prefix — gzip starts at offset 8.
            if raw.len() < 8 {
                return Err(crate::Error::Cfb(format!(
                    "stream '{name}' too short for CustomPrefix8 framing: {} bytes",
                    raw.len()
                )));
            }
            crate::compression::inflate_at(&raw, 8)
        }
        StreamFraming::Verbatim => Ok(raw),
    }
}

/// Verify that every patch in `patches` round-tripped through the
/// writer cleanly (WRT-13). Opens `dst`, reads each named stream,
/// decompresses it with the patch's `framing`, and compares the
/// resulting bytes to the patch's `new_decompressed`.
///
/// Typical use:
///
/// ```no_run
/// # use rvt::writer::{write_with_patches, verify_patches_applied, StreamPatch, StreamFraming};
/// # use std::path::Path;
/// let patches = vec![StreamPatch {
///     stream_name: "Formats/Latest".into(),
///     new_decompressed: vec![/* new bytes */],
///     framing: StreamFraming::RawGzipFromZero,
/// }];
/// write_with_patches(Path::new("in.rfa"), Path::new("out.rfa"), &patches)?;
/// let report = verify_patches_applied(Path::new("out.rfa"), &patches)?;
/// assert!(report.all_matched(), "one or more patches failed to round-trip");
/// # Ok::<(), rvt::Error>(())
/// ```
pub fn verify_patches_applied(
    dst: &Path,
    patches: &[StreamPatch],
) -> Result<StreamVerificationReport> {
    let mut report = StreamVerificationReport::default();
    for p in patches {
        match decompress_stream(dst, &p.stream_name, p.framing) {
            Ok(actual) => {
                let first_diff = actual
                    .iter()
                    .zip(p.new_decompressed.iter())
                    .position(|(a, b)| a != b)
                    .or_else(|| {
                        if actual.len() != p.new_decompressed.len() {
                            Some(actual.len().min(p.new_decompressed.len()))
                        } else {
                            None
                        }
                    });
                let match_ = actual == p.new_decompressed;
                report.streams.push(StreamVerification {
                    stream_name: p.stream_name.clone(),
                    match_,
                    first_diff_at: if match_ { None } else { first_diff },
                    decompress_error: None,
                    actual_len: actual.len(),
                    expected_len: p.new_decompressed.len(),
                });
            }
            Err(e) => {
                report.streams.push(StreamVerification {
                    stream_name: p.stream_name.clone(),
                    match_: false,
                    first_diff_at: None,
                    decompress_error: Some(e.to_string()),
                    actual_len: 0,
                    expected_len: p.new_decompressed.len(),
                });
            }
        }
    }
    Ok(report)
}

/// Convenience wrapper: [`write_with_patches`] followed by
/// [`verify_patches_applied`] on the written file (WRT-13).
/// Returns the verification report directly so callers can gate
/// deployment on `report.all_matched()` without a second call.
///
/// On verification failure the output file is left in place so the
/// caller can inspect it — we don't auto-delete, since the bytes
/// may still be useful for diagnosis.
pub fn write_with_patches_verified(
    src: &Path,
    dst: &Path,
    patches: &[StreamPatch],
) -> Result<StreamVerificationReport> {
    write_with_patches(src, dst, patches)?;
    verify_patches_applied(dst, patches)
}

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

    #[test]
    fn stream_patch_struct_builds() {
        let p = StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: vec![0x1fu8, 0x8b, 0x08],
            framing: StreamFraming::RawGzipFromZero,
        };
        assert_eq!(p.stream_name, "Formats/Latest");
        assert_eq!(p.framing, StreamFraming::RawGzipFromZero);
    }

    // ---- WRT-13: verify_patches_applied end-to-end ----

    fn temp_path(name: &str) -> std::path::PathBuf {
        let mut p = std::env::temp_dir();
        p.push(format!(
            "rvt-writer-test-{}-{}-{}",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos(),
            name
        ));
        p
    }

    /// Build a minimal CFB file with one gzip-compressed stream
    /// `"Formats/Latest"` carrying `payload`.
    fn build_tiny_cfb(path: &Path, payload: &[u8]) -> Result<()> {
        use crate::compression::truncated_gzip_encode;
        let compressed = truncated_gzip_encode(payload)?;
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)?;
        let mut cfb =
            cfb::CompoundFile::create(f).map_err(|e| crate::Error::Cfb(format!("create: {e}")))?;
        cfb.create_storage("/Formats")
            .map_err(|e| crate::Error::Cfb(format!("storage: {e}")))?;
        let mut s = cfb
            .create_stream("/Formats/Latest")
            .map_err(|e| crate::Error::Cfb(format!("stream: {e}")))?;
        s.write_all(&compressed)
            .map_err(|e| crate::Error::Cfb(format!("write: {e}")))?;
        drop(s);
        cfb.flush()
            .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
        Ok(())
    }

    fn build_cfb_with_raw_formats_latest(path: &Path, bytes: &[u8]) -> Result<()> {
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)?;
        let mut cfb =
            cfb::CompoundFile::create(f).map_err(|e| crate::Error::Cfb(format!("create: {e}")))?;
        cfb.create_storage("/Formats")
            .map_err(|e| crate::Error::Cfb(format!("storage: {e}")))?;
        let mut s = cfb
            .create_stream("/Formats/Latest")
            .map_err(|e| crate::Error::Cfb(format!("stream: {e}")))?;
        s.write_all(bytes)
            .map_err(|e| crate::Error::Cfb(format!("write: {e}")))?;
        drop(s);
        cfb.flush()
            .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
        Ok(())
    }

    #[test]
    fn verify_patches_applied_round_trips_clean_edit() {
        let src = temp_path("src.rvt");
        let dst = temp_path("dst.rvt");
        build_tiny_cfb(&src, b"old-bytes-for-stream").unwrap();
        let new_payload = b"new-payload-after-patch".to_vec();
        let patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: new_payload.clone(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        write_with_patches(&src, &dst, &patches).unwrap();
        let report = verify_patches_applied(&dst, &patches).unwrap();
        assert!(
            report.all_matched(),
            "expected all streams to verify: {:?}",
            report.streams
        );
        assert_eq!(report.failure_count(), 0);
        assert_eq!(report.streams.len(), 1);
        assert_eq!(report.streams[0].expected_len, new_payload.len());
        assert_eq!(report.streams[0].actual_len, new_payload.len());
        assert!(report.streams[0].decompress_error.is_none());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    /// Empty-patch round-trip must remain byte-identical (stored-accurate
    /// identity copy). Finding 1 strip must not touch `read_stream` /
    /// empty-patch paths.
    #[test]
    fn empty_patch_round_trip_is_byte_identical_stored_accurate() {
        let src = temp_path("empty_patch_src.rvt");
        let dst = temp_path("empty_patch_dst.rvt");
        build_tiny_cfb(&src, b"identity-payload-bytes").unwrap();
        write_with_patches(&src, &dst, &[]).unwrap();
        let a = std::fs::read(&src).unwrap();
        let b = std::fs::read(&dst).unwrap();
        assert_eq!(a, b, "empty-patch must copy stored CFB bytes unchanged");
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    /// Writer emits strip-clean truncated-gzip. A patch whose encoded size
    /// crosses one stored page (≥ 65_249 bytes) must still verify under
    /// bare inflate — `inflate_stream_at` would false-strip and break WRT-13.
    #[test]
    fn large_formats_patch_round_trips_without_false_page_strip() {
        use crate::compression::{
            REVIT_STORED_PAGE_BYTES, strip_revit_page_checksums, truncated_gzip_encode,
        };

        let src = temp_path("large_patch_src.rvt");
        let dst = temp_path("large_patch_dst.rvt");
        build_tiny_cfb(&src, b"seed").unwrap();

        // High-entropy payload → compressed form exceeds one stored page.
        let mut state = 0xA5A5_u32;
        let payload: Vec<u8> = (0..200_000)
            .map(|_| {
                state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                (state >> 16) as u8
            })
            .collect();
        let encoded = truncated_gzip_encode(&payload).unwrap();
        assert!(
            encoded.len() >= REVIT_STORED_PAGE_BYTES,
            "encoded fixture must be ≥ one stored page (got {})",
            encoded.len()
        );
        // Sanity: naive strip on writer output would mutilate the bitstream.
        assert_ne!(
            strip_revit_page_checksums(&encoded),
            encoded,
            "strip on strip-clean writer output must change bytes at page boundaries"
        );

        let patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: payload.clone(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        write_with_patches(&src, &dst, &patches).unwrap();
        let report = verify_patches_applied(&dst, &patches).unwrap();
        assert!(
            report.all_matched(),
            "large writer patch must verify without page-strip: {:?}",
            report.streams
        );

        // Stored bytes on disk are the encoder output (no 353-byte trailers).
        let mut rf = RevitFile::open(&dst).unwrap();
        let stored = rf.read_stream("Formats/Latest").unwrap();
        assert_eq!(stored, encoded);

        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn verify_patches_applied_detects_byte_mismatch() {
        let src = temp_path("src.rvt");
        let dst = temp_path("dst.rvt");
        build_tiny_cfb(&src, b"original").unwrap();
        // Tell the writer to write "actual-patch" but tell the
        // verifier to expect something different, simulating a
        // patch that wasn't properly re-encoded.
        let written_patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: b"actual-patch".to_vec(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        write_with_patches(&src, &dst, &written_patches).unwrap();
        let expected_patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: b"different-expected".to_vec(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        let report = verify_patches_applied(&dst, &expected_patches).unwrap();
        assert!(!report.all_matched());
        assert_eq!(report.failure_count(), 1);
        let fail = &report.streams[0];
        assert!(!fail.match_);
        assert!(fail.first_diff_at.is_some());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn write_with_patches_verified_is_all_in_one() {
        let src = temp_path("src.rvt");
        let dst = temp_path("dst.rvt");
        build_tiny_cfb(&src, b"seed").unwrap();
        let patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: b"fresh-payload".to_vec(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        let report = write_with_patches_verified(&src, &dst, &patches).unwrap();
        assert!(report.all_matched());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn verify_report_failures_iterator_yields_only_fails() {
        let ok = StreamVerification {
            stream_name: "Good".into(),
            match_: true,
            first_diff_at: None,
            decompress_error: None,
            actual_len: 4,
            expected_len: 4,
        };
        let bad = StreamVerification {
            stream_name: "Bad".into(),
            match_: false,
            first_diff_at: Some(2),
            decompress_error: None,
            actual_len: 4,
            expected_len: 4,
        };
        let report = StreamVerificationReport {
            streams: vec![ok, bad],
        };
        let fails: Vec<&str> = report.failures().map(|s| s.stream_name.as_str()).collect();
        assert_eq!(fails, vec!["Bad"]);
        assert_eq!(report.failure_count(), 1);
        assert!(!report.all_matched());
    }

    #[test]
    fn all_matched_false_for_empty_report() {
        let report = StreamVerificationReport::default();
        assert!(!report.all_matched());
    }

    #[test]
    fn decompress_stream_surfaces_framing_errors() {
        let src = temp_path("src.rvt");
        build_tiny_cfb(&src, b"hello").unwrap();
        // Ask for CustomPrefix8 on a RawGzipFromZero stream — the
        // first 8 bytes aren't a prefix, they're the gzip header,
        // so inflate_at(raw, 8) will fail.
        let result = decompress_stream(&src, "Formats/Latest", StreamFraming::CustomPrefix8);
        assert!(result.is_err());
        std::fs::remove_file(&src).ok();
    }

    #[test]
    fn verify_patches_applied_reports_corrupt_gzip() {
        let src = temp_path("corrupt-gzip.rvt");
        build_cfb_with_raw_formats_latest(&src, b"not a gzip stream").unwrap();
        let patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: b"expected".to_vec(),
            framing: StreamFraming::RawGzipFromZero,
        }];

        let report = verify_patches_applied(&src, &patches).unwrap();
        assert_eq!(report.streams.len(), 1);
        assert_eq!(report.failure_count(), 1);
        let failure = &report.streams[0];
        assert!(!failure.match_);
        assert_eq!(failure.actual_len, 0);
        assert!(
            failure.decompress_error.is_some(),
            "corrupt gzip must be reported as a decompression failure"
        );
        std::fs::remove_file(&src).ok();
    }

    // ---- WRT-05: GUID preservation ----

    /// Build a minimal CFB containing ONLY a `BasicFileInfo` stream
    /// with the given raw UTF-16LE bytes. Enough to drive the GUID
    /// invariant tests without a full Revit layout.
    fn build_cfb_with_basic_file_info(path: &Path, info_bytes: &[u8]) -> Result<()> {
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)?;
        let mut cfb =
            cfb::CompoundFile::create(f).map_err(|e| crate::Error::Cfb(format!("create: {e}")))?;
        let mut s = cfb
            .create_stream("/BasicFileInfo")
            .map_err(|e| crate::Error::Cfb(format!("stream: {e}")))?;
        s.write_all(info_bytes)
            .map_err(|e| crate::Error::Cfb(format!("write: {e}")))?;
        drop(s);
        cfb.flush()
            .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
        Ok(())
    }

    #[test]
    fn file_guid_round_trips_via_basic_file_info() {
        let src = temp_path("guid.rvt");
        let info = crate::basic_file_info::BasicFileInfo {
            version: 2024,
            build: Some("20230308_1635(x64)".into()),
            original_path: None,
            guid: Some("aabbccdd-1122-3344-5566-778899aabbcc".into()),
            locale: None,
            properties: Vec::new(),
            raw_text: String::new(),
        };
        build_cfb_with_basic_file_info(&src, &info.encode()).unwrap();
        let guid = file_guid(&src).unwrap();
        assert_eq!(
            guid.as_deref(),
            Some("aabbccdd-1122-3344-5566-778899aabbcc")
        );
        std::fs::remove_file(&src).ok();
    }

    #[test]
    fn file_guid_returns_none_when_no_basic_file_info() {
        let src = temp_path("no_guid.rvt");
        build_tiny_cfb(&src, b"nothing-here").unwrap();
        // build_tiny_cfb only creates Formats/Latest, no BasicFileInfo.
        let guid = file_guid(&src).unwrap();
        assert!(guid.is_none());
        std::fs::remove_file(&src).ok();
    }

    #[test]
    fn copy_file_preserves_guid() {
        let src = temp_path("src_guid.rvt");
        let dst = temp_path("dst_guid.rvt");
        let info = crate::basic_file_info::BasicFileInfo {
            version: 2024,
            build: Some("20230308_1635(x64)".into()),
            original_path: None,
            guid: Some("12345678-9abc-def0-1234-56789abcdef0".into()),
            locale: None,
            properties: Vec::new(),
            raw_text: String::new(),
        };
        build_cfb_with_basic_file_info(&src, &info.encode()).unwrap();
        copy_file(&src, &dst).unwrap();
        assert!(guid_preserved(&src, &dst).unwrap());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn write_with_no_basic_file_info_patch_preserves_guid() {
        let src = temp_path("src_pres.rvt");
        let dst = temp_path("dst_pres.rvt");
        // Build a CFB with BasicFileInfo (carrying the GUID) plus a
        // Formats/Latest stream (which we'll patch). Reuse the
        // BasicFileInfo setup, then also add Formats/Latest.
        let info = crate::basic_file_info::BasicFileInfo {
            version: 2024,
            build: Some("20230308_1635(x64)".into()),
            original_path: None,
            guid: Some("99999999-8888-7777-6666-555544443333".into()),
            locale: None,
            properties: Vec::new(),
            raw_text: String::new(),
        };
        {
            let f = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&src)
                .unwrap();
            let mut cfb = cfb::CompoundFile::create(f).unwrap();
            cfb.create_storage("/Formats").unwrap();
            let mut s = cfb.create_stream("/BasicFileInfo").unwrap();
            s.write_all(&info.encode()).unwrap();
            drop(s);
            let compressed = crate::compression::truncated_gzip_encode(b"original").unwrap();
            let mut s2 = cfb.create_stream("/Formats/Latest").unwrap();
            s2.write_all(&compressed).unwrap();
            drop(s2);
            cfb.flush().unwrap();
        }
        let patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: b"patched-bytes".to_vec(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        write_with_patches(&src, &dst, &patches).unwrap();
        assert!(guid_preserved(&src, &dst).unwrap());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn guid_diverges_when_dst_has_different_basic_file_info() {
        let src = temp_path("a_guid.rvt");
        let dst = temp_path("b_guid.rvt");
        let info_a = crate::basic_file_info::BasicFileInfo {
            version: 2024,
            build: None,
            original_path: None,
            guid: Some("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into()),
            locale: None,
            properties: Vec::new(),
            raw_text: String::new(),
        };
        let info_b = crate::basic_file_info::BasicFileInfo {
            guid: Some("bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb".into()),
            ..info_a.clone()
        };
        build_cfb_with_basic_file_info(&src, &info_a.encode()).unwrap();
        build_cfb_with_basic_file_info(&dst, &info_b.encode()).unwrap();
        assert!(!guid_preserved(&src, &dst).unwrap());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    // ---- WRT-06: History chain preservation ----

    /// Build a synthetic Global/Latest decompressed payload with
    /// embedded UTF-16LE "Revit …" version strings. Mirrors the
    /// byte shape DocumentHistory::from_decompressed scans for.
    fn synth_global_latest_with_history(versions: &[&str]) -> Vec<u8> {
        let mut out = Vec::new();
        // 8 bytes of header padding — the Revit format has ~0x48
        // bytes of framing but the scanner finds the first "Revit "
        // marker itself, so any leading bytes work.
        out.extend_from_slice(&[0u8; 64]);
        for v in versions {
            // Pad between entries so the scanner doesn't coalesce them.
            out.extend_from_slice(&[0u8; 4]);
            for unit in v.encode_utf16() {
                out.extend_from_slice(&unit.to_le_bytes());
            }
            // Null terminator so the scanner stops at the string end.
            out.extend_from_slice(&[0, 0]);
        }
        out
    }

    fn build_cfb_with_global_latest(path: &Path, decompressed: &[u8]) -> Result<()> {
        let f = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(true)
            .open(path)?;
        let mut cfb =
            cfb::CompoundFile::create(f).map_err(|e| crate::Error::Cfb(format!("create: {e}")))?;
        cfb.create_storage("/Global")
            .map_err(|e| crate::Error::Cfb(format!("storage: {e}")))?;
        let compressed = crate::compression::truncated_gzip_encode_with_prefix8(decompressed)?;
        let mut s = cfb
            .create_stream("/Global/Latest")
            .map_err(|e| crate::Error::Cfb(format!("stream: {e}")))?;
        s.write_all(&compressed)
            .map_err(|e| crate::Error::Cfb(format!("write: {e}")))?;
        drop(s);
        cfb.flush()
            .map_err(|e| crate::Error::Cfb(format!("flush: {e}")))?;
        Ok(())
    }

    #[test]
    fn file_history_recovers_synthetic_chain() {
        let src = temp_path("history.rvt");
        let decomp = synth_global_latest_with_history(&[
            "Revit 2018 - Initial",
            "Revit 2020 - Upgrade",
            "Revit 2024",
        ]);
        build_cfb_with_global_latest(&src, &decomp).unwrap();
        let entries = file_history_entries(&src).unwrap();
        assert!(entries.iter().any(|e| e.contains("2018")));
        assert!(entries.iter().any(|e| e.contains("2024")));
        std::fs::remove_file(&src).ok();
    }

    #[test]
    fn file_history_returns_empty_when_no_global_latest() {
        let src = temp_path("no_history.rvt");
        build_tiny_cfb(&src, b"nothing").unwrap();
        let entries = file_history_entries(&src).unwrap();
        assert!(entries.is_empty());
        std::fs::remove_file(&src).ok();
    }

    #[test]
    fn copy_file_preserves_history_chain() {
        let src = temp_path("src_hist.rvt");
        let dst = temp_path("dst_hist.rvt");
        let decomp =
            synth_global_latest_with_history(&["Revit 2022 - Original", "Revit 2024 - Upgrade"]);
        build_cfb_with_global_latest(&src, &decomp).unwrap();
        copy_file(&src, &dst).unwrap();
        assert!(history_entries_preserved(&src, &dst).unwrap());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn write_with_patches_non_global_preserves_history() {
        let src = temp_path("src_hist2.rvt");
        let dst = temp_path("dst_hist2.rvt");
        // Build a CFB with both Global/Latest (carrying history) and
        // Formats/Latest (which we'll patch).
        let decomp = synth_global_latest_with_history(&["Revit 2024 - only"]);
        {
            let f = std::fs::OpenOptions::new()
                .read(true)
                .write(true)
                .create(true)
                .truncate(true)
                .open(&src)
                .unwrap();
            let mut cfb = cfb::CompoundFile::create(f).unwrap();
            cfb.create_storage("/Global").unwrap();
            cfb.create_storage("/Formats").unwrap();
            let glob = crate::compression::truncated_gzip_encode_with_prefix8(&decomp).unwrap();
            let mut s1 = cfb.create_stream("/Global/Latest").unwrap();
            s1.write_all(&glob).unwrap();
            drop(s1);
            let fmt = crate::compression::truncated_gzip_encode(b"formats-body").unwrap();
            let mut s2 = cfb.create_stream("/Formats/Latest").unwrap();
            s2.write_all(&fmt).unwrap();
            drop(s2);
            cfb.flush().unwrap();
        }
        let patches = vec![StreamPatch {
            stream_name: "Formats/Latest".into(),
            new_decompressed: b"new-formats".to_vec(),
            framing: StreamFraming::RawGzipFromZero,
        }];
        write_with_patches(&src, &dst, &patches).unwrap();
        assert!(history_entries_preserved(&src, &dst).unwrap());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }

    #[test]
    fn history_diverges_when_global_latest_changed() {
        let src = temp_path("hist_a.rvt");
        let dst = temp_path("hist_b.rvt");
        let decomp_a = synth_global_latest_with_history(&["Revit 2018"]);
        let decomp_b = synth_global_latest_with_history(&["Revit 2024"]);
        build_cfb_with_global_latest(&src, &decomp_a).unwrap();
        build_cfb_with_global_latest(&dst, &decomp_b).unwrap();
        assert!(!history_entries_preserved(&src, &dst).unwrap());
        std::fs::remove_file(&src).ok();
        std::fs::remove_file(&dst).ok();
    }
}