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
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
//! The IR types (RFC 001 D-1/D-3/D-4, re-cut by RFC 011 §2.4).
//!
//! A content store (in [`crate::content`]) plus a DAG of [`ChangeAtom`]s plus per-import
//! [`ImportProvenance`] and [`LossBoundary`]. Each atom holds the source's **literal** path operations
//! and — separately — marked [`CopyRecord`]s, so a rename never hides the delete+create the source
//! actually recorded (D-3). There is **no node-identity type**: the IR carries evidence for identity,
//! never identity (D-4). Every type has one canonical, tagged-record encoding (RFC 011 §2.4), used for
//! the artifact and for [`AtomId`] computation.

use std::collections::BTreeMap;

use sha2::{Digest, Sha256};

use crate::Error;
use crate::canon::{CanonReader, CanonWriter, RecordWriter, list_value, map_value};
use crate::content::{ContentStore, to_hex};
use crate::status::EpistemicStatus;

pub use crate::content::BlobId;

/// Text carried as the bytes the source gave, with an optional declared encoding (RFC 011 D-2): a
/// commit message or identity name/email is **not** assumed to be UTF-8 just because most sources are.
/// `encoding` is `None` unless the source declared one; the bytes are carried unchanged either way.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Text {
    /// The raw bytes, exactly as the source gave them (may be empty).
    pub bytes: Vec<u8>,
    /// The encoding the source declared, if any (e.g. Git's `encoding` commit header). `None` does not
    /// mean UTF-8 — it means the source did not say.
    pub encoding: Option<String>,
}

impl Text {
    /// A `Text` from a Rust string, with no declared encoding.
    #[must_use]
    pub fn utf8(s: &str) -> Self {
        Self {
            bytes: s.as_bytes().to_vec(),
            encoding: None,
        }
    }

    /// The bytes decoded as UTF-8, if they are valid UTF-8 (regardless of `encoding`).
    #[must_use]
    pub fn as_utf8(&self) -> Option<&str> {
        std::str::from_utf8(&self.bytes).ok()
    }
}

/// A point in time as the source stated it: seconds since the Unix epoch, plus the source's own UTC
/// offset if it gave one (RFC 011 D-2). The offset is carried, never normalized away — two sources'
/// times are comparable only in `seconds`, not "local time".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Time {
    /// Seconds since the Unix epoch, as the source stated (may be negative).
    pub seconds: i64,
    /// The source's own UTC offset in minutes, if it recorded one; `None` when the source gave no
    /// offset (e.g. a bare epoch timestamp).
    pub offset_minutes: Option<i16>,
}

/// Which source system an identity came from.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SourceKind {
    /// Git.
    Git,
    /// Mercurial.
    Hg,
    /// Subversion.
    Svn,
    /// CVS.
    Cvs,
    /// A source this build does not name; the label is preserved.
    Other(String),
}

/// One opaque cryptographic signature the source carried over its own object (e.g. Git's `gpgsig`),
/// labelled so a reader knows what it signs without brygge interpreting it (RFC 011 D-6). Never
/// verified by brygge.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Signature {
    /// What the signature is (e.g. `"gpgsig"`, `"gpgsig-sha256"`).
    pub label: String,
    /// The signature's raw bytes, exactly as the source stored them.
    pub bytes: Vec<u8>,
}

/// One opaque, source-specific datum brygge does not model by name, carried rather than dropped (RFC
/// 011 D-6): a labelled bag for source data with no home elsewhere in the IR.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Extra {
    /// What the datum is, in the source's own terms (e.g. `"mergetag"`).
    pub label: String,
    /// Its raw bytes, exactly as the source stored them.
    pub bytes: Vec<u8>,
}

/// The source's own opaque identifiers, signatures and unclassified extras (`PR-4/IR-3`) — the only
/// cryptographic link back to the original. Carried unchanged; they verify nothing in any target.
///
/// `Hash` (RFC 018 D-6): `brygge_ir::transform` matches atoms between an input and output artifact by
/// this value, so it needs to key a map.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SourceIdentity {
    /// The source system.
    pub kind: SourceKind,
    /// Opaque repository identity (e.g. a root commit id, a UUID).
    pub repo_id: Vec<u8>,
    /// Opaque atom identity (e.g. a Git commit SHA, an SVN revision, a CVS revision tag).
    pub atom_id: Vec<u8>,
    /// Opaque signatures, in source order.
    pub signatures: Vec<Signature>,
    /// Opaque, unclassified extras, in source order.
    pub extras: Vec<Extra>,
}

/// What is at a path (RFC 021 D-1): the only two things brygge ever carries there. The wire mirrors this
/// choice exactly — a state with both a blob and a submodule, or neither, cannot be written at all.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Content {
    /// Ordinary file content.
    Blob {
        /// Content address.
        blob: BlobId,
        /// Unix-style file mode.
        mode: u32,
    },
    /// A pinned reference to a commit in another Git repository; brygge never reads, fetches or
    /// verifies that repository. `commit` is the pinned commit id, exactly as the source stated it: 20
    /// bytes for a SHA-1 repository, 32 for SHA-256 (the floor's `sha256-object-format` keeps the
    /// decoder from ever producing the latter today, but the wire admits it so lifting that floor item
    /// later needs no contract change).
    Submodule {
        /// The pinned commit id (20 or 32 bytes).
        commit: Vec<u8>,
    },
}

impl Content {
    /// Convenience constructor for ordinary file content — keeps call sites readable (RFC 021 D-1).
    #[must_use]
    pub fn blob(blob: BlobId, mode: u32) -> Self {
        Self::Blob { blob, mode }
    }

    /// Convenience constructor for a pinned submodule reference — keeps call sites readable, the same
    /// reason [`Self::blob`] exists (RFC 021 D-1, batch G). Does not check `commit`'s length; that is
    /// [`crate::builder::IrBuilder::add_atom`]'s job, once, at the point an atom is actually built.
    #[must_use]
    pub fn submodule(commit: Vec<u8>) -> Self {
        Self::Submodule { commit }
    }
}

/// One path operation within an atom, each carrying its own epistemic status (D-2/D-3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathOp {
    /// A path created with the given content.
    Add {
        /// Repo-relative path.
        path: String,
        /// What is now at this path.
        content: Content,
        /// Stated or derived.
        status: EpistemicStatus,
    },
    /// A path's content changed, its kind (blob or submodule) unchanged — a submodule's `Modify` is a
    /// moved pointer, not a new kind (RFC 021 D-1). A change of kind at one path is `Replace`.
    Modify {
        /// Repo-relative path.
        path: String,
        /// The new content, of the same kind the path already held.
        content: Content,
        /// Stated or derived.
        status: EpistemicStatus,
    },
    /// A path removed.
    Delete {
        /// Repo-relative path.
        path: String,
        /// Stated or derived.
        status: EpistemicStatus,
    },
    /// A path replaced in place — a source that draws a distinction between "modify" and "replace"
    /// (e.g. a symlink swapped for a regular file at the same path), or a change of kind between a
    /// blob and a submodule (RFC 021 D-1), states it here rather than being folded into `Modify` (RFC
    /// 011 D-7).
    Replace {
        /// Repo-relative path.
        path: String,
        /// The new content, of either kind.
        content: Content,
        /// Stated or derived.
        status: EpistemicStatus,
    },
}

