sheets-diff 2.5.0

Structured diff engine for Microsoft Excel .xlsx workbooks
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
//! Fixture generator for the `sheets-diff` test corpus (RFC-030, RFC-034).
//!
//! Run with:
//!   cargo run --example gen-fixtures
//!
//! This is a plain example, not a test: `cargo test` never runs it, so a
//! checkout only changes the fixture corpus when this is invoked explicitly.
//! Every generated workbook carries a fixed creation timestamp so re-running
//! this generator against unchanged scenario definitions produces
//! byte-identical `.xlsx` files (RFC-034 §5.2).
//!
//! This generator writes `old.xlsx`, `new.xlsx`, and `scenario.toml` only. It
//! does not write `expected.json` and does not depend on `sheets-diff`'s
//! comparison logic at all — see correction request 01 on Handoff 01: a
//! generator that also produces goldens is a second, silent bless path. The
//! only way `expected.json` changes is
//! `BLESS=1 cargo test --features serde,chrono -- generated_fixtures_match_golden`
//! (`tests/integration.rs`), which asserts before it ever writes. `serde`
//! and `chrono` together, not `serde` alone, are the canonical feature set
//! goldens are blessed under (RFC-036 Handoff 02 correction C-01) — a
//! date-bearing fixture's exact JSON depends on `chrono` being enabled.

use std::path::Path;

use rust_xlsxwriter::{Chart, ChartType, DocProperties, ExcelDateTime, Format, Formula, Workbook};

// ---------------------------------------------------------------------------
// Fixed-timestamp workbook construction
// ---------------------------------------------------------------------------

/// One fixed creation date for every generated fixture, so byte content
/// depends only on the scenario definition below, never on wall-clock time.
fn fixture_properties() -> DocProperties {
    let date = ExcelDateTime::from_ymd(2020, 1, 1).expect("valid fixed fixture date");
    DocProperties::new().set_creation_datetime(&date)
}

fn new_workbook() -> Workbook {
    let mut wb = Workbook::new();
    wb.set_properties(&fixture_properties());
    wb
}

// ---------------------------------------------------------------------------
// Builder helpers
//
// These deliberately duplicate a subset of tests/support.rs rather than
// sharing it — an example cannot depend on the tests/ integration-test
// module without a workspace restructure (RFC-034 §8 already weighed and
// rejected the equivalent xtask option on the same cost/benefit grounds).
// The duplication is not accidental: unlike tests/support.rs's builders,
// every builder here pins fixture_properties() so the committed corpus is
// byte-reproducible. tests/support.rs's builders must NOT gain a pinned
// timestamp — they back ~60 non-corpus tests that don't write tracked files
// and have no reproducibility requirement. If you change one file's builder
// signatures, check whether the other needs the same change.
// ---------------------------------------------------------------------------

fn wb_wide_column(row: u32, col: u16, value: &str) -> Vec<u8> {
    let mut wb = new_workbook();
    let ws = wb.add_worksheet();
    ws.write_string(row, col, value).unwrap();
    wb.save_to_buffer().unwrap()
}

/// One named sheet's cells, as `(name, cells)`.
type SheetSpec<'a> = (&'a str, &'a [(u32, u16, &'a str)]);

fn wb_sheets(sheets: &[SheetSpec]) -> Vec<u8> {
    let mut wb = new_workbook();
    for (name, cells) in sheets {
        let ws = wb.add_worksheet();
        ws.set_name(*name).unwrap();
        for (row, col, val) in *cells {
            ws.write_string(*row, *col, *val).unwrap();
        }
    }
    wb.save_to_buffer().unwrap()
}

fn wb_with_formula(
    value_row: u32,
    value_col: u16,
    value: &str,
    formula_row: u32,
    formula_col: u16,
    formula: &str,
) -> Vec<u8> {
    let mut wb = new_workbook();
    let ws = wb.add_worksheet();
    ws.write_string(value_row, value_col, value).unwrap();
    ws.write_formula(formula_row, formula_col, Formula::new(formula))
        .unwrap();
    wb.save_to_buffer().unwrap()
}

fn wb_empty() -> Vec<u8> {
    let mut wb = new_workbook();
    wb.add_worksheet();
    wb.save_to_buffer().unwrap()
}

