brygge-ir 0.10.0

brygge's intermediate representation: the faithfulness-with-provenance model, its canonical content-addressed artifact, and the honesty machinery. The light core that links no source-decoder dependency.
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
//! Tests for the IR model types, their canonical (RFC 011 ยง2.4) round trips, and `AtomId` computation.

#![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]

use super::*;
use crate::Error;
use crate::canon::{CanonReader, RecordWriter};

fn sample_source() -> SourceIdentity {
    SourceIdentity {
        kind: SourceKind::Git,
        repo_id: b"repo".to_vec(),
        atom_id: b"deadbeef".to_vec(),
        signatures: vec![Signature {
            label: "gpgsig".to_string(),
            bytes: b"sig-bytes".to_vec(),
        }],
        extras: vec![Extra {
            label: "mergetag".to_string(),
            bytes: b"extra-bytes".to_vec(),
        }],
    }
}

fn atom(msg: &str, source_atom: &[u8]) -> ChangeAtom {
    let mut a = ChangeAtom {
        id: AtomId([0u8; 32]),
        parents: Vec::new(),
        ops: Vec::new(),
        copies: Vec::new(),
        metadata: MetadataClaims {
            message: Some(Text::utf8(msg)),
            ..MetadataClaims::default()
        },
        source: SourceIdentity {
            atom_id: source_atom.to_vec(),
            ..sample_source()
        },
        status: EpistemicStatus::Stated,
    };
    a.id = a.compute_id();
    a
}

// ---- round trips ------------------------------------------------------------------------------

#[test]
fn text_roundtrips_with_and_without_encoding() {
    for t in [
        Text::utf8("hello"),
        Text {
            bytes: Vec::new(),
            encoding: None,
        },
        Text {
            bytes: b"\xff\xfe".to_vec(),
            encoding: Some("latin1".to_string()),
        },
    ] {
        let bytes = t.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(Text::decode(&mut r).unwrap(), t);
        assert!(r.is_empty());
    }
}

#[test]
fn time_roundtrips_with_and_without_offset() {
    for t in [
        Time {
            seconds: 0,
            offset_minutes: None,
        },
        Time {
            seconds: -12345,
            offset_minutes: Some(-480),
        },
        Time {
            seconds: i64::from(i32::MAX),
            offset_minutes: Some(330),
        },
    ] {
        let bytes = t.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(Time::decode(&mut r).unwrap(), t);
        assert!(r.is_empty());
    }
}

#[test]
fn time_offset_out_of_i16_range_is_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(1, true, crate::canon::svarint_value(0));
    rw.field(
        2,
        true,
        crate::canon::svarint_value(i64::from(i16::MAX) + 1),
    );
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match Time::decode(&mut r) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

#[test]
fn source_kind_roundtrips_every_variant() {
    for k in [
        SourceKind::Git,
        SourceKind::Hg,
        SourceKind::Svn,
        SourceKind::Cvs,
        SourceKind::Other("perforce".to_string()),
    ] {
        let bytes = k.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(SourceKind::decode(&mut r).unwrap(), k);
        assert!(r.is_empty());
    }
}

#[test]
fn source_identity_roundtrips() {
    let s = sample_source();
    let bytes = s.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(SourceIdentity::decode(&mut r).unwrap(), s);
    assert!(r.is_empty());
}

#[test]
fn source_identity_roundtrips_with_no_signatures_or_extras() {
    let s = SourceIdentity {
        signatures: Vec::new(),
        extras: Vec::new(),
        ..sample_source()
    };
    let bytes = s.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(SourceIdentity::decode(&mut r).unwrap(), s);
}

#[test]
fn an_empty_signatures_list_encoded_is_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(1, true, SourceKind::Git.encode());
    rw.field(2, true, b"r".to_vec());
    rw.field(3, true, b"a".to_vec());
    rw.field(4, true, crate::canon::list_value(std::iter::empty()));
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match SourceIdentity::decode(&mut r) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