/// A marked record that one path is a copy of another at a specific earlier atom (D-3, RFC 011 D-5).
/// `Stated` when the source recorded it (e.g. `hg mv`, an SVN copy); `Derived` when brygge inferred it
/// (e.g. Git similarity). Sits *beside* the literal delete+create/add ops, never replacing them.
///
/// A **move** is exactly: `from_atom` is the atom's first parent **and** the atom's own ops delete
/// `from` — see [`ChangeAtom::is_move`]. Anything else (a copy from a non-parent atom, or a copy whose
/// source path survives) is a copy that is not a move.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CopyRecord {
    /// The source path, as it existed in `from_atom`.
    pub from: String,
    /// The atom `from` is copied from — always an atom earlier in canonical order than the one this
    /// record belongs to.
    pub from_atom: AtomId,
    /// The destination path, in this atom.
    pub to: String,
    /// Stated or derived.
    pub status: EpistemicStatus,
}

/// An author/committer identity, carried as a *claim* (`PR-3`), never verified.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Identity {
    /// Claimed name, as the source's raw bytes.
    pub name: Text,
    /// Claimed email, as the source's raw bytes, if the source gave one.
    pub email: Option<Text>,
}

/// Message and authorship metadata, as claims not verified facts (`PR-3`). Times are source-stated and
/// identity-bearing (they are part of what the source recorded).
///
/// **The one-claim rule:** `author`/`author_time` hold what the source attributes the change to —
/// brygge's best single claim of authorship. `committer`/`commit_time` hold only a **distinct**
/// recording identity or time the source itself states (e.g. Git's separate committer); a source with
/// no such distinction leaves them `None` rather than duplicating `author`/`author_time`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MetadataClaims {
    /// Claimed author.
    pub author: Option<Identity>,
    /// Claimed author time.
    pub author_time: Option<Time>,
    /// Claimed committer — only when the source states one distinct from the author.
    pub committer: Option<Identity>,
    /// Claimed commit time — only when the source states one distinct from the author time.
    pub commit_time: Option<Time>,
    /// Claimed message.
    pub message: Option<Text>,
}

impl MetadataClaims {
    /// True when every claim is absent — the condition under which `ChangeAtom` omits its `metadata`
    /// field entirely (RFC 011 §2.4).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.author.is_none()
            && self.author_time.is_none()
            && self.committer.is_none()
            && self.commit_time.is_none()
            && self.message.is_none()
    }
}

/// A change atom's IR-local identity: SHA-256 over its canonical record encoding, excluding field 1
/// (D-4, RFC 011 §2.4). **Not** a source id and **not** a target node id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AtomId(pub [u8; 32]);

impl AtomId {
    /// A lowercase-hex rendering.
    #[must_use]
    pub fn to_hex(&self) -> String {
        to_hex(&self.0)
    }
}

impl std::fmt::Display for AtomId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.to_hex())
    }
}

/// One atom of history (a commit / revision / reconstructed changeset), with an atom-level epistemic
/// status (`Stated` for git/hg/svn, `Derived` for a reconstructed CVS changeset).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChangeAtom {
    /// The computed IR-local id.
    pub id: AtomId,
    /// Parent atom ids, order significant (`PR-2`).
    pub parents: Vec<AtomId>,
    /// The source's literal path operations, in canonical path order.
    pub ops: Vec<PathOp>,
    /// Marked copy records, in canonical order.
    pub copies: Vec<CopyRecord>,
    /// Message/authorship claims; absent when the source gave none.
    pub metadata: MetadataClaims,
    /// The source's opaque identity for this atom.
    pub source: SourceIdentity,
    /// Whether the atom itself is stated or derived.
    pub status: EpistemicStatus,
}

impl ChangeAtom {
    /// True when `copy` represents this atom moving `copy.from` to `copy.to`: `copy.from_atom` is this
    /// atom's first parent, **and** this atom's own ops delete `copy.from` (RFC 011 D-5). A copy that
    /// does not meet both conditions is a copy, not a move.
    #[must_use]
    pub fn is_move(&self, copy: &CopyRecord) -> bool {
        self.parents.first() == Some(&copy.from_atom)
            && self
                .ops
                .iter()
                .any(|op| matches!(op, PathOp::Delete { path, .. } if path == &copy.from))
    }
}

/// The kind of a ref pointer.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum RefKind {
    /// A branch.
    Branch,
    /// A tag.
    Tag,
    /// A Mercurial-style bookmark.
    Bookmark,
    /// A Mercurial-style named branch.
    NamedBranch,
    /// A kind this build does not name.
    Other(String),
}

/// A tag/ref's own annotation, when the source carries one distinct from the ref pointer itself (e.g.
/// an annotated Git tag object) — RFC 011 D-6.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Annotation {
    /// Who made the annotation, if the source states one.
    pub tagger: Option<Identity>,
    /// When it was made, if the source states one.
    pub time: Option<Time>,
    /// The annotation's message, if the source states one.
    pub message: Option<Text>,
}

/// A ref pointer into the atom DAG (`PR-2`). A reconstructed SVN branch is `Derived`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RefRecord {
    /// The ref name.
    pub name: String,
    /// Its kind.
    pub kind: RefKind,
    /// The atom it points at.
    pub target: AtomId,
    /// Stated or derived.
    pub status: EpistemicStatus,
    /// The source's opaque identity for the ref, if any.
    pub source: Option<SourceIdentity>,
    /// The ref's own annotation, if the source carries one distinct from the pointer.
    pub annotation: Option<Annotation>,
}

/// The class of a dropped datum (RFC 002 D-2). Dropping is permitted only for the first two; the
/// never-silently-omit class (`PR-9`) must be carried or explicitly noted, never a silent drop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LossClass {
    /// Representation rather than assertion (packfiles, deltas, index, reflogs).
    Representation,
    /// Advisory data known to be unreliable (SVN mergeinfo, hg obsmarkers).
    AdvisoryUnreliable,
    /// Any other explicitly-recorded drop.
    Other,
    /// A transform step dropped this (RFC 018 D-5) — `DropRecord::step` names which one.
    Transform,
}

/// One recorded drop: what class, what was dropped, and why (`HO-2`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DropRecord {
    /// The class.
    pub class: LossClass,
    /// What was dropped.
    pub what: String,
    /// Why it was safe to drop.
    pub reason: String,
    /// Which transform step dropped this (RFC 018 D-5): required when `class` is
    /// [`LossClass::Transform`], absent for every other class.
    pub step: Option<u64>,
}

/// The boundary of loss for an import (`HO-2/IR-4`). The *derived* side of the boundary is computed from
/// the atoms by [`crate::honesty::summary`]; this records the *dropped* side.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LossBoundary {
    /// Everything the decoder dropped, by class, with reasons.
    pub dropped: Vec<DropRecord>,
}

/// Which kind of attention-worthy condition a [`Flag`] records (RFC 011 D-8): a typed replacement for
/// the old magic-string exit-30 detection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FlagKind {
    /// A source convention the decoder expected did not hold (e.g. an SVN branch layout it could not
    /// resolve).
    ConventionViolation,
    /// A confidence value fell below the decoder's own floor for the class of inference involved.
    BelowConfidenceFloor,
}

/// One flagged condition surfaced to the caller — drives CLI exit 30 (RFC 011 D-8). Unlike a
/// [`DropRecord`], nothing here was dropped; a flag says "this import needs your attention", not "this
/// datum is missing".
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Flag {
    /// The kind of condition.
    pub kind: FlagKind,
    /// What the flag concerns (a path, a revision range, a layout description).
    pub what: String,
    /// How many occurrences this flag summarizes (at least 1).
    pub count: u64,
    /// Why this was flagged rather than silently accepted.
    pub reason: String,
}