fn wb_strings(cells: &[(u32, u16, &str)]) -> Vec<u8> {
    let mut wb = new_workbook();
    let ws = wb.add_worksheet();
    for (row, col, val) in cells {
        ws.write_string(*row, *col, *val).unwrap();
    }
    wb.save_to_buffer().unwrap()
}

/// Rewrite one XML entry inside a generated `.xlsx` with `patch` applied to
/// its UTF-8 text content; every other entry is copied through unchanged.
///
/// Duplicated from `tests/support.rs::patch_xlsx_xml` rather than shared
/// (RFC-036 Handoff 03 §1) — this generator deliberately does not depend on
/// anything under `tests/`, the same reason its other builders above
/// duplicate `tests/support.rs` rather than importing it: the fixture bytes
/// must not be influenced by, or coupled to, the code under test. Reused
/// verbatim rather than reimplemented, since re-verifying zip round-trip
/// correctness from scratch would buy nothing. Byte-reproducibility of its
/// output was verified empirically (two runs, 2s apart, byte-identical) —
/// `zip::write::FileOptions::default()`'s timestamp does not vary with
/// wall-clock time in this build configuration; see the Handoff 03 review
/// request for the check.
fn patch_xlsx_xml(
    xlsx_bytes: &[u8],
    entry_path: &str,
    patch: impl Fn(String) -> String,
) -> Vec<u8> {
    let mut archive = zip::ZipArchive::new(std::io::Cursor::new(xlsx_bytes)).unwrap();
    let mut out_buf = Vec::new();
    let mut writer = zip::ZipWriter::new(std::io::Cursor::new(&mut out_buf));
    let mut patched = false;

    for i in 0..archive.len() {
        let mut entry = archive.by_index(i).unwrap();
        let name = entry.name().to_string();
        let mut contents = Vec::new();
        std::io::Read::read_to_end(&mut entry, &mut contents).unwrap();

        let options: zip::write::FileOptions<()> = zip::write::FileOptions::default();
        writer.start_file(&name, options).unwrap();

        if name == entry_path {
            let text = String::from_utf8(contents).unwrap();
            let patched_text = patch(text);
            std::io::Write::write_all(&mut writer, patched_text.as_bytes()).unwrap();
            patched = true;
        } else {
            std::io::Write::write_all(&mut writer, &contents).unwrap();
        }
    }
    writer.finish().unwrap();

    assert!(patched, "entry {entry_path} not found in xlsx archive");
    out_buf
}

// ---------------------------------------------------------------------------
// Scenario output helpers
// ---------------------------------------------------------------------------

fn write_scenario(dir: &Path, name: &str, kind: &str, description: &str) {
    let toml = format!(
        "name        = {:?}\nkind        = {:?}\ndescription = {:?}\nnotes       = \"\"\n",
        name, kind, description
    );
    std::fs::write(dir.join("scenario.toml"), toml).unwrap();
}

fn write_fixture_pair(dir: &Path, old: &[u8], new: &[u8]) {
    std::fs::create_dir_all(dir).unwrap();
    std::fs::write(dir.join("old.xlsx"), old).unwrap();
    std::fs::write(dir.join("new.xlsx"), new).unwrap();
}

// ---------------------------------------------------------------------------
// Encrypted-workbook fixture (M5 Handoff 03, RFC-032)
//
// Not an .xlsx at all, and not encrypted -- a minimal hand-built CFB
// (Compound File Binary / OLE2) container shaped exactly enough to trigger
// calamine 0.36.1's password-protection detection, which is purely
// structural:
//
//   fn check_for_password_protected(...) -> Result<(), XlsxError> {
//       ...
//       if let Ok(cfb) = crate::cfb::Cfb::new(reader, offset_end) {
//           if cfb.has_directory("EncryptedPackage") {
//               return Err(XlsxError::Password);
//           }
//       }
//       Ok(())
//   }
//
// It checks for a CFB directory entry literally named "EncryptedPackage" --
// nothing about real encryption. A container with that one entry and no
// payload satisfies it. rust_xlsxwriter cannot produce a CFB container at
// all (it only ever emits ZIP/xlsx), so this is written by hand rather than
// generated through the usual builder helpers above.
//
// This is a fact about calamine 0.36.1's internals, not a public contract --
// if a future calamine version changes what it looks for, this fixture stops
// tripping the check and the resulting test failure is the coupling
// surfacing correctly, not a bug in the fixture. See [MS-CFB] for the
// container format; the layout below is the smallest structurally valid
// instance of it: one FAT sector, one directory sector, no data streams.
// ---------------------------------------------------------------------------