#[test]
fn path_op_roundtrips_every_variant() {
    let status = EpistemicStatus::Stated;
    let blob = BlobId([7u8; 32]);
    let ops = [
        PathOp::Add {
            path: "a".into(),
            content: Content::blob(blob, 0o100644),
            status: status.clone(),
        },
        PathOp::Modify {
            path: "a".into(),
            content: Content::blob(blob, 0o100644),
            status: status.clone(),
        },
        PathOp::Delete {
            path: "a".into(),
            status: status.clone(),
        },
        PathOp::Replace {
            path: "a".into(),
            content: Content::blob(blob, 0o120000),
            status,
        },
    ];
    for op in ops {
        let bytes = op.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(PathOp::decode(&mut r, 4).unwrap(), op);
        assert!(r.is_empty());
    }
}

/// RFC 021 D-1: a submodule entry round-trips for every variant that carries content, at both commit
/// lengths the wire admits (20 bytes, SHA-1; 32, SHA-256 โ€” the floor refuses the decoder from
/// producing the latter today, but the reader accepts it).
#[test]
fn path_op_roundtrips_a_submodule_at_every_variant_and_commit_length() {
    let status = EpistemicStatus::Stated;
    for commit_len in [20usize, 32] {
        let content = Content::Submodule {
            commit: vec![0xab; commit_len],
        };
        let ops = [
            PathOp::Add {
                path: "modules/x".into(),
                content: content.clone(),
                status: status.clone(),
            },
            PathOp::Modify {
                path: "modules/x".into(),
                content: content.clone(),
                status: status.clone(),
            },
            PathOp::Replace {
                path: "modules/x".into(),
                content: content.clone(),
                status: status.clone(),
            },
        ];
        for op in ops {
            let bytes = op.encode();
            let mut r = CanonReader::new(&bytes);
            assert_eq!(PathOp::decode(&mut r, 4).unwrap(), op);
            assert!(r.is_empty());
        }
    }
}

/// RFC 021 D-1/review 186: a blob entry's wire bytes (fields 1 path, 2 blob, 3 mode, 4 status) are
/// unchanged byte for byte from before this RFC โ€” the direct proof `AtomId` cannot change for existing
/// content, since [`ChangeAtom::compute_id`] hashes this same encoding.
#[test]
fn a_blob_entrys_wire_bytes_are_unchanged_by_rfc_021() {
    let op = PathOp::Add {
        path: "a".into(),
        content: Content::blob(BlobId([7u8; 32]), 0o100_644),
        status: EpistemicStatus::Stated,
    };
    let mut expected = RecordWriter::new();
    expected.field(1, true, b"a".to_vec());
    expected.field(2, true, [7u8; 32].to_vec());
    expected.field(3, true, crate::canon::uvarint_value(0o100_644));
    expected.field(4, true, EpistemicStatus::Stated.encode());
    let mut w = crate::canon::CanonWriter::new();
    w.uvarint(0); // the Add variant tag
    expected.finish_into(&mut w);
    assert_eq!(op.encode(), w.into_bytes());
}