/// Per-import provenance (`PR-6`): what it was made from and by what. Separable from the history it
/// describes (`PX-02`).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ImportProvenance {
    /// The source repository identity.
    pub source: SourceIdentity,
    /// The brygge version that produced this import.
    pub brygge_version: String,
    /// The decoder id.
    pub decoder: String,
    /// The decoder version.
    pub decoder_version: String,
    /// Every inference parameter that governed the import (`PR-5`), canonical/sorted.
    pub params: BTreeMap<String, String>,
}

/// The whole intermediate representation. The contract version this artifact conforms to is not a field
/// here — it travels in the container header (RFC 011 §2.3), not the metadata record.
///
/// **Not `Clone`** (RFC 015 D-3): `content` may be backed by an open spill file, which cannot be
/// cloned by copying a handle without duplicating the underlying file; nothing in this crate or its
/// decoders clones a whole `Ir` today.
#[derive(Debug, PartialEq, Eq)]
pub struct Ir {
    /// The atoms, in canonical (topological, tiebroken) order.
    pub atoms: Vec<ChangeAtom>,
    /// The refs.
    pub refs: Vec<RefRecord>,
    /// The import provenance.
    pub provenance: ImportProvenance,
    /// The loss boundary.
    pub loss: LossBoundary,
    /// Flagged conditions (RFC 011 D-8).
    pub flags: Vec<Flag>,
    /// The content store.
    pub content: ContentStore,
    /// Transform records (RFC 018 D-5), oldest first; empty for a decoder's own artifact.
    pub transforms: Vec<TransformRecord>,
}

/// One part of an atom's, an op's, or a ref's status a transform changed (RFC 018 D-5), from contract
/// 0.3.0's closed vocabulary (`ir-artifact-format.md`). The Rust API, not a raw string, so a caller
/// cannot misspell one; [`ChangedPart::as_str`]/[`ChangedPart::parse`] are the only way in or out of the
/// wire's `list<text>` representation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChangedPart {
    /// An atom's claimed author.
    Author,
    /// An atom's claimed author time.
    AuthorTime,
    /// An atom's claimed committer.
    Committer,
    /// An atom's claimed commit time.
    CommitTime,
    /// An atom's claimed message.
    Message,
    /// An atom's own path operations.
    Ops,
    /// An atom's own copy records.
    Copies,
    /// An atom's own parents (RFC 018 D-6, R-a: removing an atom rewires its children's parents).
    Parents,
    /// An op's content address.
    Blob,
    /// An op's file mode.
    Mode,
    /// An op's path.
    Path,
    /// A ref's annotation.
    Annotation,
    /// A ref's kind.
    Kind,
    /// A ref's name.
    Name,
    /// A ref's target atom.
    Target,
}

impl ChangedPart {
    /// The spelling this part is carried as on the wire (RFC 018 D-5's closed vocabulary).
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Author => "author",
            Self::AuthorTime => "author-time",
            Self::Committer => "committer",
            Self::CommitTime => "commit-time",
            Self::Message => "message",
            Self::Ops => "ops",
            Self::Copies => "copies",
            Self::Parents => "parents",
            Self::Blob => "blob",
            Self::Mode => "mode",
            Self::Path => "path",
            Self::Annotation => "annotation",
            Self::Kind => "kind",
            Self::Name => "name",
            Self::Target => "target",
        }
    }

    /// Parse a wire spelling, `None` for anything outside the closed vocabulary.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        Some(match s {
            "author" => Self::Author,
            "author-time" => Self::AuthorTime,
            "committer" => Self::Committer,
            "commit-time" => Self::CommitTime,
            "message" => Self::Message,
            "ops" => Self::Ops,
            "copies" => Self::Copies,
            "parents" => Self::Parents,
            "blob" => Self::Blob,
            "mode" => Self::Mode,
            "path" => Self::Path,
            "annotation" => Self::Annotation,
            "kind" => Self::Kind,
            "name" => Self::Name,
            "target" => Self::Target,
            _ => return None,
        })
    }

    /// True on an atom's own status (RFC 018 D-5's atom vocabulary).
    #[must_use]
    pub fn valid_on_atom(&self) -> bool {
        matches!(
            self,
            Self::Author
                | Self::AuthorTime
                | Self::Committer
                | Self::CommitTime
                | Self::Message
                | Self::Ops
                | Self::Copies
                | Self::Parents
        )
    }

    /// True on an op's own status (RFC 018 D-5's op vocabulary).
    #[must_use]
    pub fn valid_on_op(&self) -> bool {
        matches!(self, Self::Blob | Self::Mode | Self::Path)
    }

    /// True on a ref's own status (RFC 018 D-5's ref vocabulary).
    #[must_use]
    pub fn valid_on_ref(&self) -> bool {
        matches!(
            self,
            Self::Annotation | Self::Kind | Self::Name | Self::Target
        )
    }
}

/// `true` for a 64-byte string of lowercase hex digits — the wire spelling of an [`AtomId`] in a
/// `Transform`-class drop's `what` (RFC 018 D-6, R-b).
fn is_lower_hex_atom_id(s: &str) -> bool {
    s.len() == 64
        && s.bytes()
            .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// The grammar a `Transform`-class [`DropRecord::what`] must match (RFC 018 D-6, R-b): exactly one of
/// `atom <id>`, `op <id> <path>`, `copy <id> <to>`, or `ref <kind> <name>` (`<kind>` one of `branch`,
/// `tag`, `bookmark`, `named-branch`, or `other:<label>`) — so every loss a transform records names
/// exactly one thing, and a reader can count them. The single space after the leading word is the only
/// separator; a path or a name runs to the end of the line (so it may itself contain spaces). Every
/// `<id>` is the *input* artifact's own `AtomId` — the one the step's own record cites as `consumed` —
/// never the output's. Every other loss class carries free text and is not checked this way.
fn is_valid_transform_drop_what(what: &str) -> bool {
    if let Some(id) = what.strip_prefix("atom ") {
        return is_lower_hex_atom_id(id);
    }
    if let Some(rest) = what.strip_prefix("op ") {
        return rest
            .split_once(' ')
            .is_some_and(|(id, _path)| is_lower_hex_atom_id(id));
    }
    if let Some(rest) = what.strip_prefix("copy ") {
        return rest
            .split_once(' ')
            .is_some_and(|(id, _to)| is_lower_hex_atom_id(id));
    }
    if let Some(rest) = what.strip_prefix("ref ") {
        return rest.split_once(' ').is_some_and(|(kind, _name)| {
            matches!(kind, "branch" | "tag" | "bookmark" | "named-branch")
                || kind.starts_with("other:")
        });
    }
    false
}

/// The plugin-name grammar a [`TransformRecord::name`] must match (RFC 018 D-5): lowercase ASCII
/// letters, digits and hyphens, starting with a letter or digit, at most 64 bytes.
fn is_valid_transform_name(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.is_empty() || bytes.len() > 64 {
        return false;
    }
    let is_lower_alnum = |b: u8| b.is_ascii_lowercase() || b.is_ascii_digit();
    match bytes.split_first() {
        Some((&first, rest)) => {
            is_lower_alnum(first) && rest.iter().all(|&b| is_lower_alnum(b) || b == b'-')
        }
        None => false,
    }
}

/// One record of a transform program's own run over an artifact (RFC 018 D-5): what program, what
/// version, with what parameters, over which artifact — named by [`TransformRecord::consumed`], the
/// D-3 digest of the artifact this step read. [`Ir::transforms`] holds these oldest first; record *k*'s
/// own output is implied — it is record *k + 1*'s `consumed`, or, for the last record, the artifact's
/// own digest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TransformRecord {
    /// The transform's own name (the plugin grammar: `[a-z0-9][a-z0-9-]*`, at most 64 bytes).
    pub name: String,
    /// The transform's version.
    pub version: String,
    /// Every parameter that governed this run, canonical/sorted.
    pub params: BTreeMap<String, String>,
    /// The D-3 digest of the artifact this step read.
    pub consumed: [u8; 32],
}