fn cfb_u32le(n: u32) -> [u8; 4] {
    n.to_le_bytes()
}

/// A 128-byte CFB directory entry. `name` must fit in 32 UTF-16 code units
/// (including the required null terminator, per [MS-CFB] 2.6.1).
#[allow(clippy::too_many_arguments)]
fn cfb_dir_entry(
    name: &str,
    object_type: u8,
    color_black: bool,
    left_sibling: u32,
    right_sibling: u32,
    child: u32,
    start_sector: u32,
    stream_size: u64,
) -> Vec<u8> {
    let mut e = Vec::with_capacity(128);

    let mut name_field = [0u8; 64];
    let units: Vec<u16> = name.encode_utf16().chain(std::iter::once(0)).collect();
    assert!(
        units.len() <= 32,
        "CFB entry name '{name}' exceeds 32 UTF-16 units including the null terminator"
    );
    for (i, u) in units.iter().enumerate() {
        let b = u.to_le_bytes();
        name_field[i * 2] = b[0];
        name_field[i * 2 + 1] = b[1];
    }
    e.extend_from_slice(&name_field);

    let name_len_bytes: u16 = if name.is_empty() {
        0
    } else {
        (units.len() as u16) * 2
    };
    e.extend_from_slice(&name_len_bytes.to_le_bytes());
    e.push(object_type);
    e.push(if color_black { 0x01 } else { 0x00 });
    e.extend_from_slice(&cfb_u32le(left_sibling));
    e.extend_from_slice(&cfb_u32le(right_sibling));
    e.extend_from_slice(&cfb_u32le(child));
    e.extend_from_slice(&[0u8; 16]); // CLSID -- zero for a non-storage-controlled entry
    e.extend_from_slice(&[0u8; 4]); // state bits -- unused here
    e.extend_from_slice(&[0u8; 8]); // creation time -- unused here
    e.extend_from_slice(&[0u8; 8]); // modified time -- unused here
    e.extend_from_slice(&cfb_u32le(start_sector));
    e.extend_from_slice(&stream_size.to_le_bytes());
    debug_assert_eq!(e.len(), 128);
    e
}