/// RFC 021 D-1/ยง2: a blob (fields 2+3) and a submodule (field 5) are mutually exclusive โ€” both, or
/// neither, is refused as `NonCanonical`, each malformed case named.
#[test]
fn path_op_refuses_both_a_blob_and_a_submodule_or_neither() {
    let status_bytes = EpistemicStatus::Stated.encode();

    // Both: fields 2, 3 and 5 all present.
    let mut rw = RecordWriter::new();
    rw.field(1, true, b"a".to_vec());
    rw.field(2, true, [7u8; 32].to_vec());
    rw.field(3, true, crate::canon::uvarint_value(0o100_644));
    rw.field(4, true, status_bytes.clone());
    rw.field(5, true, vec![0xab; 20]);
    let mut w = crate::canon::CanonWriter::new();
    w.uvarint(0);
    rw.finish_into(&mut w);
    let bytes = w.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match PathOp::decode(&mut r, 4) {
        Err(Error::NonCanonical(msg)) => assert!(msg.contains("both a blob and a submodule")),
        other => panic!("expected NonCanonical, got {other:?}"),
    }

    // Neither: only path and status.
    let mut rw = RecordWriter::new();
    rw.field(1, true, b"a".to_vec());
    rw.field(4, true, status_bytes.clone());
    let mut w = crate::canon::CanonWriter::new();
    w.uvarint(0);
    rw.finish_into(&mut w);
    let bytes = w.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match PathOp::decode(&mut r, 4) {
        Err(Error::NonCanonical(msg)) => assert!(msg.contains("neither a blob")),
        other => panic!("expected NonCanonical, got {other:?}"),
    }

    // A partial blob: field 2 (blob) present without field 3 (mode).
    let mut rw = RecordWriter::new();
    rw.field(1, true, b"a".to_vec());
    rw.field(2, true, [7u8; 32].to_vec());
    rw.field(4, true, status_bytes);
    let mut w = crate::canon::CanonWriter::new();
    w.uvarint(0);
    rw.finish_into(&mut w);
    let bytes = w.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match PathOp::decode(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

/// RFC 021 D-1: field 5's commit must be 20 or 32 bytes.
#[test]
fn path_op_refuses_a_submodule_commit_of_the_wrong_length() {
    let mut rw = RecordWriter::new();
    rw.field(1, true, b"a".to_vec());
    rw.field(4, true, EpistemicStatus::Stated.encode());
    rw.field(5, true, vec![0xab; 19]);
    let mut w = crate::canon::CanonWriter::new();
    w.uvarint(0);
    rw.finish_into(&mut w);
    let bytes = w.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match PathOp::decode(&mut r, 4) {
        Err(Error::NonCanonical(msg)) => assert!(msg.contains("20 or 32")),
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

/// RFC 021 D-1/ยง2: contract 0.2.0 and 0.3.0 do not know field 5 at all โ€” a hand-built record naming it,
/// critical as every field is, is refused at the generic unknown-critical-field rule, never read as a
/// submodule.
#[test]
fn path_op_field_5_is_refused_under_contract_0_2_0_and_0_3_0() {
    for minor in [2u32, 3] {
        let mut rw = RecordWriter::new();
        rw.field(1, true, b"a".to_vec());
        rw.field(4, true, EpistemicStatus::Stated.encode());
        rw.field(5, true, vec![0xab; 20]);
        let mut w = crate::canon::CanonWriter::new();
        w.uvarint(0);
        rw.finish_into(&mut w);
        let bytes = w.into_bytes();
        let mut r = CanonReader::new(&bytes);
        match PathOp::decode(&mut r, minor) {
            Err(Error::UnknownCriticalField { tag: 5, .. }) => {}
            other => {
                panic!("minor {minor}: expected UnknownCriticalField for tag 5, got {other:?}")
            }
        }
    }
}

#[test]
fn copy_record_roundtrips() {
    let c = CopyRecord {
        from: "old.txt".into(),
        from_atom: AtomId([3u8; 32]),
        to: "new.txt".into(),
        status: EpistemicStatus::Stated,
    };
    let bytes = c.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(CopyRecord::decode(&mut r).unwrap(), c);
}

#[test]
fn identity_roundtrips_with_and_without_email() {
    for i in [
        Identity {
            name: Text::utf8("Ada"),
            email: Some(Text::utf8("ada@example.com")),
        },
        Identity {
            name: Text::utf8("Ada"),
            email: None,
        },
    ] {
        let bytes = i.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(Identity::decode(&mut r).unwrap(), i);
    }
}

#[test]
fn metadata_claims_roundtrips_full_and_empty() {
    let full = MetadataClaims {
        author: Some(Identity {
            name: Text::utf8("A"),
            email: None,
        }),
        author_time: Some(Time {
            seconds: 1,
            offset_minutes: None,
        }),
        committer: Some(Identity {
            name: Text::utf8("C"),
            email: None,
        }),
        commit_time: Some(Time {
            seconds: 2,
            offset_minutes: Some(60),
        }),
        message: Some(Text::utf8("msg")),
    };
    assert!(!full.is_empty());
    let bytes = full.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(MetadataClaims::decode(&mut r).unwrap(), full);

    let empty = MetadataClaims::default();
    assert!(empty.is_empty());
    let bytes = empty.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(MetadataClaims::decode(&mut r).unwrap(), empty);
}

#[test]
fn ref_kind_roundtrips_every_variant() {
    for k in [
        RefKind::Branch,
        RefKind::Tag,
        RefKind::Bookmark,
        RefKind::NamedBranch,
        RefKind::Other("phase".to_string()),
    ] {
        let bytes = k.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(RefKind::decode(&mut r).unwrap(), k);
    }
}

#[test]
fn ref_record_roundtrips_with_source_and_annotation() {
    let rf = RefRecord {
        name: "refs/tags/v1".into(),
        kind: RefKind::Tag,
        target: AtomId([9u8; 32]),
        status: EpistemicStatus::Stated,
        source: Some(sample_source()),
        annotation: Some(Annotation {
            tagger: Some(Identity {
                name: Text::utf8("T"),
                email: None,
            }),
            time: Some(Time {
                seconds: 5,
                offset_minutes: None,
            }),
            message: Some(Text::utf8("tag message")),
        }),
    };
    let bytes = rf.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(RefRecord::decode(&mut r).unwrap(), rf);
}

#[test]
fn ref_record_roundtrips_with_neither_source_nor_annotation() {
    let rf = RefRecord {
        name: "refs/heads/main".into(),
        kind: RefKind::Branch,
        target: AtomId([1u8; 32]),
        status: EpistemicStatus::Stated,
        source: None,
        annotation: None,
    };
    let bytes = rf.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(RefRecord::decode(&mut r).unwrap(), rf);
}

#[test]
fn loss_class_roundtrips_every_variant() {
    for c in [
        LossClass::Representation,
        LossClass::AdvisoryUnreliable,
        LossClass::Other,
    ] {
        let bytes = c.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(LossClass::decode(&mut r).unwrap(), c);
    }
}

#[test]
fn drop_record_roundtrips() {
    let d = DropRecord {
        class: LossClass::AdvisoryUnreliable,
        what: "svn:mergeinfo".into(),
        reason: "advisory, not authoritative".into(),
        step: None,
    };
    let bytes = d.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(DropRecord::decode(&mut r).unwrap(), d);
}

#[test]
fn flag_kind_roundtrips_every_variant() {
    for k in [
        FlagKind::ConventionViolation,
        FlagKind::BelowConfidenceFloor,
    ] {
        let bytes = k.encode();
        let mut r = CanonReader::new(&bytes);
        assert_eq!(FlagKind::decode(&mut r).unwrap(), k);
    }
}

#[test]
fn flag_roundtrips() {
    let f = Flag {
        kind: FlagKind::BelowConfidenceFloor,
        what: "1.0..1.4".into(),
        count: 3,
        reason: "below the CVS clustering confidence floor".into(),
    };
    let bytes = f.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(Flag::decode(&mut r).unwrap(), f);
}

#[test]
fn flag_count_zero_is_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(1, true, FlagKind::ConventionViolation.encode());
    rw.field(2, true, b"x".to_vec());
    rw.field(3, true, crate::canon::uvarint_value(0));
    rw.field(4, true, b"why".to_vec());
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match Flag::decode(&mut r) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

#[test]
fn import_provenance_roundtrips_with_and_without_params() {
    let mut params = std::collections::BTreeMap::new();
    params.insert("floor".to_string(), "2".to_string());
    let with = ImportProvenance {
        source: sample_source(),
        brygge_version: "0.1.0".into(),
        decoder: "brygge-decode-git".into(),
        decoder_version: "0.1.0".into(),
        params,
    };
    let bytes = with.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(ImportProvenance::decode(&mut r).unwrap(), with);

    let without = ImportProvenance {
        params: std::collections::BTreeMap::new(),
        ..with
    };
    let bytes = without.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(ImportProvenance::decode(&mut r).unwrap(), without);
}

// ---- ChangeAtom / AtomId ------------------------------------------------------------------------

#[test]
fn atom_id_is_deterministic_and_content_sensitive() {
    let a1 = atom("same", b"x");
    let a2 = atom("same", b"x");
    let a3 = atom("different", b"x");
    assert_eq!(a1.id, a2.id); // identical content โ†’ identical id
    assert_ne!(a1.id, a3.id); // different content โ†’ different id
    assert_eq!(a1.id.to_hex().len(), 64);
}

#[test]
fn atom_id_excludes_only_field_1() {
    // Two atoms differing only in their (irrelevant, since it's recomputed) stored id field must
    // compute the same id โ€” the id is a function of fields 2-7 alone.
    let mut a = atom("m", b"y");
    a.id = AtomId([0u8; 32]);
    let id_a = a.compute_id();
    a.id = AtomId([0xff; 32]);
    let id_b = a.compute_id();
    assert_eq!(id_a, id_b);
}

#[test]
fn atom_decode_rejects_a_wrong_stored_id() {
    let mut a = atom("m", b"y");
    a.id = AtomId([0xAB; 32]); // corrupt the stored id
    let bytes = a.encode();
    let mut r = CanonReader::new(&bytes);
    assert!(ChangeAtom::decode(&mut r, 4).is_err());
}

#[test]
fn atom_roundtrips_with_ops_and_copies() {
    let mut a = ChangeAtom {
        id: AtomId([0u8; 32]),
        parents: vec![AtomId([1u8; 32])],
        ops: vec![
            PathOp::Add {
                path: "a.txt".into(),
                content: Content::blob(BlobId([2u8; 32]), 0o100644),
                status: EpistemicStatus::Stated,
            },
            PathOp::Delete {
                path: "old.txt".into(),
                status: EpistemicStatus::Stated,
            },
        ],
        copies: vec![CopyRecord {
            from: "old.txt".into(),
            from_atom: AtomId([1u8; 32]),
            to: "a.txt".into(),
            status: EpistemicStatus::Stated,
        }],
        metadata: MetadataClaims::default(),
        source: sample_source(),
        status: EpistemicStatus::Stated,
    };
    a.id = a.compute_id();
    assert!(a.is_move(&a.copies[0]));

    let bytes = a.encode();
    let mut r = CanonReader::new(&bytes);
    assert_eq!(ChangeAtom::decode(&mut r, 4).unwrap(), a);
}

#[test]
fn ops_out_of_order_are_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(1, true, [0u8; 32].to_vec());
    let ops = [
        PathOp::Delete {
            path: "b".into(),
            status: EpistemicStatus::Stated,
        },
        PathOp::Delete {
            path: "a".into(),
            status: EpistemicStatus::Stated,
        },
    ];
    rw.field(
        3,
        true,
        crate::canon::list_value(ops.iter().map(PathOp::encode)),
    );
    rw.field(6, true, sample_source().encode());
    rw.field(7, true, EpistemicStatus::Stated.encode());
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match ChangeAtom::decode(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

#[test]
fn copies_out_of_order_are_rejected() {
    let from_atom = AtomId([1u8; 32]);
    let copies = [
        CopyRecord {
            from: "x".into(),
            from_atom,
            to: "b".into(),
            status: EpistemicStatus::Stated,
        },
        CopyRecord {
            from: "x".into(),
            from_atom,
            to: "a".into(),
            status: EpistemicStatus::Stated,
        },
    ];
    let mut rw = RecordWriter::new();
    rw.field(1, true, [0u8; 32].to_vec());
    rw.field(
        4,
        true,
        crate::canon::list_value(copies.iter().map(CopyRecord::encode)),
    );
    rw.field(6, true, sample_source().encode());
    rw.field(7, true, EpistemicStatus::Stated.encode());
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match ChangeAtom::decode(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

#[test]
fn metadata_encoded_but_every_claim_absent_is_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(1, true, [0u8; 32].to_vec());
    rw.field(5, true, MetadataClaims::default().encode());
    rw.field(6, true, sample_source().encode());
    rw.field(7, true, EpistemicStatus::Stated.encode());
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match ChangeAtom::decode(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

/// AtomId compatibility vector (RFC 011 ยง7.6): pins one literal hash for a fixed atom, so a change to
/// the codec or the model's field order is caught as a regression rather than silently shipped.
#[test]
fn atom_id_compatibility_vector() {
    let a = atom("same", b"x");
    assert_eq!(
        a.id.to_hex(),
        "95b657712f771e76c275d509d6108a05db812c5bf07dc5e3771f88c232626610",
    );
}

// ---- Ir -----------------------------------------------------------------------------------------

#[test]
fn ir_refs_out_of_order_are_rejected() {
    let a = atom("m", b"x");
    let target = a.id;
    let mut rw = RecordWriter::new();
    rw.field(
        1,
        true,
        crate::canon::list_value(std::iter::once(a.encode())),
    );
    let refs = [
        RefRecord {
            name: "b".into(),
            kind: RefKind::Branch,
            target,
            status: EpistemicStatus::Stated,
            source: None,
            annotation: None,
        },
        RefRecord {
            name: "a".into(),
            kind: RefKind::Branch,
            target,
            status: EpistemicStatus::Stated,
            source: None,
            annotation: None,
        },
    ];
    rw.field(
        2,
        true,
        crate::canon::list_value(refs.iter().map(RefRecord::encode)),
    );
    let prov = ImportProvenance {
        source: sample_source(),
        brygge_version: "0".into(),
        decoder: "d".into(),
        decoder_version: "0".into(),
        params: std::collections::BTreeMap::new(),
    };
    rw.field(3, true, prov.encode());
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match Ir::decode_metadata(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

fn sample_provenance() -> ImportProvenance {
    ImportProvenance {
        source: sample_source(),
        brygge_version: "0".into(),
        decoder: "d".into(),
        decoder_version: "0".into(),
        params: std::collections::BTreeMap::new(),
    }
}

#[test]
fn ir_dropped_out_of_order_is_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(3, true, sample_provenance().encode());
    let dropped = [
        DropRecord {
            class: LossClass::Other,
            what: "z".into(),
            reason: "r".into(),
            step: None,
        },
        DropRecord {
            class: LossClass::Other,
            what: "a".into(),
            reason: "r".into(),
            step: None,
        },
    ];
    rw.field(
        4,
        true,
        crate::canon::list_value(dropped.iter().map(DropRecord::encode)),
    );
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match Ir::decode_metadata(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}

#[test]
fn ir_flags_out_of_order_are_rejected() {
    let mut rw = RecordWriter::new();
    rw.field(3, true, sample_provenance().encode());
    let flags = [
        Flag {
            kind: FlagKind::ConventionViolation,
            what: "z".into(),
            count: 1,
            reason: "r".into(),
        },
        Flag {
            kind: FlagKind::ConventionViolation,
            what: "a".into(),
            count: 1,
            reason: "r".into(),
        },
    ];
    rw.field(
        5,
        true,
        crate::canon::list_value(flags.iter().map(Flag::encode)),
    );
    let bytes = rw.into_bytes();
    let mut r = CanonReader::new(&bytes);
    match Ir::decode_metadata(&mut r, 4) {
        Err(Error::NonCanonical(_)) => {}
        other => panic!("expected NonCanonical, got {other:?}"),
    }
}