// ---- canonical encode/decode (RFC 011 §2.1/§2.2/§2.4) --------------------------------------------

impl SourceKind {
    fn encode(&self) -> Vec<u8> {
        let mut w = CanonWriter::new();
        let variant = match self {
            Self::Git => 0,
            Self::Hg => 1,
            Self::Svn => 2,
            Self::Cvs => 3,
            Self::Other(_) => 4,
        };
        w.uvarint(variant);
        let mut rw = RecordWriter::new();
        if let Self::Other(label) = self {
            rw.field(1, true, label.as_bytes().to_vec());
        }
        rw.finish_into(&mut w);
        w.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        match r.uvarint()? {
            v @ 0..=3 => {
                r.record_fields("SourceKind", |_, _, _| Ok(false))?;
                Ok(match v {
                    0 => Self::Git,
                    1 => Self::Hg,
                    2 => Self::Svn,
                    _ => Self::Cvs,
                })
            }
            4 => {
                let mut label = None;
                r.record_fields("SourceKind::Other", |r, id, len| {
                    if id == 1 {
                        label = Some(r.text(len)?);
                        Ok(true)
                    } else {
                        Ok(false)
                    }
                })?;
                Ok(Self::Other(label.ok_or_else(|| {
                    Error::NonCanonical("SourceKind::Other missing field 1 (label)".to_string())
                })?))
            }
            o => Err(Error::Decode(format!("unknown SourceKind variant {o}"))),
        }
    }
}