/// Builds the smallest CFB container calamine 0.36.1 recognises as
/// password-protected: a 512-byte header, one FAT sector, one directory
/// sector containing a Root Entry and a single child storage entry named
/// "EncryptedPackage" -- no stream data anywhere. 1536 bytes total.
fn build_encrypted_workbook_fixture() -> Vec<u8> {
    const FREESECT: u32 = 0xFFFFFFFF;
    const ENDOFCHAIN: u32 = 0xFFFFFFFE;
    const FATSECT: u32 = 0xFFFFFFFD;
    const NOSTREAM: u32 = 0xFFFFFFFF;

    let mut out = Vec::with_capacity(1536);

    // --- Header (512 bytes), [MS-CFB] 2.2 ---
    out.extend_from_slice(&[0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1]); // signature
    out.extend_from_slice(&[0u8; 16]); // CLSID, reserved
    out.extend_from_slice(&[0x3E, 0x00]); // minor version
    out.extend_from_slice(&[0x03, 0x00]); // major version 3 -> 512-byte sectors
    out.extend_from_slice(&[0xFE, 0xFF]); // byte order mark, little-endian
    out.extend_from_slice(&[0x09, 0x00]); // sector shift: 2^9 = 512
    out.extend_from_slice(&[0x06, 0x00]); // mini sector shift: 2^6 = 64
    out.extend_from_slice(&[0u8; 6]); // reserved
    out.extend_from_slice(&cfb_u32le(0)); // directory sector count -- must be 0 for major version 3
    out.extend_from_slice(&cfb_u32le(1)); // FAT sector count
    out.extend_from_slice(&cfb_u32le(1)); // first directory sector -- sector 1
    out.extend_from_slice(&cfb_u32le(0)); // transaction signature, unused
    out.extend_from_slice(&cfb_u32le(0x1000)); // mini stream cutoff (4096, standard, unused here)
    out.extend_from_slice(&cfb_u32le(ENDOFCHAIN)); // first mini FAT sector -- none
    out.extend_from_slice(&cfb_u32le(0)); // mini FAT sector count
    out.extend_from_slice(&cfb_u32le(ENDOFCHAIN)); // first DIFAT sector -- none, one FAT sector fits in the header array below
    out.extend_from_slice(&cfb_u32le(0)); // DIFAT sector count
    // DIFAT array: 109 entries. Entry 0 -> FAT sector 0; the rest unused.
    out.extend_from_slice(&cfb_u32le(0));
    for _ in 0..108 {
        out.extend_from_slice(&cfb_u32le(FREESECT));
    }
    debug_assert_eq!(out.len(), 512);

    // --- Sector 0: the FAT itself (512 bytes / 128 four-byte entries) ---
    out.extend_from_slice(&cfb_u32le(FATSECT)); // entry 0: this sector is a FAT sector
    out.extend_from_slice(&cfb_u32le(ENDOFCHAIN)); // entry 1: directory sector, one-sector chain
    for _ in 0..126 {
        out.extend_from_slice(&cfb_u32le(FREESECT));
    }
    debug_assert_eq!(out.len(), 1024);

    // --- Sector 1: directory (512 bytes / four 128-byte entries) ---
    // Entry 0: Root Entry, object type 0x05, points at entry 1 as its child.
    out.extend_from_slice(&cfb_dir_entry(
        "Root Entry",
        0x05,
        true,
        NOSTREAM,
        NOSTREAM,
        1,
        ENDOFCHAIN,
        0,
    ));
    // Entry 1: "EncryptedPackage", object type 0x01 (storage) -- the entry
    // calamine's check looks for. No children, no stream data.
    out.extend_from_slice(&cfb_dir_entry(
        "EncryptedPackage",
        0x01,
        true,
        NOSTREAM,
        NOSTREAM,
        NOSTREAM,
        0,
        0,
    ));
    // Entries 2-3: unused, zeroed (object type 0x00).
    out.extend_from_slice(&cfb_dir_entry(
        "", 0x00, false, NOSTREAM, NOSTREAM, NOSTREAM, 0, 0,
    ));
    out.extend_from_slice(&cfb_dir_entry(
        "", 0x00, false, NOSTREAM, NOSTREAM, NOSTREAM, 0, 0,
    ));
    debug_assert_eq!(out.len(), 1536);

    out
}

// ---------------------------------------------------------------------------
// Scenarios
// ---------------------------------------------------------------------------