impl Text {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.bytes.clone());
        if let Some(enc) = &self.encoding {
            rw.field(2, true, enc.as_bytes().to_vec());
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut bytes = None;
        let mut encoding = None;
        r.record_fields("Text", |r, id, len| match id {
            1 => {
                bytes = Some(r.bytes_exact(len)?);
                Ok(true)
            }
            2 => {
                encoding = Some(r.text(len)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            bytes: bytes
                .ok_or_else(|| Error::NonCanonical("Text missing field 1 (bytes)".to_string()))?,
            encoding,
        })
    }
}

impl Time {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, crate::canon::svarint_value(self.seconds));
        if let Some(off) = self.offset_minutes {
            rw.field(2, true, crate::canon::svarint_value(i64::from(off)));
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut seconds = None;
        let mut offset_minutes = None;
        r.record_fields("Time", |r, id, _len| match id {
            1 => {
                seconds = Some(r.svarint()?);
                Ok(true)
            }
            2 => {
                let v = r.svarint()?;
                let v = i16::try_from(v).map_err(|_| {
                    Error::NonCanonical("Time.offset_minutes does not fit i16".to_string())
                })?;
                offset_minutes = Some(v);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            seconds: seconds
                .ok_or_else(|| Error::NonCanonical("Time missing field 1 (seconds)".to_string()))?,
            offset_minutes,
        })
    }
}

impl Signature {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.label.as_bytes().to_vec());
        rw.field(2, true, self.bytes.clone());
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut label = None;
        let mut bytes = None;
        r.record_fields("Signature", |r, id, len| match id {
            1 => {
                label = Some(r.text(len)?);
                Ok(true)
            }
            2 => {
                bytes = Some(r.bytes_exact(len)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            label: label.ok_or_else(|| {
                Error::NonCanonical("Signature missing field 1 (label)".to_string())
            })?,
            bytes: bytes.ok_or_else(|| {
                Error::NonCanonical("Signature missing field 2 (bytes)".to_string())
            })?,
        })
    }
}

impl Extra {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.label.as_bytes().to_vec());
        rw.field(2, true, self.bytes.clone());
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut label = None;
        let mut bytes = None;
        r.record_fields("Extra", |r, id, len| match id {
            1 => {
                label = Some(r.text(len)?);
                Ok(true)
            }
            2 => {
                bytes = Some(r.bytes_exact(len)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            label: label
                .ok_or_else(|| Error::NonCanonical("Extra missing field 1 (label)".to_string()))?,
            bytes: bytes
                .ok_or_else(|| Error::NonCanonical("Extra missing field 2 (bytes)".to_string()))?,
        })
    }
}

impl SourceIdentity {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.kind.encode());
        rw.field(2, true, self.repo_id.clone());
        rw.field(3, true, self.atom_id.clone());
        if !self.signatures.is_empty() {
            rw.field(
                4,
                true,
                list_value(self.signatures.iter().map(Signature::encode)),
            );
        }
        if !self.extras.is_empty() {
            rw.field(5, true, list_value(self.extras.iter().map(Extra::encode)));
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut kind = None;
        let mut repo_id = None;
        let mut atom_id = None;
        let mut signatures = Vec::new();
        let mut extras = Vec::new();
        r.record_fields("SourceIdentity", |r, id, len| match id {
            1 => {
                kind = Some(SourceKind::decode(r)?);
                Ok(true)
            }
            2 => {
                repo_id = Some(r.bytes_exact(len)?);
                Ok(true)
            }
            3 => {
                atom_id = Some(r.bytes_exact(len)?);
                Ok(true)
            }
            4 => {
                signatures = r.list(Signature::decode)?;
                non_empty_list("SourceIdentity.signatures", &signatures)?;
                Ok(true)
            }
            5 => {
                extras = r.list(Extra::decode)?;
                non_empty_list("SourceIdentity.extras", &extras)?;
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            kind: kind.ok_or_else(|| {
                Error::NonCanonical("SourceIdentity missing field 1 (kind)".to_string())
            })?,
            repo_id: repo_id.ok_or_else(|| {
                Error::NonCanonical("SourceIdentity missing field 2 (repo_id)".to_string())
            })?,
            atom_id: atom_id.ok_or_else(|| {
                Error::NonCanonical("SourceIdentity missing field 3 (atom_id)".to_string())
            })?,
            signatures,
            extras,
        })
    }
}

fn non_empty_list<T>(field: &'static str, v: &[T]) -> Result<(), Error> {
    if v.is_empty() {
        Err(Error::NonCanonical(format!("{field} encoded but empty")))
    } else {
        Ok(())
    }
}

impl PathOp {
    /// The path this op concerns (its canonical sort key).
    #[must_use]
    pub fn path(&self) -> &str {
        match self {
            Self::Add { path, .. }
            | Self::Modify { path, .. }
            | Self::Delete { path, .. }
            | Self::Replace { path, .. } => path,
        }
    }
    /// This op's own epistemic status (RFC 018 D-5: where a transform may mark it `Transformed`).
    #[must_use]
    pub fn status(&self) -> &EpistemicStatus {
        match self {
            Self::Add { status, .. }
            | Self::Modify { status, .. }
            | Self::Delete { status, .. }
            | Self::Replace { status, .. } => status,
        }
    }
    /// What this op puts at its path — `None` for `Delete` (RFC 021 D-1). No accessor collapses this to
    /// a `BlobId`: a caller must match on the kind.
    #[must_use]
    pub fn content(&self) -> Option<&Content> {
        match self {
            Self::Add { content, .. }
            | Self::Modify { content, .. }
            | Self::Replace { content, .. } => Some(content),
            Self::Delete { .. } => None,
        }
    }
    /// `PathOp`'s wire is flat and additive (RFC 021 D-1, revised by review 186): a blob entry's fields
    /// (`1 path, 2 blob, 3 mode, 4 status`) are **unchanged byte for byte** from before this RFC, so
    /// [`ChangeAtom::compute_id`] — which hashes this same encoding — never changes for existing content.
    /// A submodule entry instead carries `5 submodule: bytes`, never both 2/3 and 5 at once. Fields are
    /// written in ascending id order, as every record requires: field 4 (`status`) therefore comes
    /// *before* field 5 for a submodule entry, even though it comes *after* fields 2/3 for a blob entry.
    fn encode(&self) -> Vec<u8> {
        let mut w = CanonWriter::new();
        let (variant, path, content, status) = match self {
            Self::Add {
                path,
                content,
                status,
            } => (0, path, Some(content), status),
            Self::Modify {
                path,
                content,
                status,
            } => (1, path, Some(content), status),
            Self::Delete { path, status } => (2, path, None, status),
            Self::Replace {
                path,
                content,
                status,
            } => (3, path, Some(content), status),
        };
        w.uvarint(variant);
        let mut rw = RecordWriter::new();
        rw.field(1, true, path.as_bytes().to_vec());
        match content {
            Some(Content::Blob { blob, mode }) => {
                rw.field(2, true, blob.as_bytes().to_vec());
                rw.field(3, true, crate::canon::uvarint_value(u64::from(*mode)));
                rw.field(4, true, status.encode());
            }
            Some(Content::Submodule { commit }) => {
                rw.field(4, true, status.encode());
                rw.field(5, true, commit.clone());
            }
            None => {
                rw.field(4, true, status.encode());
            }
        }
        rw.finish_into(&mut w);
        w.into_bytes()
    }
    /// Decode one `PathOp`. `minor` is the artifact's own contract minor (RFC 021 D-1, review 186):
    /// `2` and `3` recognize fields 1–4 only (field 5 is unknown to them, and so refused as critical if
    /// present); `4` and later also recognize field 5. Either way, a blob entry (fields 2 and 3) and a
    /// submodule entry (field 5) are mutually exclusive — both, or neither, is `NonCanonical`.
    fn decode(r: &mut CanonReader, minor: u32) -> Result<Self, Error> {
        let variant = r.uvarint()?;
        let mut path = None;
        let mut blob = None;
        let mut mode = None;
        let mut commit = None;
        let mut status = None;
        let handle = |r: &mut CanonReader, id: u64, len: usize| match id {
            1 => {
                path = Some(r.text(len)?);
                Ok(true)
            }
            2 => {
                blob = Some(BlobId(r.raw32()?));
                Ok(true)
            }
            3 => {
                mode = Some(read_u32(r)?);
                Ok(true)
            }
            4 => {
                status = Some(EpistemicStatus::decode(r, 0)?);
                Ok(true)
            }
            5 if minor >= 4 => {
                commit = Some(r.bytes_exact(len)?);
                Ok(true)
            }
            _ => Ok(false),
        };
        r.record_fields("PathOp", handle)?;
        let path =
            path.ok_or_else(|| Error::NonCanonical("PathOp missing field 1 (path)".to_string()))?;
        let status = status
            .ok_or_else(|| Error::NonCanonical("PathOp missing field 4 (status)".to_string()))?;
        let mut need_content = |what: &'static str| -> Result<Content, Error> {
            match (blob, mode, commit.take()) {
                (Some(blob), Some(mode), None) => Ok(Content::Blob { blob, mode }),
                (None, None, Some(commit)) => {
                    if commit.len() != 20 && commit.len() != 32 {
                        return Err(Error::NonCanonical(format!(
                            "PathOp::{what} field 5 (submodule) is {} bytes, must be 20 or 32",
                            commit.len()
                        )));
                    }
                    Ok(Content::Submodule { commit })
                }
                (None, None, None) => Err(Error::NonCanonical(format!(
                    "PathOp::{what} has neither a blob (fields 2 and 3) nor a submodule (field 5)"
                ))),
                _ => Err(Error::NonCanonical(format!(
                    "PathOp::{what} has both a blob and a submodule, or an incomplete blob (field 2 \
                     without 3, or field 3 without 2)"
                ))),
            }
        };
        Ok(match variant {
            0 => Self::Add {
                path,
                content: need_content("Add")?,
                status,
            },
            1 => Self::Modify {
                path,
                content: need_content("Modify")?,
                status,
            },
            2 => Self::Delete { path, status },
            3 => Self::Replace {
                path,
                content: need_content("Replace")?,
                status,
            },
            o => return Err(Error::Decode(format!("unknown PathOp variant {o}"))),
        })
    }
}

impl CopyRecord {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.from.as_bytes().to_vec());
        rw.field(2, true, self.from_atom.0.to_vec());
        rw.field(3, true, self.to.as_bytes().to_vec());
        rw.field(4, true, self.status.encode());
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut from = None;
        let mut from_atom = None;
        let mut to = None;
        let mut status = None;
        r.record_fields("CopyRecord", |r, id, len| match id {
            1 => {
                from = Some(r.text(len)?);
                Ok(true)
            }
            2 => {
                from_atom = Some(AtomId(r.raw32()?));
                Ok(true)
            }
            3 => {
                to = Some(r.text(len)?);
                Ok(true)
            }
            4 => {
                status = Some(EpistemicStatus::decode(r, 0)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            from: from.ok_or_else(|| {
                Error::NonCanonical("CopyRecord missing field 1 (from)".to_string())
            })?,
            from_atom: from_atom.ok_or_else(|| {
                Error::NonCanonical("CopyRecord missing field 2 (from_atom)".to_string())
            })?,
            to: to.ok_or_else(|| {
                Error::NonCanonical("CopyRecord missing field 3 (to)".to_string())
            })?,
            status: status.ok_or_else(|| {
                Error::NonCanonical("CopyRecord missing field 4 (status)".to_string())
            })?,
        })
    }
}

impl Identity {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.name.encode());
        if let Some(email) = &self.email {
            rw.field(2, true, email.encode());
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut name = None;
        let mut email = None;
        r.record_fields("Identity", |r, id, _len| match id {
            1 => {
                name = Some(Text::decode(r)?);
                Ok(true)
            }
            2 => {
                email = Some(Text::decode(r)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            name: name.ok_or_else(|| {
                Error::NonCanonical("Identity missing field 1 (name)".to_string())
            })?,
            email,
        })
    }
}

impl MetadataClaims {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        if let Some(a) = &self.author {
            rw.field(1, true, a.encode());
        }
        if let Some(t) = &self.author_time {
            rw.field(2, true, t.encode());
        }
        if let Some(c) = &self.committer {
            rw.field(3, true, c.encode());
        }
        if let Some(t) = &self.commit_time {
            rw.field(4, true, t.encode());
        }
        if let Some(m) = &self.message {
            rw.field(5, true, m.encode());
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut out = Self::default();
        r.record_fields("MetadataClaims", |r, id, _len| match id {
            1 => {
                out.author = Some(Identity::decode(r)?);
                Ok(true)
            }
            2 => {
                out.author_time = Some(Time::decode(r)?);
                Ok(true)
            }
            3 => {
                out.committer = Some(Identity::decode(r)?);
                Ok(true)
            }
            4 => {
                out.commit_time = Some(Time::decode(r)?);
                Ok(true)
            }
            5 => {
                out.message = Some(Text::decode(r)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(out)
    }
}

fn read_u32(r: &mut CanonReader) -> Result<u32, Error> {
    u32::try_from(r.uvarint()?).map_err(|_| Error::Decode("mode out of range".to_string()))
}

impl ChangeAtom {
    /// Build fields 2–7 (everything but `id`) into `rw`, in ascending order — the shared body for both
    /// the full record encoding and [`Self::compute_id`] (RFC 011 §2.4: "the record without field 1").
    fn encode_body(&self, rw: &mut RecordWriter) {
        if !self.parents.is_empty() {
            rw.field(
                2,
                true,
                list_value(self.parents.iter().map(|id| id.0.to_vec())),
            );
        }
        if !self.ops.is_empty() {
            rw.field(3, true, list_value(self.ops.iter().map(PathOp::encode)));
        }
        if !self.copies.is_empty() {
            rw.field(
                4,
                true,
                list_value(self.copies.iter().map(CopyRecord::encode)),
            );
        }
        if !self.metadata.is_empty() {
            rw.field(5, true, self.metadata.encode());
        }
        rw.field(6, true, self.source.encode());
        rw.field(7, true, self.status.encode());
    }

    /// Compute the [`AtomId`] from the record body (fields 2–7, excluding `id` itself).
    #[must_use]
    pub(crate) fn compute_id(&self) -> AtomId {
        let mut rw = RecordWriter::new();
        self.encode_body(&mut rw);
        let mut hasher = Sha256::new();
        hasher.update(rw.into_bytes());
        AtomId(hasher.finalize().into())
    }

    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.id.0.to_vec());
        self.encode_body(&mut rw);
        rw.into_bytes()
    }

    fn decode(r: &mut CanonReader, minor: u32) -> Result<Self, Error> {
        let mut id = None;
        let mut parents = Vec::new();
        let mut ops = Vec::new();
        let mut copies = Vec::new();
        let mut metadata = MetadataClaims::default();
        let mut source = None;
        let mut status = None;
        r.record_fields("ChangeAtom", |r, fid, _len| match fid {
            1 => {
                id = Some(AtomId(r.raw32()?));
                Ok(true)
            }
            2 => {
                parents = r.list(|r| Ok(AtomId(r.raw32()?)))?;
                non_empty_list("ChangeAtom.parents", &parents)?;
                Ok(true)
            }
            3 => {
                ops = r.list(|r| PathOp::decode(r, minor))?;
                non_empty_list("ChangeAtom.ops", &ops)?;
                Ok(true)
            }
            4 => {
                copies = r.list(CopyRecord::decode)?;
                non_empty_list("ChangeAtom.copies", &copies)?;
                Ok(true)
            }
            5 => {
                metadata = MetadataClaims::decode(r)?;
                if metadata.is_empty() {
                    return Err(Error::NonCanonical(
                        "ChangeAtom.metadata encoded but every claim absent".to_string(),
                    ));
                }
                Ok(true)
            }
            6 => {
                source = Some(SourceIdentity::decode(r)?);
                Ok(true)
            }
            7 => {
                status = Some(EpistemicStatus::decode(r, 0)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        let id =
            id.ok_or_else(|| Error::NonCanonical("ChangeAtom missing field 1 (id)".to_string()))?;
        // Ops must be strictly ascending by path (§2.5): one op per path per atom.
        for (a, b) in ops.iter().zip(ops.iter().skip(1)) {
            if a.path() >= b.path() {
                return Err(Error::NonCanonical(
                    "ChangeAtom.ops are not strictly ascending by path".to_string(),
                ));
            }
        }
        for (a, b) in copies.iter().zip(copies.iter().skip(1)) {
            let ka = (&a.to, &a.from, a.from_atom);
            let kb = (&b.to, &b.from, b.from_atom);
            if ka >= kb {
                return Err(Error::NonCanonical(
                    "ChangeAtom.copies are not strictly ascending by (to, from, from_atom)"
                        .to_string(),
                ));
            }
        }
        let atom = Self {
            id,
            parents,
            ops,
            copies,
            metadata,
            source: source.ok_or_else(|| {
                Error::NonCanonical("ChangeAtom missing field 6 (source)".to_string())
            })?,
            status: status.ok_or_else(|| {
                Error::NonCanonical("ChangeAtom missing field 7 (status)".to_string())
            })?,
        };
        // Integrity: the stored id must match the recomputed one (RFC 011 §2.5).
        if atom.compute_id() != id {
            return Err(Error::Decode(
                "atom id does not match its contents".to_string(),
            ));
        }
        Ok(atom)
    }
}

impl RefKind {
    /// The variant number in the format's kind table: what the encoder writes, and the key the canonical
    /// order of refs is defined on (`ir-artifact-format.md` §6). Never derived from a name.
    pub(crate) fn variant(&self) -> u8 {
        match self {
            Self::Branch => 0,
            Self::Tag => 1,
            Self::Bookmark => 2,
            Self::NamedBranch => 3,
            Self::Other(_) => 4,
        }
    }
    fn encode(&self) -> Vec<u8> {
        let mut w = CanonWriter::new();
        w.uvarint(u64::from(self.variant()));
        let mut rw = RecordWriter::new();
        if let Self::Other(label) = self {
            rw.field(1, true, label.as_bytes().to_vec());
        }
        rw.finish_into(&mut w);
        w.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        match r.uvarint()? {
            v @ 0..=3 => {
                r.record_fields("RefKind", |_, _, _| Ok(false))?;
                Ok(match v {
                    0 => Self::Branch,
                    1 => Self::Tag,
                    2 => Self::Bookmark,
                    _ => Self::NamedBranch,
                })
            }
            4 => {
                let mut label = None;
                r.record_fields("RefKind::Other", |r, id, len| {
                    if id == 1 {
                        label = Some(r.text(len)?);
                        Ok(true)
                    } else {
                        Ok(false)
                    }
                })?;
                Ok(Self::Other(label.ok_or_else(|| {
                    Error::NonCanonical("RefKind::Other missing field 1 (label)".to_string())
                })?))
            }
            o => Err(Error::Decode(format!("unknown RefKind variant {o}"))),
        }
    }
}

impl Annotation {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        if let Some(t) = &self.tagger {
            rw.field(1, true, t.encode());
        }
        if let Some(t) = &self.time {
            rw.field(2, true, t.encode());
        }
        if let Some(m) = &self.message {
            rw.field(3, true, m.encode());
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut out = Self::default();
        r.record_fields("Annotation", |r, id, _len| match id {
            1 => {
                out.tagger = Some(Identity::decode(r)?);
                Ok(true)
            }
            2 => {
                out.time = Some(Time::decode(r)?);
                Ok(true)
            }
            3 => {
                out.message = Some(Text::decode(r)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(out)
    }
}

impl RefRecord {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.name.as_bytes().to_vec());
        rw.field(2, true, self.kind.encode());
        rw.field(3, true, self.target.0.to_vec());
        rw.field(4, true, self.status.encode());
        if let Some(s) = &self.source {
            rw.field(5, true, s.encode());
        }
        if let Some(a) = &self.annotation {
            rw.field(6, true, a.encode());
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut name = None;
        let mut kind = None;
        let mut target = None;
        let mut status = None;
        let mut source = None;
        let mut annotation = None;
        r.record_fields("RefRecord", |r, id, len| match id {
            1 => {
                name = Some(r.text(len)?);
                Ok(true)
            }
            2 => {
                kind = Some(RefKind::decode(r)?);
                Ok(true)
            }
            3 => {
                target = Some(AtomId(r.raw32()?));
                Ok(true)
            }
            4 => {
                status = Some(EpistemicStatus::decode(r, 0)?);
                Ok(true)
            }
            5 => {
                source = Some(SourceIdentity::decode(r)?);
                Ok(true)
            }
            6 => {
                annotation = Some(Annotation::decode(r)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            name: name.ok_or_else(|| {
                Error::NonCanonical("RefRecord missing field 1 (name)".to_string())
            })?,
            kind: kind.ok_or_else(|| {
                Error::NonCanonical("RefRecord missing field 2 (kind)".to_string())
            })?,
            target: target.ok_or_else(|| {
                Error::NonCanonical("RefRecord missing field 3 (target)".to_string())
            })?,
            status: status.ok_or_else(|| {
                Error::NonCanonical("RefRecord missing field 4 (status)".to_string())
            })?,
            source,
            annotation,
        })
    }
}

impl LossClass {
    /// The variant number in the format's class table: what the encoder writes, and the key the canonical
    /// order of drops is defined on (`ir-artifact-format.md` §6). Never derived from a name.
    pub(crate) fn variant(self) -> u8 {
        match self {
            Self::Representation => 0,
            Self::AdvisoryUnreliable => 1,
            Self::Other => 2,
            Self::Transform => 3,
        }
    }
    fn encode(&self) -> Vec<u8> {
        let mut w = CanonWriter::new();
        w.uvarint(u64::from(self.variant()));
        RecordWriter::new().finish_into(&mut w);
        w.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let variant = r.uvarint()?;
        r.record_fields("LossClass", |_, _, _| Ok(false))?;
        Ok(match variant {
            0 => Self::Representation,
            1 => Self::AdvisoryUnreliable,
            2 => Self::Other,
            3 => Self::Transform,
            o => return Err(Error::Decode(format!("unknown LossClass variant {o}"))),
        })
    }
}

impl DropRecord {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.class.encode());
        rw.field(2, true, self.what.as_bytes().to_vec());
        rw.field(3, true, self.reason.as_bytes().to_vec());
        if let Some(step) = self.step {
            rw.field(4, true, crate::canon::uvarint_value(step));
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut class = None;
        let mut what = None;
        let mut reason = None;
        let mut step = None;
        r.record_fields("DropRecord", |r, id, len| match id {
            1 => {
                class = Some(LossClass::decode(r)?);
                Ok(true)
            }
            2 => {
                what = Some(r.text(len)?);
                Ok(true)
            }
            3 => {
                reason = Some(r.text(len)?);
                Ok(true)
            }
            4 => {
                step = Some(r.uvarint()?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        let class = class
            .ok_or_else(|| Error::NonCanonical("DropRecord missing field 1 (class)".to_string()))?;
        match (class, step) {
            (LossClass::Transform, None) => {
                return Err(Error::NonCanonical(
                    "DropRecord.class is Transform but field 4 (step) is missing".to_string(),
                ));
            }
            (c, Some(_)) if c != LossClass::Transform => {
                return Err(Error::NonCanonical(
                    "DropRecord field 4 (step) is present but class is not Transform".to_string(),
                ));
            }
            _ => {}
        }
        let what = what
            .ok_or_else(|| Error::NonCanonical("DropRecord missing field 2 (what)".to_string()))?;
        if class == LossClass::Transform && !is_valid_transform_drop_what(&what) {
            return Err(Error::Decode(format!(
                "DropRecord.what {what:?} does not match the Transform-drop grammar"
            )));
        }
        Ok(Self {
            class,
            what,
            reason: reason.ok_or_else(|| {
                Error::NonCanonical("DropRecord missing field 3 (reason)".to_string())
            })?,
            step,
        })
    }
}

impl FlagKind {
    /// The variant number in the format's kind table: what the encoder writes, and the key the canonical
    /// order of flags is defined on (`ir-artifact-format.md` §6). Never derived from a name.
    pub(crate) fn variant(self) -> u8 {
        match self {
            Self::ConventionViolation => 0,
            Self::BelowConfidenceFloor => 1,
        }
    }
    fn encode(&self) -> Vec<u8> {
        let mut w = CanonWriter::new();
        w.uvarint(u64::from(self.variant()));
        RecordWriter::new().finish_into(&mut w);
        w.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let variant = r.uvarint()?;
        r.record_fields("FlagKind", |_, _, _| Ok(false))?;
        Ok(match variant {
            0 => Self::ConventionViolation,
            1 => Self::BelowConfidenceFloor,
            o => return Err(Error::Decode(format!("unknown FlagKind variant {o}"))),
        })
    }
}

impl Flag {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.kind.encode());
        rw.field(2, true, self.what.as_bytes().to_vec());
        rw.field(3, true, crate::canon::uvarint_value(self.count));
        rw.field(4, true, self.reason.as_bytes().to_vec());
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut kind = None;
        let mut what = None;
        let mut count = None;
        let mut reason = None;
        r.record_fields("Flag", |r, id, len| match id {
            1 => {
                kind = Some(FlagKind::decode(r)?);
                Ok(true)
            }
            2 => {
                what = Some(r.text(len)?);
                Ok(true)
            }
            3 => {
                count = Some(r.uvarint()?);
                Ok(true)
            }
            4 => {
                reason = Some(r.text(len)?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        let count =
            count.ok_or_else(|| Error::NonCanonical("Flag missing field 3 (count)".to_string()))?;
        if count < 1 {
            return Err(Error::NonCanonical(
                "Flag.count must be at least 1".to_string(),
            ));
        }
        Ok(Self {
            kind: kind
                .ok_or_else(|| Error::NonCanonical("Flag missing field 1 (kind)".to_string()))?,
            what: what
                .ok_or_else(|| Error::NonCanonical("Flag missing field 2 (what)".to_string()))?,
            count,
            reason: reason
                .ok_or_else(|| Error::NonCanonical("Flag missing field 4 (reason)".to_string()))?,
        })
    }
}

impl TransformRecord {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.name.as_bytes().to_vec());
        rw.field(2, true, self.version.as_bytes().to_vec());
        if !self.params.is_empty() {
            rw.field(
                3,
                true,
                map_value(self.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))),
            );
        }
        rw.field(4, true, self.consumed.to_vec());
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut name = None;
        let mut version = None;
        let mut params = BTreeMap::new();
        let mut consumed = None;
        r.record_fields("TransformRecord", |r, id, len| match id {
            1 => {
                name = Some(r.text(len)?);
                Ok(true)
            }
            2 => {
                version = Some(r.text(len)?);
                Ok(true)
            }
            3 => {
                params = r.map()?;
                if params.is_empty() {
                    return Err(Error::NonCanonical(
                        "TransformRecord.params encoded but empty".to_string(),
                    ));
                }
                Ok(true)
            }
            4 => {
                consumed = Some(r.raw32()?);
                Ok(true)
            }
            _ => Ok(false),
        })?;
        let name = name.ok_or_else(|| {
            Error::NonCanonical("TransformRecord missing field 1 (name)".to_string())
        })?;
        if !is_valid_transform_name(&name) {
            return Err(Error::Decode(format!(
                "TransformRecord.name {name:?} does not match the plugin grammar"
            )));
        }
        let version = version.ok_or_else(|| {
            Error::NonCanonical("TransformRecord missing field 2 (version)".to_string())
        })?;
        if version.is_empty() {
            return Err(Error::NonCanonical(
                "TransformRecord.version is empty".to_string(),
            ));
        }
        let consumed = consumed.ok_or_else(|| {
            Error::NonCanonical("TransformRecord missing field 4 (consumed)".to_string())
        })?;
        Ok(Self {
            name,
            version,
            params,
            consumed,
        })
    }
}

impl ImportProvenance {
    fn encode(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        rw.field(1, true, self.source.encode());
        rw.field(2, true, self.brygge_version.as_bytes().to_vec());
        rw.field(3, true, self.decoder.as_bytes().to_vec());
        rw.field(4, true, self.decoder_version.as_bytes().to_vec());
        if !self.params.is_empty() {
            rw.field(
                5,
                true,
                map_value(self.params.iter().map(|(k, v)| (k.as_str(), v.as_str()))),
            );
        }
        rw.into_bytes()
    }
    fn decode(r: &mut CanonReader) -> Result<Self, Error> {
        let mut source = None;
        let mut brygge_version = None;
        let mut decoder = None;
        let mut decoder_version = None;
        let mut params = BTreeMap::new();
        r.record_fields("ImportProvenance", |r, id, len| match id {
            1 => {
                source = Some(SourceIdentity::decode(r)?);
                Ok(true)
            }
            2 => {
                brygge_version = Some(r.text(len)?);
                Ok(true)
            }
            3 => {
                decoder = Some(r.text(len)?);
                Ok(true)
            }
            4 => {
                decoder_version = Some(r.text(len)?);
                Ok(true)
            }
            5 => {
                params = r.map()?;
                if params.is_empty() {
                    return Err(Error::NonCanonical(
                        "ImportProvenance.params encoded but empty".to_string(),
                    ));
                }
                Ok(true)
            }
            _ => Ok(false),
        })?;
        Ok(Self {
            source: source.ok_or_else(|| {
                Error::NonCanonical("ImportProvenance missing field 1 (source)".to_string())
            })?,
            brygge_version: brygge_version.ok_or_else(|| {
                Error::NonCanonical("ImportProvenance missing field 2 (brygge_version)".to_string())
            })?,
            decoder: decoder.ok_or_else(|| {
                Error::NonCanonical("ImportProvenance missing field 3 (decoder)".to_string())
            })?,
            decoder_version: decoder_version.ok_or_else(|| {
                Error::NonCanonical(
                    "ImportProvenance missing field 4 (decoder_version)".to_string(),
                )
            })?,
            params,
        })
    }
}

impl Ir {
    /// Encode the metadata record (everything but the blob bytes) — the container's `metadata` section
    /// (RFC 011 §2.3).
    pub(crate) fn encode_metadata(&self) -> Vec<u8> {
        let mut rw = RecordWriter::new();
        if !self.atoms.is_empty() {
            rw.field(
                1,
                true,
                list_value(self.atoms.iter().map(ChangeAtom::encode)),
            );
        }
        if !self.refs.is_empty() {
            rw.field(2, true, list_value(self.refs.iter().map(RefRecord::encode)));
        }
        rw.field(3, true, self.provenance.encode());
        if !self.loss.dropped.is_empty() {
            rw.field(
                4,
                true,
                list_value(self.loss.dropped.iter().map(DropRecord::encode)),
            );
        }
        if !self.flags.is_empty() {
            rw.field(5, true, list_value(self.flags.iter().map(Flag::encode)));
        }
        if !self.transforms.is_empty() {
            rw.field(
                6,
                true,
                list_value(self.transforms.iter().map(TransformRecord::encode)),
            );
        }
        rw.into_bytes()
    }

    /// Decode the metadata record (blobs are read separately by [`crate::artifact`]). `minor` is the
    /// artifact's own contract minor (RFC 021 D-1): it governs only how a [`PathOp`]'s content is laid
    /// out on the wire, threaded down to [`PathOp::decode`] through [`ChangeAtom::decode`].
    pub(crate) fn decode_metadata(r: &mut CanonReader, minor: u32) -> Result<Self, Error> {
        let mut atoms = Vec::new();
        let mut refs = Vec::new();
        let mut provenance = None;
        let mut dropped = Vec::new();
        let mut flags = Vec::new();
        let mut transforms = Vec::new();
        r.record_fields("Ir", |r, id, _len| match id {
            1 => {
                atoms = r.list(|r| ChangeAtom::decode(r, minor))?;
                non_empty_list("Ir.atoms", &atoms)?;
                Ok(true)
            }
            2 => {
                refs = r.list(RefRecord::decode)?;
                non_empty_list("Ir.refs", &refs)?;
                Ok(true)
            }
            3 => {
                provenance = Some(ImportProvenance::decode(r)?);
                Ok(true)
            }
            4 => {
                dropped = r.list(DropRecord::decode)?;
                non_empty_list("Ir.dropped", &dropped)?;
                Ok(true)
            }
            5 => {
                flags = r.list(Flag::decode)?;
                non_empty_list("Ir.flags", &flags)?;
                Ok(true)
            }
            6 => {
                transforms = r.list(TransformRecord::decode)?;
                non_empty_list("Ir.transforms", &transforms)?;
                if transforms.len() > 64 {
                    return Err(Error::NonCanonical(
                        "Ir.transforms holds more than 64 records".to_string(),
                    ));
                }
                Ok(true)
            }
            _ => Ok(false),
        })?;
        for (a, b) in refs.iter().zip(refs.iter().skip(1)) {
            let ka = (&a.name, a.kind.variant());
            let kb = (&b.name, b.kind.variant());
            if ka >= kb {
                return Err(Error::NonCanonical(
                    "Ir.refs are not strictly ascending by (name, kind variant)".to_string(),
                ));
            }
        }
        for (a, b) in dropped.iter().zip(dropped.iter().skip(1)) {
            let ka = (a.class.variant(), a.step, &a.what);
            let kb = (b.class.variant(), b.step, &b.what);
            if ka >= kb {
                return Err(Error::NonCanonical(
                    "Ir.dropped is not strictly ascending by (class variant, step, what)"
                        .to_string(),
                ));
            }
        }
        for (a, b) in flags.iter().zip(flags.iter().skip(1)) {
            let ka = (a.kind.variant(), &a.what);
            let kb = (b.kind.variant(), &b.what);
            if ka >= kb {
                return Err(Error::NonCanonical(
                    "Ir.flags are not strictly ascending by (kind variant, what)".to_string(),
                ));
            }
        }
        Ok(Self {
            atoms,
            refs,
            provenance: provenance.ok_or_else(|| {
                Error::NonCanonical("Ir missing field 3 (provenance)".to_string())
            })?,
            loss: LossBoundary { dropped },
            flags,
            content: ContentStore::new(),
            transforms,
        })
    }
}

#[cfg(test)]
mod tests;