fn main() {
    let base = Path::new("tests/fixtures/generated");

    // 1. Wide columns — tests A1 encoding through XFD
    {
        let dir = base.join("wide_columns");
        let old = wb_wide_column(0, 16383, "before"); // 0-based col 16383 → 1-based 16384 → XFD
        let new = wb_wide_column(0, 16383, "after");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "wide_columns_xfd",
            "regression",
            "Covers A1 addressing through column XFD (column 16384). \
             Tests the v1 address-encoding bug.",
        );
        println!("✓ wide_columns");
    }

    // 2. Renamed sheet — verifies cell diffs survive rename detection
    {
        let dir = base.join("renamed_sheet");
        let old = wb_sheets(&[("OldName", &[(0, 0, "before"), (1, 0, "same")])]);
        let new = wb_sheets(&[("NewName", &[(0, 0, "after"), (1, 0, "same")])]);
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "renamed_sheet_with_cell_change",
            "feature",
            "A single renamed sheet with one cell changed. Verifies conservative \
             rename detection and cell diff preservation across rename.",
        );
        println!("✓ renamed_sheet");
    }

    // 3. Typed values — text vs number vs bool distinctness
    {
        let dir = base.join("typed_values");
        let old = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_string(0, 0, "100").unwrap();
            ws.write_boolean(0, 1, true).unwrap();
            ws.write_string(0, 2, "2024-01-01").unwrap();
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_number(0, 0, 100.0).unwrap();
            ws.write_boolean(0, 1, false).unwrap();
            ws.write_string(0, 2, "2024-01-01").unwrap();
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "typed_values_text_vs_number_vs_bool",
            "feature",
            "Text \"100\" and number 100 are different. Bool true→false is a \
             content change. String \"2024-01-01\" unchanged.",
        );
        println!("✓ typed_values");
    }

    // 4. Formula — formula text change with same cached value
    {
        let dir = base.join("formula");
        let old = wb_with_formula(0, 0, "label", 1, 0, "=1+1");
        let new = wb_with_formula(0, 0, "label", 1, 0, "=2+0");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "formula_text_change",
            "feature",
            "Formula text changes (=1+1 → =2+0) with equivalent result. \
             Tests formula-layer detection independent of value change.",
        );
        println!("✓ formula");
    }

    // 5. Empty sheet — both sides empty
    {
        let dir = base.join("empty_sheet");
        let b = wb_empty();
        write_fixture_pair(&dir, &b, &b);
        write_scenario(
            &dir,
            "empty_sheet_identical",
            "edge_case",
            "Both workbooks have a single empty sheet. Result: no diffs.",
        );
        println!("✓ empty_sheet");
    }

    // 6. Sparse range — only a few cells far apart
    {
        let dir = base.join("sparse_range");
        let old = wb_strings(&[(0, 0, "A1"), (99, 25, "Z100")]);
        let new = wb_strings(&[(0, 0, "A1_changed"), (99, 25, "Z100")]);
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "sparse_range_one_change",
            "feature",
            "Large used range with only two populated cells far apart. \
             Only A1 changes; Z100 stays the same.",
        );
        println!("✓ sparse_range");
    }

    // 7. Row insertion cascade — shows positional vs key-aligned diff count
    {
        let dir = base.join("row_insertion_cascade");
        let old = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            for r in 0u32..20 {
                ws.write_string(r, 0, format!("id_{r}")).unwrap();
                ws.write_string(r, 1, format!("val_{r}")).unwrap();
            }
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_string(0, 0, "id_inserted").unwrap();
            ws.write_string(0, 1, "val_inserted").unwrap();
            for r in 0u32..20 {
                ws.write_string(r + 1, 0, format!("id_{r}")).unwrap();
                ws.write_string(r + 1, 1, format!("val_{r}")).unwrap();
            }
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "row_insertion_cascade",
            "regression",
            "One row inserted at the top of a 20-row sheet. Positional diff \
             reports all 20 rows as changed (cascade). Row-key alignment should \
             report only the inserted row.",
        );
        println!("✓ row_insertion_cascade");
    }

    // -----------------------------------------------------------------------
    // RFC-036 §5.2 matrix — scenarios 1-9 (Handoff 02, rust_xlsxwriter-only)
    // -----------------------------------------------------------------------

    // 8. Row-shifted origin — data block starts at row 5, not row 1.
    {
        let dir = base.join("row_shifted_origin");
        let old = wb_strings(&[(4, 0, "before")]); // row 5 (0-based row 4), col A
        let new = wb_strings(&[(4, 0, "after")]);
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "row_shifted_origin",
            "regression",
            "Data block starts at row 5, not row 1 (leading empty rows). \
             Value-only, no formulas. Coverage for coordinate arithmetic \
             that assumes origin row 1 (RFC-036 #1).",
        );
        println!("✓ row_shifted_origin");
    }

    // 9. Formula origin shifted — value and formula ranges both start below
    //    row 1, with a gap between them (also exercises non-contiguous
    //    formula cells).
    {
        let dir = base.join("formula_shifted_origin");
        let old = wb_with_formula(4, 0, "label", 6, 0, "=1+1"); // row5=label, row7=formula
        let new = wb_with_formula(4, 0, "label", 6, 0, "=2+0");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "formula_shifted_origin",
            "regression",
            "Value range and formula range both start below row 1, and the \
             formula is not immediately below the label cell (a gap at row \
             6). General case of D-04's origin-translation fix, beyond the \
             row-1-vs-row-2 shape the `formula` fixture already covers \
             (RFC-036 #2, positive case).",
        );
        println!("✓ formula_shifted_origin");
    }

    // 10. Formula at the first cell — the D-04 negative control. Origins
    //     coincide; guards against a future fix that special-cases this
    //     instead of translating through absolute coordinates unconditionally.
    {
        let dir = base.join("formula_at_first_cell");
        let old = wb_with_formula(1, 0, "label", 0, 0, "=1+1"); // formula at row1, label at row2
        let new = wb_with_formula(1, 0, "label", 0, 0, "=2+0");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "formula_at_first_cell",
            "regression",
            "The formula cell IS the first populated cell — value-range and \
             formula-range origins coincide. Negative control for D-04: the \
             shape that would have hidden the defect entirely, and a guard \
             against a future fix that special-cases the coinciding-origin \
             case (RFC-036 #2, negative control).",
        );
        println!("✓ formula_at_first_cell");
    }

    // 11. RowSignature alignment — matched by whole-row content signature,
    //     not a key column. Zero test coverage before this scenario.
    {
        let dir = base.join("alignment_row_signature");
        let old = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            for r in 0u32..5 {
                ws.write_string(r, 0, format!("row_{r}_a")).unwrap();
                ws.write_string(r, 1, format!("row_{r}_b")).unwrap();
            }
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_string(0, 0, "inserted_a").unwrap();
            ws.write_string(0, 1, "inserted_b").unwrap();
            for r in 0u32..5 {
                ws.write_string(r + 1, 0, format!("row_{r}_a")).unwrap();
                ws.write_string(r + 1, 1, format!("row_{r}_b")).unwrap();
            }
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "alignment_row_signature",
            "regression",
            "Row inserted at the top of a 5-row sheet, matched by \
             RowSignature alignment (whole-row content signature, not a key \
             column) rather than RowKey. RowSignature had zero test \
             coverage before this scenario (RFC-036 #3).",
        );
        println!("✓ alignment_row_signature");
    }

    // 12. HeaderColumn alignment — header row plus data rows, one inserted.
    //     Zero test coverage before this scenario.
    {
        let dir = base.join("alignment_header_column");
        let old = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_string(0, 0, "id").unwrap();
            ws.write_string(0, 1, "value").unwrap();
            for r in 1u32..4 {
                ws.write_string(r, 0, format!("id_{r}")).unwrap();
                ws.write_string(r, 1, format!("val_{r}")).unwrap();
            }
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_string(0, 0, "id").unwrap();
            ws.write_string(0, 1, "value").unwrap();
            ws.write_string(1, 0, "id_inserted").unwrap();
            ws.write_string(1, 1, "val_inserted").unwrap();
            for r in 1u32..4 {
                ws.write_string(r + 1, 0, format!("id_{r}")).unwrap();
                ws.write_string(r + 1, 1, format!("val_{r}")).unwrap();
            }
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "alignment_header_column",
            "regression",
            "Header row plus 3 data rows, one row inserted, matched by \
             HeaderColumn alignment. HeaderColumn had zero test coverage \
             before this scenario (RFC-036 #4).",
        );
        println!("✓ alignment_header_column");
    }

    // 13. Error values — one cell changes error kind, one stays the same
    //     error kind. CellError comparison had zero coverage at any level.
    {
        let dir = base.join("error_values");
        let old = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_formula(0, 0, Formula::new("1/0").set_result("#DIV/0!"))
                .unwrap();
            ws.write_formula(1, 0, Formula::new("A1").set_result("#N/A"))
                .unwrap();
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_formula(0, 0, Formula::new("A2").set_result("#REF!"))
                .unwrap();
            ws.write_formula(1, 0, Formula::new("A1").set_result("#N/A"))
                .unwrap();
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "error_values",
            "regression",
            "One error cell changes kind (#DIV/0! -> #REF!); a second stays \
             the same error kind (#N/A unchanged). CellError comparison and \
             ValueDifferenceKind::ErrorKindChanged had zero test coverage \
             at any level before this scenario (RFC-036 #5).",
        );
        println!("✓ error_values");
    }

    // 14. Sheet reordered — two sheets swap position (SheetChange::Moved,
    //     never distinguished from Unchanged by any prior test); a third
    //     stays in place but its content changes.
    {
        let dir = base.join("sheet_reordered");
        let old = {
            let mut wb = new_workbook();
            let a = wb.add_worksheet();
            a.set_name("Alpha").unwrap();
            a.write_string(0, 0, "alpha_val").unwrap();
            let b = wb.add_worksheet();
            b.set_name("Beta").unwrap();
            b.write_string(0, 0, "beta_val").unwrap();
            let c = wb.add_worksheet();
            c.set_name("Gamma").unwrap();
            c.write_string(0, 0, "gamma_before").unwrap();
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            // Beta and Alpha swap order; Gamma stays in place but changes.
            let b = wb.add_worksheet();
            b.set_name("Beta").unwrap();
            b.write_string(0, 0, "beta_val").unwrap();
            let a = wb.add_worksheet();
            a.set_name("Alpha").unwrap();
            a.write_string(0, 0, "alpha_val").unwrap();
            let c = wb.add_worksheet();
            c.set_name("Gamma").unwrap();
            c.write_string(0, 0, "gamma_after").unwrap();
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "sheet_reordered",
            "regression",
            "Three sheets: Alpha and Beta swap position (same content, \
             different index — SheetChange::Moved), Gamma stays in place \
             but its one cell changes. SheetChange::Moved had never been \
             distinguished from Unchanged by any test before this scenario \
             (RFC-036 #6). Reordering needs no special API — sheets are \
             added in a different call order between old and new.",
        );
        println!("✓ sheet_reordered");
    }

    // 15. Date column — ordinary serial-based dates, one changed. No
    //     golden-corpus fixture used dates at all before this scenario,
    //     despite dates being where four M2 defects lived.
    {
        let dir = base.join("date_column");
        let date_format = Format::new().set_num_format("yyyy-mm-dd");
        let old = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_datetime_with_format(
                0,
                0,
                ExcelDateTime::from_ymd(2024, 1, 1).unwrap(),
                &date_format,
            )
            .unwrap();
            ws.write_datetime_with_format(
                1,
                0,
                ExcelDateTime::from_ymd(2024, 6, 15).unwrap(),
                &date_format,
            )
            .unwrap();
            wb.save_to_buffer().unwrap()
        };
        let new = {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_datetime_with_format(
                0,
                0,
                ExcelDateTime::from_ymd(2024, 1, 1).unwrap(),
                &date_format,
            )
            .unwrap();
            ws.write_datetime_with_format(
                1,
                0,
                ExcelDateTime::from_ymd(2025, 6, 15).unwrap(),
                &date_format,
            )
            .unwrap();
            wb.save_to_buffer().unwrap()
        };
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "date_column",
            "regression",
            "A column of ordinary serial-based dates, one changed. No \
             golden-corpus fixture used dates before this scenario, despite \
             dates being where four M2 defects lived (RFC-036 #7). Its \
             golden is blessed under the canonical `serde,chrono` feature \
             set, not `serde` alone — CellDateTime.iso is \
             chrono-feature-conditional, so the exact-JSON golden check is \
             gated on both features together (RFC-036 Handoff 02 correction \
             C-01). Also covered by the feature-invariant \
             date_column_fixture_detects_date_change in tests/integration.rs.",
        );
        println!("✓ date_column");
    }

    // 16. Non-ASCII text — sheet name and cell content. Zero coverage of
    //     XML-escaping / shared-string handling for non-ASCII content.
    {
        let dir = base.join("non_ascii_text");
        let old = wb_sheets(&[(
            "Café☕",
            &[(0, 0, "héllo wörld"), (1, 0, "unchanged 日本語")],
        )]);
        let new = wb_sheets(&[(
            "Café☕",
            &[(0, 0, "héllo wörld — updated"), (1, 0, "unchanged 日本語")],
        )]);
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "non_ascii_text",
            "regression",
            "Non-ASCII sheet name and cell text (accented Latin, CJK, \
             emoji). XML-escaping and the shared-string table had zero \
             coverage of non-ASCII content before this scenario \
             (RFC-036 #8).",
        );
        println!("✓ non_ascii_text");
    }

    // 17. Chart sheet beside a worksheet — the chart-sheet coverage
    //     diagnostic had never fired in any test.
    {
        let dir = base.join("chart_sheet");
        let build_chart_workbook = |cell_value: &str| -> Vec<u8> {
            let mut wb = new_workbook();
            let ws = wb.add_worksheet();
            ws.write_number(0, 0, 1.0).unwrap();
            ws.write_number(1, 0, 2.0).unwrap();
            ws.write_string(3, 0, cell_value).unwrap();
            let mut chart = Chart::new(ChartType::Line);
            chart.add_series().set_values(("Sheet1", 0, 0, 1, 0));
            let cs = wb.add_chartsheet();
            cs.insert_chart(0, 0, &chart).unwrap();
            wb.save_to_buffer().unwrap()
        };
        let old = build_chart_workbook("before");
        let new = build_chart_workbook("after");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "chart_sheet",
            "regression",
            "A chart sheet beside an ordinary worksheet whose own cell \
             content changes. The chart-sheet coverage diagnostic had never \
             fired in any test before this scenario (RFC-036 #9).",
        );
        println!("✓ chart_sheet");
    }

    // -----------------------------------------------------------------------
    // RFC-036 §5.2 matrix — scenarios 10-11 (Handoff 03, XML-patched)
    // -----------------------------------------------------------------------

    // 18. Empty cell before content — a physically-present but empty <c>
    //     element precedes the sheet's real content. calamine filters
    //     DataRef::Empty out before computing range bounds, so this must
    //     NOT anchor the origin. rust_xlsxwriter has no reason to emit an
    //     empty cell element for a cell nothing was written to.
    {
        let dir = base.join("empty_cell_before_content");
        let build = |value: &str| -> Vec<u8> {
            let base_wb = wb_strings(&[(1, 0, value)]); // row 2 (0-based row 1), col A
            patch_xlsx_xml(&base_wb, "xl/worksheets/sheet1.xml", |xml| {
                xml.replacen(
                    "<sheetData>",
                    "<sheetData><row r=\"1\"><c r=\"A1\"/></row>",
                    1,
                )
            })
        };
        let old = build("before");
        let new = build("after");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "empty_cell_before_content",
            "regression",
            "A physically-present but empty cell (<c r=\"A1\"/>, no value or \
             type) precedes the sheet's real content at A2. calamine \
             filters DataRef::Empty cells out before computing the range's \
             start/end, so this must not anchor the origin at A1 — a real \
             and non-obvious behaviour with no prior test (RFC-036 #10). \
             Generated then XML-patched: rust_xlsxwriter has no reason to \
             emit an empty cell element for a cell nothing was written to.",
        );
        println!("✓ empty_cell_before_content");
    }

    // 19. ISO datetime — a t="d" cell, calamine's DateTimeIso path.
    //     rust_xlsxwriter cannot emit this cell type. Promotes RFC-035
    //     Handoff 05's hand-built reachability test into a durable
    //     corpus trip-wire for the exact bug D-01 was.
    {
        let dir = base.join("iso_datetime");
        let build = |iso: &str| -> Vec<u8> {
            let base_wb = wb_strings(&[(0, 0, "label")]);
            patch_xlsx_xml(&base_wb, "xl/worksheets/sheet1.xml", |xml| {
                xml.replacen(
                    "</sheetData>",
                    &format!("<row r=\"2\"><c r=\"A2\" t=\"d\"><v>{iso}</v></c></row></sheetData>"),
                    1,
                )
            })
        };
        let old = build("2024-01-01T00:00:00");
        let new = build("2099-12-31T23:59:59");
        write_fixture_pair(&dir, &old, &new);
        write_scenario(
            &dir,
            "iso_datetime",
            "regression",
            "An ISO-typed date/time cell (t=\"d\", calamine's DateTimeIso \
             path). rust_xlsxwriter cannot emit this cell type; generated \
             then XML-patched. Promotes RFC-035 Handoff 05's hand-built \
             d01_iso_datetime_reachability_end_to_end test into a durable \
             corpus trip-wire for the exact bug D-01 was (RFC-036 #11).",
        );
        println!("✓ iso_datetime");
    }

    // Encrypted-workbook fixture (M5 Handoff 03) -- a single standalone
    // negative-input file, like `not_a_zip.xlsx`, not an old/new scenario
    // pair, so it does not go under `base` or get a `scenario.toml`.
    {
        let corrupt_dir = Path::new("tests/fixtures/corrupt");
        std::fs::write(
            corrupt_dir.join("encrypted.xlsx"),
            build_encrypted_workbook_fixture(),
        )
        .unwrap();
        println!("✓ encrypted.xlsx (tests/fixtures/corrupt/)");
    }

    println!("\nAll fixtures generated in {}", base.display());
    println!("expected.json is not written here — bless goldens with:");
    println!("  BLESS=1 cargo test --features serde,chrono -- generated_fixtures_match_golden");
}