openehr 0.3.0

openEHR Reference Model types, validation, paths, AQL parsing, and change-control security primitives
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
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
//! The openEHR **Common Information Model**: archetyping, parties,
//! participation, audit, and change control.
//!
//! This module holds the two ideas that make openEHR openEHR.
//!
//! **Archetyping.** Every clinical node is a [`Locatable`]: it carries a
//! runtime `name`, a design-time `archetype_node_id`, and — at archetype roots
//! — an [`Archetyped`] saying which archetype and template shaped it. That is
//! what lets one `COMPOSITION` be read by software that has never seen the
//! archetype it was built from.
//!
//! **Change control.** Nothing in an openEHR record is updated in place. A
//! [`VersionedObject`] holds a tree of [`Version`]s; each version carries the
//! [`AuditDetails`] of its commit; a [`Contribution`] groups the versions
//! committed together. Deletion is a version whose `data` is absent and whose
//! `lifecycle_state` is `deleted` — the record of the deletion is itself a
//! record.
//!
//! # What this module enforces that a plain struct would not
//!
//! [`VersionedObject::commit`] refuses a version whose `uid` names a different
//! versioned object, whose `preceding_version_uid` is not the current latest,
//! or whose version id already exists. Each of those produces a history that
//! *reads back* — it just does not connect, and it does not connect in a way
//! that is invisible until someone asks what changed.

use crate::base::{
    ArchetypeId, HierObjectId, Interval, LocatableRef, ObjectRef, ObjectVersionId, PartyRef,
    TemplateId, UidBasedId,
};
use crate::error::ParseError;
use crate::rm::data_types::{
    DataValue, DvCodedText, DvDate, DvDateTime, DvEhrUri, DvIdentifier, DvMultimedia, Text,
};
use crate::terminology;
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Archetyping
// ---------------------------------------------------------------------------

/// The archetype and template that shaped a node.
///
/// Present only at archetype roots — that is what `is_archetype_root` means.
/// An `ARCHETYPED` on every node would be a lie about where the archetype
/// boundaries are, and the boundaries are what a template composes.
///
/// ```
/// use openehr::rm::common::Archetyped;
///
/// let a = Archetyped::new("openEHR-EHR-OBSERVATION.blood_pressure.v2", "1.1.0").unwrap();
/// assert!(a.archetype_id().constrains("OBSERVATION"));
/// assert_eq!(a.rm_version(), "1.1.0");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Archetyped {
    archetype_id: ArchetypeId,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    template_id: Option<TemplateId>,
    rm_version: String,
}

impl Archetyped {
    /// Builds archetype details.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the archetype id is malformed or the RM
    /// version is empty. The RM version matters: it says which release's
    /// invariants the data was built against, and data built against 1.0.2
    /// can contain things 1.1.0 forbids.
    pub fn new(archetype_id: &str, rm_version: impl Into<String>) -> Result<Self, ParseError> {
        let rm_version = rm_version.into();
        if rm_version.is_empty() {
            return Err(ParseError::invariant("ARCHETYPED", "Rm_version_valid"));
        }
        Ok(Self {
            archetype_id: archetype_id.parse()?,
            template_id: None,
            rm_version,
        })
    }

    /// Records the template that composed this archetype into a form.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the template id is malformed.
    pub fn with_template(mut self, template_id: &str) -> Result<Self, ParseError> {
        self.template_id = Some(template_id.parse()?);
        Ok(self)
    }

    /// The archetype.
    #[must_use]
    pub fn archetype_id(&self) -> &ArchetypeId {
        &self.archetype_id
    }

    /// The template, if one was used.
    #[must_use]
    pub fn template_id(&self) -> Option<&TemplateId> {
        self.template_id.as_ref()
    }

    /// The openEHR release the data was built against.
    #[must_use]
    pub fn rm_version(&self) -> &str {
        &self.rm_version
    }
}

/// A typed relationship from one archetyped structure to another.
///
/// `LINK.target` is a [`DvEhrUri`] and not a free URI: a link inside a health
/// record points inside a health record. See [`crate::rm::data_types::uri`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
// `link_type` shadows the struct name only because openEHR calls the attribute
// `type`, which is a Rust keyword. Renaming it to something that reads better
// in Rust would break the correspondence with the class definition.
#[allow(clippy::struct_field_names)]
pub struct Link {
    meaning: Text,
    #[serde(rename = "type")]
    link_type: Text,
    target: DvEhrUri,
}

impl Link {
    /// Builds a link.
    #[must_use]
    pub fn new(meaning: Text, link_type: Text, target: DvEhrUri) -> Self {
        Self {
            meaning,
            link_type,
            target,
        }
    }

    /// What the relationship means clinically.
    #[must_use]
    pub fn meaning(&self) -> &Text {
        &self.meaning
    }

    /// The relationship's domain-level classification, such as `problem` or
    /// `issue`.
    #[must_use]
    pub fn link_type(&self) -> &Text {
        &self.link_type
    }

    /// What the link points at.
    #[must_use]
    pub fn target(&self) -> &DvEhrUri {
        &self.target
    }
}

/// What one system in a feeder chain did with the data.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FeederAuditDetails {
    system_id: String,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    location: Option<PartyIdentified>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    subject: Option<PartyProxy>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    provider: Option<PartyIdentified>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    time: Option<DvDateTime>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    version_id: Option<String>,
}

impl FeederAuditDetails {
    /// Builds feeder audit details.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the system id is empty. A feeder audit whose
    /// system id is blank records that data came from somewhere without saying
    /// where, which is the one fact it exists to carry.
    pub fn new(system_id: impl Into<String>) -> Result<Self, ParseError> {
        let system_id = system_id.into();
        if system_id.is_empty() {
            return Err(ParseError::invariant(
                "FEEDER_AUDIT_DETAILS",
                "System_id_valid",
            ));
        }
        Ok(Self {
            system_id,
            location: None,
            subject: None,
            provider: None,
            time: None,
            version_id: None,
        })
    }

    /// Records when the system handled the data.
    #[must_use]
    pub fn with_time(mut self, time: DvDateTime) -> Self {
        self.time = Some(time);
        self
    }

    /// The system's identifier.
    #[must_use]
    pub fn system_id(&self) -> &str {
        &self.system_id
    }

    /// When the system handled the data.
    #[must_use]
    pub fn time(&self) -> Option<&DvDateTime> {
        self.time.as_ref()
    }

    /// The data's version in the originating system.
    #[must_use]
    pub fn version_id(&self) -> Option<&str> {
        self.version_id.as_deref()
    }
}

/// Provenance for data that was converted from a non-openEHR system.
///
/// The reason this exists rather than a note in `other_details`: converted data
/// is the data most likely to be wrong, and the conversion is the most likely
/// place for it to have gone wrong. A `FEEDER_AUDIT` keeps the original
/// content and the identifiers it had, so a discrepancy found years later can
/// be traced to the transform rather than argued about.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FeederAudit {
    originating_system_audit: FeederAuditDetails,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    originating_system_item_ids: Vec<DvIdentifier>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    feeder_system_audit: Option<FeederAuditDetails>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    feeder_system_item_ids: Vec<DvIdentifier>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    original_content: Option<DataValue>,
}

impl FeederAudit {
    /// Builds a feeder audit.
    #[must_use]
    pub fn new(originating_system_audit: FeederAuditDetails) -> Self {
        Self {
            originating_system_audit,
            originating_system_item_ids: Vec::new(),
            feeder_system_audit: None,
            feeder_system_item_ids: Vec::new(),
            original_content: None,
        }
    }

    /// Keeps the pre-conversion content.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] unless the content is a `DV_ENCAPSULATED`
    /// descendant — `DV_PARSABLE` or `DV_MULTIMEDIA`. openEHR types this
    /// attribute `DV_ENCAPSULATED` because the original content is by
    /// definition in a formalism openEHR does not model; accepting a
    /// `DV_TEXT` here would invite a lossy stringification of the very thing
    /// that exists to be lossless.
    pub fn with_original_content(mut self, content: DataValue) -> Result<Self, ParseError> {
        if !matches!(content, DataValue::Parsable(_) | DataValue::Multimedia(_)) {
            return Err(ParseError::invariant(
                "FEEDER_AUDIT",
                "Original_content_encapsulated",
            ));
        }
        self.original_content = Some(content);
        Ok(self)
    }

    /// Records the identifiers the data had in the originating system.
    #[must_use]
    pub fn with_originating_item_id(mut self, id: DvIdentifier) -> Self {
        self.originating_system_item_ids.push(id);
        self
    }

    /// The originating system's audit details.
    #[must_use]
    pub fn originating_system_audit(&self) -> &FeederAuditDetails {
        &self.originating_system_audit
    }

    /// The identifiers the data had in the originating system.
    #[must_use]
    pub fn originating_system_item_ids(&self) -> &[DvIdentifier] {
        &self.originating_system_item_ids
    }

    /// The pre-conversion content, if kept.
    #[must_use]
    pub fn original_content(&self) -> Option<&DataValue> {
        self.original_content.as_ref()
    }
}

/// The attributes every `LOCATABLE` carries.
///
/// Held as one struct and flattened into each clinical class, mirroring
/// openEHR's own placement of them on the abstract parent.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LocatableAttrs {
    name: Text,
    archetype_node_id: String,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    uid: Option<UidBasedId>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    links: Vec<Link>,
    // Boxed for deserializer frame size, not for ownership. `LocatableAttrs`
    // is flattened into every clinical class, so serde generates one
    // `visit_map` per embedding class holding an `Option<T>` local per field.
    // `FEEDER_AUDIT` transitively contains a `DATA_VALUE` — a 22-variant enum
    // — and it is present on well under 1% of nodes. Boxing trades a rare
    // allocation for a stack cost paid on every node of every document.
    // See spec/audit.md A-03 for the measurements.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    archetype_details: Option<Box<Archetyped>>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    feeder_audit: Option<Box<FeederAudit>>,
}

impl LocatableAttrs {
    /// Builds the locatable attributes.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if `archetype_node_id` is empty. Every locatable
    /// has one — an at-code such as `at0004` for an internal node, or a full
    /// archetype id at a root — and a node without one cannot be addressed by
    /// a path, which makes it unreachable by AQL and by templates alike.
    pub fn new(name: Text, archetype_node_id: impl Into<String>) -> Result<Self, ParseError> {
        let archetype_node_id = archetype_node_id.into();
        if archetype_node_id.is_empty() {
            return Err(ParseError::invariant(
                "LOCATABLE",
                "Archetype_node_id_valid",
            ));
        }
        Ok(Self {
            name,
            archetype_node_id,
            uid: None,
            links: Vec::new(),
            archetype_details: None,
            feeder_audit: None,
        })
    }

    /// Builds locatable attributes with a plain-text name.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the name is empty or the node id is empty.
    pub fn named(name: &str, archetype_node_id: &str) -> Result<Self, ParseError> {
        Self::new(Text::plain(name)?, archetype_node_id)
    }

    /// Marks this node as an archetype root.
    #[must_use]
    pub fn with_archetype_details(mut self, details: Archetyped) -> Self {
        self.archetype_details = Some(Box::new(details));
        self
    }

    /// Gives the node a persistent identifier.
    #[must_use]
    pub fn with_uid(mut self, uid: UidBasedId) -> Self {
        self.uid = Some(uid);
        self
    }

    /// Adds a link to another archetyped structure.
    #[must_use]
    pub fn with_link(mut self, link: Link) -> Self {
        self.links.push(link);
        self
    }

    /// Records where the data came from.
    #[must_use]
    pub fn with_feeder_audit(mut self, audit: FeederAudit) -> Self {
        self.feeder_audit = Some(Box::new(audit));
        self
    }

    /// Whether the node carries a persistent identifier.
    ///
    /// Optional on most locatables and **required** on a `PARTY`, which is why
    /// this is a question the attributes can answer directly rather than only
    /// through the [`Locatable`] trait.
    #[must_use]
    pub fn has_uid(&self) -> bool {
        self.uid.is_some()
    }

    /// The node's runtime name.
    #[must_use]
    pub fn name(&self) -> &Text {
        &self.name
    }

    /// The node's design-time code.
    #[must_use]
    pub fn archetype_node_id(&self) -> &str {
        &self.archetype_node_id
    }

    /// The node's persistent identifier, if it has one.
    #[must_use]
    pub fn uid(&self) -> Option<&UidBasedId> {
        self.uid.as_ref()
    }
}

/// Read access to the attributes of `LOCATABLE`.
///
/// Implemented by every clinical class. The trait is what lets path
/// navigation, validation, and redaction walk a composition without a match
/// arm per class.
pub trait Locatable {
    /// The `LOCATABLE` attributes.
    fn locatable(&self) -> &LocatableAttrs;

    /// The openEHR class name, as it appears in `_type`.
    fn rm_type_name(&self) -> &'static str;

    /// The runtime name of the node — what a clinician sees as its label.
    fn name(&self) -> &Text {
        &self.locatable().name
    }

    /// The design-time code: an at-code, or an archetype id at a root.
    fn archetype_node_id(&self) -> &str {
        &self.locatable().archetype_node_id
    }

    /// The node's persistent identifier, if it has one.
    fn uid(&self) -> Option<&UidBasedId> {
        self.locatable().uid.as_ref()
    }

    /// Links to other archetyped structures.
    fn links(&self) -> &[Link] {
        &self.locatable().links
    }

    /// The archetype details, present only at archetype roots.
    fn archetype_details(&self) -> Option<&Archetyped> {
        self.locatable().archetype_details.as_deref()
    }

    /// Provenance for converted data, if any.
    fn feeder_audit(&self) -> Option<&FeederAudit> {
        self.locatable().feeder_audit.as_deref()
    }

    /// Whether this node is the root of an archetype.
    fn is_archetype_root(&self) -> bool {
        self.locatable().archetype_details.is_some()
    }

    /// The clinical concept this node expresses.
    ///
    /// openEHR defines `concept` as the name of the *archetype root*, so this
    /// answers only at a root and returns `None` elsewhere rather than
    /// offering an internal node's name as though it were a concept.
    fn concept(&self) -> Option<&Text> {
        self.is_archetype_root().then(|| self.name())
    }
}

/// Implements [`Locatable`] for a struct with a `locatable: LocatableAttrs`
/// field.
macro_rules! impl_locatable {
    ($ty:ty, $class:literal) => {
        impl $crate::rm::common::Locatable for $ty {
            fn locatable(&self) -> &$crate::rm::common::LocatableAttrs {
                &self.locatable
            }

            fn rm_type_name(&self) -> &'static str {
                $class
            }
        }
    };
}

pub(crate) use impl_locatable;

// ---------------------------------------------------------------------------
// Parties
// ---------------------------------------------------------------------------

/// The subject of the record, referred to without naming them.
///
/// `PARTY_SELF` with no `external_ref` is how openEHR supports a fully
/// anonymous record: the entry says "the subject of this record", and nothing
/// in the record says who that is. This is not a degenerate case to be
/// normalised away — it is the representation a research extract needs.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct PartySelf {
    #[serde(skip_serializing_if = "Option::is_none", default)]
    external_ref: Option<PartyRef>,
}

impl PartySelf {
    /// The record subject, anonymously.
    #[must_use]
    pub fn anonymous() -> Self {
        Self::default()
    }

    /// The record subject, with a demographic reference.
    #[must_use]
    pub fn with_external_ref(external_ref: PartyRef) -> Self {
        Self {
            external_ref: Some(external_ref),
        }
    }

    /// The demographic reference, if any.
    #[must_use]
    pub fn external_ref(&self) -> Option<&PartyRef> {
        self.external_ref.as_ref()
    }
}

/// A party other than the record subject, identified by name, by formal
/// identifiers, or by a demographic reference.
///
/// ```
/// use openehr::rm::common::PartyIdentified;
///
/// let composer = PartyIdentified::named("Dr A Nurse").unwrap();
/// assert_eq!(composer.name(), Some("Dr A Nurse"));
///
/// // At least one of name, identifiers, or external_ref is required: a
/// // PARTY_IDENTIFIED with none of them identifies nobody.
/// assert!(PartyIdentified::new(None, Vec::new(), None).is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PartyIdentified {
    #[serde(skip_serializing_if = "Option::is_none", default)]
    external_ref: Option<PartyRef>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    name: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    identifiers: Vec<DvIdentifier>,
}

impl PartyIdentified {
    /// Builds an identified party.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if all three of `name`, `identifiers`, and
    /// `external_ref` are absent (`Basic_validity`), or if `name` is present
    /// and empty.
    pub fn new(
        name: Option<String>,
        identifiers: Vec<DvIdentifier>,
        external_ref: Option<PartyRef>,
    ) -> Result<Self, ParseError> {
        if name.as_ref().is_some_and(String::is_empty) {
            return Err(ParseError::invariant("PARTY_IDENTIFIED", "Name_valid"));
        }
        if name.is_none() && identifiers.is_empty() && external_ref.is_none() {
            return Err(ParseError::invariant("PARTY_IDENTIFIED", "Basic_validity"));
        }
        Ok(Self {
            external_ref,
            name,
            identifiers,
        })
    }

    /// Builds a party identified only by name.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the name is empty.
    pub fn named(name: impl Into<String>) -> Result<Self, ParseError> {
        Self::new(Some(name.into()), Vec::new(), None)
    }

    /// The party's name, if recorded.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// The party's formal identifiers.
    #[must_use]
    pub fn identifiers(&self) -> &[DvIdentifier] {
        &self.identifiers
    }

    /// The demographic reference, if any.
    #[must_use]
    pub fn external_ref(&self) -> Option<&PartyRef> {
        self.external_ref.as_ref()
    }
}

/// A party whose relationship to the record subject is recorded.
///
/// This is how an entry says it is *about someone else* — a family history
/// about a mother, a finding about a foetus. Without it, an entry recorded
/// during a consultation reads as a finding about the patient, which is how a
/// mother's breast cancer becomes the patient's.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PartyRelated {
    #[serde(flatten)]
    identified: PartyIdentified,
    relationship: DvCodedText,
}

impl PartyRelated {
    /// Builds a related party from an openEHR `subject_relationship` code.
    ///
    /// Taking a code rather than a `DV_CODED_TEXT` makes
    /// `Relationship_valid` hold by construction, as it does for every other
    /// coded attribute in this crate: the rubric cannot disagree with the code
    /// because the caller never supplies one.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the code is not in the openEHR
    /// `subject_relationship` group (`Relationship_valid`).
    pub fn new(identified: PartyIdentified, relationship_code: &str) -> Result<Self, ParseError> {
        let relationship = terminology::subject_relationship::GROUP
            .coded_text(relationship_code)
            .ok_or_else(|| ParseError::invariant("PARTY_RELATED", "Relationship_valid"))?;
        Ok(Self {
            identified,
            relationship,
        })
    }

    /// Builds a related party from an already-coded relationship.
    ///
    /// For reading data that arrived from elsewhere, where the relationship may
    /// legitimately be coded against a terminology this crate does not carry.
    /// The group membership is then checked by [`crate::validation`] rather
    /// than here.
    #[must_use]
    pub fn from_coded(identified: PartyIdentified, relationship: DvCodedText) -> Self {
        Self {
            identified,
            relationship,
        }
    }

    /// The relationship to the record subject.
    #[must_use]
    pub fn relationship(&self) -> &DvCodedText {
        &self.relationship
    }

    /// The party's identifying attributes.
    #[must_use]
    pub fn as_identified(&self) -> &PartyIdentified {
        &self.identified
    }

    /// Whether the relationship is `0|self|` — the record subject themselves.
    #[must_use]
    pub fn is_self(&self) -> bool {
        self.relationship.defining_code().is_openehr()
            && self.relationship.defining_code().code_string()
                == terminology::subject_relationship::SELF
    }
}

/// Any reference to a party from inside the health record.
///
/// The variants differ substantially in size — a [`PartySelf`] is one optional
/// reference and a [`PartyRelated`] carries identifiers and a coded
/// relationship. Boxing the large variant would shrink the enum and put a heap
/// allocation on the path of every clinical statement's `subject`, which is the
/// hottest field in the model; the enum stays flat deliberately.
///
/// # Reading a payload with no `_type`
///
/// `relationship` implies `PARTY_RELATED`; `name` or `identifiers` imply
/// `PARTY_IDENTIFIED`; anything else is `PARTY_SELF`. The order matters for
/// the same reason it does in [`Text`]: reading a `PARTY_RELATED` as a
/// `PARTY_IDENTIFIED` would drop the relationship, and the relationship is the
/// attribute that says whom the data is about.
#[derive(Debug, Clone, PartialEq)]
// See the note on the variants' sizes above.
#[allow(clippy::large_enum_variant)]
pub enum PartyProxy {
    /// The record subject.
    SelfParty(PartySelf),
    /// A named or identified party.
    Identified(PartyIdentified),
    /// A party with a stated relationship to the record subject.
    Related(PartyRelated),
}

impl PartyProxy {
    /// The demographic reference, if any.
    #[must_use]
    pub fn external_ref(&self) -> Option<&PartyRef> {
        match self {
            Self::SelfParty(p) => p.external_ref(),
            Self::Identified(p) => p.external_ref(),
            Self::Related(p) => p.as_identified().external_ref(),
        }
    }

    /// The party's formal identifiers, if this form carries any.
    ///
    /// Empty for a `PARTY_SELF`, which is anonymous by design and legitimately
    /// so (`M5.16`) — not missing data.
    ///
    /// Beside [`PartyProxy::external_ref`] and [`PartyProxy::name`] because a
    /// caller asking "which party is this?" should not have to match on the
    /// variant to find out. A caller that did would answer the question three
    /// ways, and the one that drifted would be the one nobody re-read.
    #[must_use]
    pub fn identifiers(&self) -> &[DvIdentifier] {
        match self {
            Self::SelfParty(_) => &[],
            Self::Identified(p) => p.identifiers(),
            Self::Related(p) => p.as_identified().identifiers(),
        }
    }

    /// The party's name, if this form carries one.
    #[must_use]
    pub fn name(&self) -> Option<&str> {
        match self {
            Self::SelfParty(_) => None,
            Self::Identified(p) => p.name(),
            Self::Related(p) => p.as_identified().name(),
        }
    }

    /// The openEHR class name, as it appears in `_type`.
    #[must_use]
    pub fn type_name(&self) -> &'static str {
        match self {
            Self::SelfParty(_) => "PARTY_SELF",
            Self::Identified(_) => "PARTY_IDENTIFIED",
            Self::Related(_) => "PARTY_RELATED",
        }
    }

    /// Whether this proxy denotes the record subject.
    ///
    /// True for `PARTY_SELF`, and for a `PARTY_RELATED` whose relationship is
    /// `0|self|`. Both spellings occur, and code that checks only the first
    /// treats a self-related entry as being about somebody else.
    #[must_use]
    pub fn is_subject(&self) -> bool {
        match self {
            Self::SelfParty(_) => true,
            Self::Identified(_) => false,
            Self::Related(p) => p.is_self(),
        }
    }
}

impl From<PartySelf> for PartyProxy {
    fn from(v: PartySelf) -> Self {
        Self::SelfParty(v)
    }
}

impl From<PartyIdentified> for PartyProxy {
    fn from(v: PartyIdentified) -> Self {
        Self::Identified(v)
    }
}

impl From<PartyRelated> for PartyProxy {
    fn from(v: PartyRelated) -> Self {
        Self::Related(v)
    }
}

impl Serialize for PartyProxy {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct Tagged<'a, T: Serialize> {
            #[serde(rename = "_type")]
            ty: &'static str,
            #[serde(flatten)]
            inner: &'a T,
        }
        match self {
            Self::SelfParty(p) => Tagged {
                ty: "PARTY_SELF",
                inner: p,
            }
            .serialize(s),
            Self::Identified(p) => Tagged {
                ty: "PARTY_IDENTIFIED",
                inner: p,
            }
            .serialize(s),
            Self::Related(p) => Tagged {
                ty: "PARTY_RELATED",
                inner: p,
            }
            .serialize(s),
        }
    }
}

impl<'de> Deserialize<'de> for PartyProxy {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        use serde::de::Error as _;

        // A flat wire struct rather than an intermediate `serde_json::Value`,
        // for the reason given on [`Text`]'s deserializer: `subject` appears on
        // every entry, and a `Value` round trip per party doubled the stack
        // depth of reading a composition.
        #[derive(Deserialize)]
        struct Wire {
            #[serde(rename = "_type", default)]
            ty: Option<String>,
            #[serde(default)]
            external_ref: Option<PartyRef>,
            #[serde(default)]
            name: Option<String>,
            #[serde(default)]
            identifiers: Vec<DvIdentifier>,
            #[serde(default)]
            relationship: Option<DvCodedText>,
        }

        let wire = Wire::deserialize(d)?;
        let kind = match wire.ty.as_deref() {
            Some(known @ ("PARTY_SELF" | "PARTY_IDENTIFIED" | "PARTY_RELATED")) => known,
            Some(other) => {
                return Err(D::Error::custom(format!(
                    "{other} is not a PARTY_PROXY class"
                )));
            }
            None if wire.relationship.is_some() => "PARTY_RELATED",
            None if wire.name.is_some() || !wire.identifiers.is_empty() => "PARTY_IDENTIFIED",
            None => "PARTY_SELF",
        };
        if kind == "PARTY_SELF" {
            return Ok(Self::SelfParty(PartySelf {
                external_ref: wire.external_ref,
            }));
        }
        let identified = PartyIdentified {
            external_ref: wire.external_ref,
            name: wire.name,
            identifiers: wire.identifiers,
        };
        if kind == "PARTY_IDENTIFIED" {
            return Ok(Self::Identified(identified));
        }
        let relationship = wire
            .relationship
            .ok_or_else(|| D::Error::missing_field("relationship"))?;
        Ok(Self::Related(PartyRelated {
            identified,
            relationship,
        }))
    }
}

/// A party's involvement in an activity, and in what capacity.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Participation {
    function: Text,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    mode: Option<DvCodedText>,
    performer: PartyProxy,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    time: Option<Interval<DvDateTime>>,
}

impl Participation {
    /// Builds a participation.
    #[must_use]
    pub fn new(function: Text, performer: PartyProxy) -> Self {
        Self {
            function,
            mode: None,
            performer,
            time: None,
        }
    }

    /// Records how the party took part — in person, by telephone, by letter.
    #[must_use]
    pub fn with_mode(mut self, mode: DvCodedText) -> Self {
        self.mode = Some(mode);
        self
    }

    /// Records when the participation happened.
    #[must_use]
    pub fn with_time(mut self, time: Interval<DvDateTime>) -> Self {
        self.time = Some(time);
        self
    }

    /// What the party did.
    #[must_use]
    pub fn function(&self) -> &Text {
        &self.function
    }

    /// How the party took part.
    #[must_use]
    pub fn mode(&self) -> Option<&DvCodedText> {
        self.mode.as_ref()
    }

    /// Who took part.
    #[must_use]
    pub fn performer(&self) -> &PartyProxy {
        &self.performer
    }

    /// When they took part.
    #[must_use]
    pub fn time(&self) -> Option<&Interval<DvDateTime>> {
        self.time.as_ref()
    }
}

// ---------------------------------------------------------------------------
// Audit
// ---------------------------------------------------------------------------

/// Who committed what, when, and why.
///
/// Every version in an openEHR record carries one. This is the class that
/// answers HIPAA §164.312(b) and IEC 62304's traceability requirement, and the
/// reason [`VersionedObject::commit`] will not accept a version without one.
///
/// ```
/// use openehr::rm::common::{AuditDetails, PartyIdentified};
/// use openehr::rm::data_types::DvDateTime;
/// use openehr::terminology::audit_change_type;
///
/// let audit = AuditDetails::new(
///     "ehr1.example.org",
///     DvDateTime::new("2026-07-31T09:15:00Z").unwrap(),
///     audit_change_type::CREATION,
///     PartyIdentified::named("Dr A Nurse").unwrap().into(),
/// ).unwrap();
/// assert_eq!(audit.change_type().value(), "creation");
/// assert!(audit.is_creation());
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AuditDetails {
    system_id: String,
    time_committed: DvDateTime,
    change_type: DvCodedText,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    description: Option<Text>,
    committer: PartyProxy,
}

impl AuditDetails {
    /// Builds audit details from an openEHR change-type code.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the system id is empty, or if the code is not
    /// in the `audit_change_type` group. Taking the code rather than a
    /// `DV_CODED_TEXT` is deliberate: it makes it impossible to build an audit
    /// record whose rubric and code disagree.
    pub fn new(
        system_id: impl Into<String>,
        time_committed: DvDateTime,
        change_type_code: &str,
        committer: PartyProxy,
    ) -> Result<Self, ParseError> {
        let system_id = system_id.into();
        if system_id.is_empty() {
            return Err(ParseError::invariant("AUDIT_DETAILS", "System_id_valid"));
        }
        let change_type = terminology::audit_change_type::GROUP
            .coded_text(change_type_code)
            .ok_or_else(|| ParseError::invariant("AUDIT_DETAILS", "Change_type_valid"))?;
        Ok(Self {
            system_id,
            time_committed,
            change_type,
            description: None,
            committer,
        })
    }

    /// Records why the change was made.
    #[must_use]
    pub fn with_description(mut self, description: Text) -> Self {
        self.description = Some(description);
        self
    }

    /// The repository that accepted the commit.
    #[must_use]
    pub fn system_id(&self) -> &str {
        &self.system_id
    }

    /// When the commit happened.
    #[must_use]
    pub fn time_committed(&self) -> &DvDateTime {
        &self.time_committed
    }

    /// What kind of change it was.
    #[must_use]
    pub fn change_type(&self) -> &DvCodedText {
        &self.change_type
    }

    /// Why the change was made, if recorded.
    #[must_use]
    pub fn description(&self) -> Option<&Text> {
        self.description.as_ref()
    }

    /// Who committed it.
    #[must_use]
    pub fn committer(&self) -> &PartyProxy {
        &self.committer
    }

    /// The openEHR change-type code.
    #[must_use]
    pub fn change_type_code(&self) -> &str {
        self.change_type.defining_code().code_string()
    }

    /// Whether this audit records the creation of the object.
    #[must_use]
    pub fn is_creation(&self) -> bool {
        self.change_type_code() == terminology::audit_change_type::CREATION
    }

    /// Whether this audit records a logical deletion.
    #[must_use]
    pub fn is_deletion(&self) -> bool {
        self.change_type_code() == terminology::audit_change_type::DELETED
    }
}

/// A signature over content by a healthcare agent.
///
/// An `ATTESTATION` is an `AUDIT_DETAILS` that also says *this is right, and I
/// say so*. The `proof` is an `OpenPGP` signature; this crate carries it and does
/// **not** verify it, because verifying needs a key ring and a trust policy
/// that belong to the deployment. [`Attestation::proof`] returning `Some` is
/// therefore not evidence of anything, and the documentation says so where a
/// caller will read it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Attestation {
    #[serde(flatten)]
    audit: AuditDetails,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    attested_view: Option<DvMultimedia>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    proof: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    items: Vec<DvEhrUri>,
    reason: Text,
    is_pending: bool,
}

impl Attestation {
    /// Builds an attestation.
    #[must_use]
    pub fn new(audit: AuditDetails, reason: Text, is_pending: bool) -> Self {
        Self {
            audit,
            attested_view: None,
            proof: None,
            items: Vec::new(),
            reason,
            is_pending,
        }
    }

    /// Attaches the rendering the attester actually saw.
    ///
    /// This matters more than it looks: a clinician signs what was on the
    /// screen, and the screen is a template's rendering of the data, not the
    /// data. Keeping the rendering is what makes the signature meaningful
    /// years later when the template has changed.
    #[must_use]
    pub fn with_attested_view(mut self, view: DvMultimedia) -> Self {
        self.attested_view = Some(view);
        self
    }

    /// Attaches an `OpenPGP` signature.
    ///
    /// **Not verified by this crate.** See the type's documentation.
    #[must_use]
    pub fn with_proof(mut self, proof: impl Into<String>) -> Self {
        self.proof = Some(proof.into());
        self
    }

    /// Narrows the attestation to specific nodes.
    #[must_use]
    pub fn with_item(mut self, item: DvEhrUri) -> Self {
        self.items.push(item);
        self
    }

    /// The commit metadata.
    #[must_use]
    pub fn audit(&self) -> &AuditDetails {
        &self.audit
    }

    /// Why the content was attested.
    #[must_use]
    pub fn reason(&self) -> &Text {
        &self.reason
    }

    /// Whether the attestation is still outstanding.
    #[must_use]
    pub fn is_pending(&self) -> bool {
        self.is_pending
    }

    /// The rendering the attester saw, if kept.
    #[must_use]
    pub fn attested_view(&self) -> Option<&DvMultimedia> {
        self.attested_view.as_ref()
    }

    /// The `OpenPGP` signature, if present. **Unverified.**
    #[must_use]
    pub fn proof(&self) -> Option<&str> {
        self.proof.as_deref()
    }

    /// The specific nodes attested to; empty means the whole object.
    #[must_use]
    pub fn items(&self) -> &[DvEhrUri] {
        &self.items
    }
}

/// One version's audit trail: the commit, plus any attestations.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionHistoryItem {
    version_id: ObjectVersionId,
    audits: Vec<AuditDetails>,
}

impl RevisionHistoryItem {
    /// Builds a revision history item.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the audit list is empty (`Audits_valid`). A
    /// version with no audit is a change nobody made.
    pub fn new(version_id: ObjectVersionId, audits: Vec<AuditDetails>) -> Result<Self, ParseError> {
        if audits.is_empty() {
            return Err(ParseError::invariant(
                "REVISION_HISTORY_ITEM",
                "Audit_valid",
            ));
        }
        Ok(Self { version_id, audits })
    }

    /// Which version this describes.
    #[must_use]
    pub fn version_id(&self) -> &ObjectVersionId {
        &self.version_id
    }

    /// The commit and attestation records.
    #[must_use]
    pub fn audits(&self) -> &[AuditDetails] {
        &self.audits
    }
}

/// The audit trail of a versioned object, **most recent last**.
///
/// # openEHR contradicts itself here, and this is the resolution
///
/// The `REVISION_HISTORY` class table says three things about the order of
/// `items`, and they do not agree:
///
/// | Where | Says |
/// | --- | --- |
/// | class *Purpose* | "The list is in most-recent-**first** order" |
/// | `items` *Meaning* | "The items in this history in most-recent-**last** order" |
/// | `most_recent_version` postcondition | `Result.is_equal(items.last.version_id.value)` |
///
/// Two of the three say most-recent-last, and one of those two is executable.
/// A postcondition is a statement a conformant implementation can be tested
/// against; a Purpose line is prose. This crate follows the postcondition, so
/// [`RevisionHistory::items`] is oldest-first and
/// [`RevisionHistory::most_recent_version`] returns the last.
///
/// Recorded rather than silently chosen, because a caller iterating this list
/// to render an audit trail will get it backwards if they trust the other
/// sentence.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RevisionHistory {
    items: Vec<RevisionHistoryItem>,
}

impl RevisionHistory {
    /// Builds a revision history.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the item list is empty.
    pub fn new(items: Vec<RevisionHistoryItem>) -> Result<Self, ParseError> {
        if items.is_empty() {
            return Err(ParseError::invariant("REVISION_HISTORY", "Items_valid"));
        }
        Ok(Self { items })
    }

    /// The items, oldest first — see the type's documentation.
    #[must_use]
    pub fn items(&self) -> &[RevisionHistoryItem] {
        &self.items
    }

    /// The most recent version's identifier: the **last** item.
    ///
    /// # Panics
    ///
    /// Never: the constructor rejects an empty history.
    #[must_use]
    pub fn most_recent_version(&self) -> &ObjectVersionId {
        self.items
            .last()
            .map(RevisionHistoryItem::version_id)
            .expect("constructor rejects an empty revision history")
    }

    /// The commit time of the most recent item.
    ///
    /// openEHR's `most_recent_version_time_committed`, whose postcondition
    /// reads `items.last.audits.first.time_committed`.
    ///
    /// # Panics
    ///
    /// Never: both lists are non-empty by construction.
    #[must_use]
    pub fn most_recent_version_time_committed(&self) -> &DvDateTime {
        self.items
            .last()
            .map(|i| i.audits()[0].time_committed())
            .expect("constructor rejects an empty revision history")
    }
}

// ---------------------------------------------------------------------------
// Change control
// ---------------------------------------------------------------------------

/// A version of a versioned object.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))]
#[serde(tag = "_type")]
// An IMPORTED_VERSION wraps an ORIGINAL_VERSION plus its own audit, so it is
// necessarily larger. Boxing it would add an allocation per imported version
// and change nothing a caller can observe; the size difference is inherent to
// the model rather than a modelling slip.
#[allow(clippy::large_enum_variant)]
pub enum Version<T> {
    /// A version created here.
    #[serde(rename = "ORIGINAL_VERSION")]
    Original(OriginalVersion<T>),
    /// A version received from another system, wrapped so that its original
    /// identity survives the import.
    #[serde(rename = "IMPORTED_VERSION")]
    Imported(ImportedVersion<T>),
}

impl<T> Version<T> {
    /// The version's identifier.
    #[must_use]
    pub fn uid(&self) -> &ObjectVersionId {
        match self {
            Self::Original(v) => &v.uid,
            // Delegating, per openEHR: an imported version's identity is the
            // identity it had where it was created, not a new one minted here.
            // Minting a local id would make the same clinical fact appear twice
            // when the two systems next exchange data.
            Self::Imported(v) => &v.item.uid,
        }
    }

    /// The version this one succeeds, if any.
    #[must_use]
    pub fn preceding_version_uid(&self) -> Option<&ObjectVersionId> {
        match self {
            Self::Original(v) => v.preceding_version_uid.as_ref(),
            Self::Imported(v) => v.item.preceding_version_uid.as_ref(),
        }
    }

    /// Attestations attached to this version.
    ///
    /// Empty for an imported version: an `IMPORTED_VERSION` wraps the item it
    /// received, and an attestation made elsewhere travels inside that item
    /// rather than being re-asserted here.
    #[must_use]
    pub fn attestations(&self) -> &[Attestation] {
        match self {
            Self::Original(v) => &v.attestations,
            Self::Imported(v) => &v.item.attestations,
        }
    }

    /// The versions merged into this one, empty when it is not a merge.
    #[must_use]
    pub fn other_input_version_uids(&self) -> &[ObjectVersionId] {
        match self {
            Self::Original(v) => &v.other_input_version_uids,
            Self::Imported(v) => &v.item.other_input_version_uids,
        }
    }

    /// The signature over this version, where one was supplied.
    ///
    /// Carried opaquely: this crate does not verify it (`S1.11`), because doing
    /// so needs key management that belongs to the deployment.
    ///
    /// An imported version's signature is the **importer's**, over the wrapper
    /// it created; the wrapped original keeps its own. They are different
    /// assertions by different parties, so this returns the outer one and
    /// `Version::Imported(v) => v.item().signature()` reaches the inner.
    #[must_use]
    pub fn signature(&self) -> Option<&str> {
        match self {
            Self::Original(v) => v.signature.as_deref(),
            Self::Imported(v) => v.signature.as_deref(),
        }
    }

    /// The version's content, absent for a logically deleted version.
    #[must_use]
    pub fn data(&self) -> Option<&T> {
        match self {
            Self::Original(v) => v.data.as_ref(),
            Self::Imported(v) => v.item.data.as_ref(),
        }
    }

    /// The commit metadata.
    #[must_use]
    pub fn commit_audit(&self) -> &AuditDetails {
        match self {
            Self::Original(v) => &v.commit_audit,
            Self::Imported(v) => &v.commit_audit,
        }
    }

    /// The lifecycle state code.
    #[must_use]
    pub fn lifecycle_state_code(&self) -> &str {
        match self {
            Self::Original(v) => v.lifecycle_state.defining_code().code_string(),
            Self::Imported(v) => v.item.lifecycle_state.defining_code().code_string(),
        }
    }

    /// Whether this version marks the object as deleted.
    #[must_use]
    pub fn is_deleted(&self) -> bool {
        self.lifecycle_state_code() == terminology::version_lifecycle_state::DELETED
    }
}

/// A version created by this system.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))]
pub struct OriginalVersion<T> {
    uid: ObjectVersionId,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    preceding_version_uid: Option<ObjectVersionId>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    other_input_version_uids: Vec<ObjectVersionId>,
    lifecycle_state: DvCodedText,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    data: Option<T>,
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    attestations: Vec<Attestation>,
    commit_audit: AuditDetails,
    contribution: ObjectRef,
    /// openEHR declares `signature` on `VERSION`, so an original version
    /// inherits it as surely as an imported one does (`A-18`). It was missing
    /// here, which meant a locally created version could not be signed at all —
    /// only a version that had arrived from somewhere else.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    signature: Option<String>,
}

impl<T> OriginalVersion<T> {
    /// Attaches a signature over this version.
    ///
    /// **Carried, never verified.** Verifying it needs key management that
    /// belongs to the deployment (`S1.11`, `X11.11`), and a library that
    /// checked a signature it could not establish trust for would be asserting
    /// something it does not know.
    #[must_use]
    pub fn with_signature(mut self, signature: impl Into<String>) -> Self {
        self.signature = Some(signature.into());
        self
    }

    /// The signature over this version, if one was supplied. **Unverified.**
    #[must_use]
    pub fn signature(&self) -> Option<&str> {
        self.signature.as_deref()
    }

    /// Builds a version.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the lifecycle state code is not in the
    /// `version_lifecycle_state` group, or if `data` is absent while the state
    /// is not `deleted`. The second rule is the one worth having: a version
    /// with no data and a `complete` state claims the content is finished and
    /// then does not supply it.
    pub fn new(
        uid: ObjectVersionId,
        preceding_version_uid: Option<ObjectVersionId>,
        lifecycle_state_code: &str,
        data: Option<T>,
        commit_audit: AuditDetails,
        contribution: ObjectRef,
    ) -> Result<Self, ParseError> {
        let lifecycle_state = terminology::version_lifecycle_state::GROUP
            .coded_text(lifecycle_state_code)
            .ok_or_else(|| ParseError::invariant("ORIGINAL_VERSION", "Lifecycle_state_valid"))?;
        if data.is_none() && lifecycle_state_code != terminology::version_lifecycle_state::DELETED {
            return Err(ParseError::invariant("ORIGINAL_VERSION", "Data_valid"));
        }
        // `VERSION.Preceding_version_uid_validity`: the first version has no
        // predecessor and every later one has exactly one. openEHR states it as
        // an exclusive or, and both halves matter — a first version naming a
        // predecessor claims a history that does not exist, and a later one
        // naming none starts a second history in the same container.
        //
        // Nothing enforced this, in the library or the store. The store refuses
        // a rootless successor only when the container already has a head, so
        // committing version 2 into an *empty* container succeeded and produced
        // a history whose first entry says it is not the first (`A-23`).
        if uid.version_tree_id().is_first() == preceding_version_uid.is_some() {
            return Err(ParseError::invariant(
                "VERSION",
                "Preceding_version_uid_validity",
            ));
        }
        Ok(Self {
            uid,
            preceding_version_uid,
            other_input_version_uids: Vec::new(),
            signature: None,
            lifecycle_state,
            data,
            attestations: Vec::new(),
            commit_audit,
            contribution,
        })
    }

    /// Adds an attestation.
    #[must_use]
    pub fn with_attestation(mut self, attestation: Attestation) -> Self {
        self.attestations.push(attestation);
        self
    }

    /// Records the other versions merged into this one.
    #[must_use]
    pub fn with_other_input_version_uid(mut self, uid: ObjectVersionId) -> Self {
        self.other_input_version_uids.push(uid);
        self
    }

    /// The version's identifier.
    #[must_use]
    pub fn uid(&self) -> &ObjectVersionId {
        &self.uid
    }

    /// The content.
    #[must_use]
    pub fn data(&self) -> Option<&T> {
        self.data.as_ref()
    }

    /// The commit metadata.
    #[must_use]
    pub fn commit_audit(&self) -> &AuditDetails {
        &self.commit_audit
    }

    /// The contribution this version was committed in.
    #[must_use]
    pub fn contribution(&self) -> &ObjectRef {
        &self.contribution
    }

    /// The attestations over this version.
    #[must_use]
    pub fn attestations(&self) -> &[Attestation] {
        &self.attestations
    }

    /// Whether this version was produced by merging others.
    #[must_use]
    pub fn is_merged(&self) -> bool {
        !self.other_input_version_uids.is_empty()
    }
}

/// A version received from another system.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))]
pub struct ImportedVersion<T> {
    item: OriginalVersion<T>,
    commit_audit: AuditDetails,
    contribution: ObjectRef,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    signature: Option<String>,
}

impl<T> ImportedVersion<T> {
    /// Wraps an original version for import.
    ///
    /// The wrapping is the point: the import gets its own audit — who imported
    /// it, into which system, when — while the wrapped version keeps the
    /// original's audit and identifier. Flattening the two would leave no way
    /// to tell an authored record from a received one.
    #[must_use]
    pub fn new(
        item: OriginalVersion<T>,
        commit_audit: AuditDetails,
        contribution: ObjectRef,
    ) -> Self {
        Self {
            item,
            commit_audit,
            contribution,
            signature: None,
        }
    }

    /// The wrapped version, as it was where it was created.
    #[must_use]
    pub fn item(&self) -> &OriginalVersion<T> {
        &self.item
    }

    /// The audit of the import itself.
    #[must_use]
    pub fn commit_audit(&self) -> &AuditDetails {
        &self.commit_audit
    }
}

impl<T> From<OriginalVersion<T>> for Version<T> {
    fn from(v: OriginalVersion<T>) -> Self {
        Self::Original(v)
    }
}

impl<T> From<ImportedVersion<T>> for Version<T> {
    fn from(v: ImportedVersion<T>) -> Self {
        Self::Imported(v)
    }
}

/// Why a commit to a [`VersionedObject`] was refused.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum CommitError {
    /// The version's `uid` names a different versioned object.
    #[error("version belongs to a different versioned object")]
    WrongObject,

    /// A version with this identifier is already in the history.
    #[error("a version with this id already exists")]
    DuplicateVersion,

    /// The first version of an object must not claim a predecessor, and every
    /// later version must.
    #[error("preceding_version_uid is absent on a successor, or present on the first version")]
    PrecedingVersionMismatch,

    /// The claimed predecessor is not the current latest version.
    ///
    /// This is the concurrent-write case: two clients read version 3 and both
    /// commit version 4. openEHR's answer is a branch, not a silent overwrite,
    /// so this refusal is the point at which a caller must decide.
    #[error("preceding version is not the current latest (concurrent modification)")]
    NotLatest,
}

/// The container for all versions of one logical object.
///
/// ```
/// use openehr::base::{HierObjectId, ObjectId, ObjectRef, ObjectVersionId};
/// use openehr::rm::common::{AuditDetails, OriginalVersion, PartyIdentified, VersionedObject};
/// use openehr::rm::data_types::DvDateTime;
/// use openehr::terminology::{audit_change_type, version_lifecycle_state};
///
/// let uid = HierObjectId::from_uid_str("87284370-2D4B-4E3D-A3F3-F303D2F4F34B").unwrap();
/// let owner = ObjectRef::new("local", "EHR", ObjectId::HierObjectId(uid.clone())).unwrap();
/// let mut vo: VersionedObject<String> =
///     VersionedObject::new(uid, owner.clone(), DvDateTime::new("2026-07-31T09:00:00Z").unwrap());
///
/// let audit = AuditDetails::new(
///     "ehr1.example.org",
///     DvDateTime::new("2026-07-31T09:15:00Z").unwrap(),
///     audit_change_type::CREATION,
///     PartyIdentified::named("Dr A Nurse").unwrap().into(),
/// ).unwrap();
///
/// let v1 = OriginalVersion::new(
///     "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::1".parse().unwrap(),
///     None,
///     version_lifecycle_state::COMPLETE,
///     Some("first".to_string()),
///     audit.clone(),
///     owner.clone(),
/// ).unwrap();
/// vo.commit(v1.into()).unwrap();
/// assert_eq!(vo.version_count(), 1);
///
/// // A second version claiming no predecessor would make the history two
/// // roots, neither wrong on its face. It is now refused one step earlier: the
/// // version cannot be built at all (`VERSION.Preceding_version_uid_validity`).
/// assert!(OriginalVersion::new(
///     "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::2".parse().unwrap(),
///     None,
///     version_lifecycle_state::COMPLETE,
///     Some("second".to_string()),
///     audit.clone(),
///     owner.clone(),
/// ).is_err());
///
/// // `CommitError::PrecedingVersionMismatch` still exists, because a version
/// // that arrived as JSON never went through the constructor — deserialization
/// // is lenient by design (`J9.9`). It is reached by naming a predecessor that
/// // is not the current head.
/// let stale = OriginalVersion::new(
///     "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::3".parse().unwrap(),
///     Some("87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::2".parse().unwrap()),
///     version_lifecycle_state::COMPLETE,
///     Some("third".to_string()),
///     audit,
///     owner,
/// ).unwrap();
/// assert!(vo.commit(stale.into()).is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(bound(serialize = "T: Serialize", deserialize = "T: Deserialize<'de>"))]
pub struct VersionedObject<T> {
    uid: HierObjectId,
    owner_id: ObjectRef,
    time_created: DvDateTime,
    #[serde(skip_serializing_if = "Vec::is_empty", default = "Vec::new")]
    versions: Vec<Version<T>>,
}

impl<T> VersionedObject<T> {
    /// Builds an empty versioned object.
    #[must_use]
    pub fn new(uid: HierObjectId, owner_id: ObjectRef, time_created: DvDateTime) -> Self {
        Self {
            uid,
            owner_id,
            time_created,
            versions: Vec::new(),
        }
    }

    /// The object's identifier.
    #[must_use]
    pub fn uid(&self) -> &HierObjectId {
        &self.uid
    }

    /// The EHR or repository that owns it.
    #[must_use]
    pub fn owner_id(&self) -> &ObjectRef {
        &self.owner_id
    }

    /// When the object was created.
    #[must_use]
    pub fn time_created(&self) -> &DvDateTime {
        &self.time_created
    }

    /// Every version, oldest first.
    #[must_use]
    pub fn all_versions(&self) -> &[Version<T>] {
        &self.versions
    }

    /// How many versions the object has.
    #[must_use]
    pub fn version_count(&self) -> usize {
        self.versions.len()
    }

    /// The most recently committed version.
    #[must_use]
    pub fn latest_version(&self) -> Option<&Version<T>> {
        self.versions.last()
    }

    /// The version with the given identifier.
    #[must_use]
    pub fn version_with_id(&self, uid: &ObjectVersionId) -> Option<&Version<T>> {
        self.versions.iter().find(|v| v.uid() == uid)
    }

    /// Whether the object has a version with the given identifier.
    #[must_use]
    pub fn has_version_id(&self, uid: &ObjectVersionId) -> bool {
        self.version_with_id(uid).is_some()
    }

    /// The version that was current at a given time.
    ///
    /// Returns the latest version whose `time_committed` is at or before
    /// `time`. Returns `None` if the object had no version yet — which is a
    /// different answer from "the object was empty", and the caller needs the
    /// difference to answer "what did the clinician see at 09:15?".
    ///
    /// Versions whose commit time is not comparable with `time` — one carries
    /// a UTC offset and the other does not — are skipped rather than assumed
    /// to be before it. See [`crate::base::iso8601`].
    #[must_use]
    pub fn version_at_time(&self, time: &DvDateTime) -> Option<&Version<T>> {
        self.versions.iter().rfind(|v| {
            matches!(
                v.commit_audit().time_committed().partial_cmp(time),
                Some(core::cmp::Ordering::Less | core::cmp::Ordering::Equal)
            )
        })
    }

    /// Whether the object had any version at a given time.
    #[must_use]
    pub fn has_version_at_time(&self, time: &DvDateTime) -> bool {
        self.version_at_time(time).is_some()
    }

    /// Appends a version, checking that it belongs to this history.
    ///
    /// # Errors
    ///
    /// See [`CommitError`]. Each variant is a history that would read back and
    /// not connect.
    pub fn commit(&mut self, version: Version<T>) -> Result<(), CommitError> {
        if version.uid().object_id() != self.uid.root() {
            return Err(CommitError::WrongObject);
        }
        if self.has_version_id(version.uid()) {
            return Err(CommitError::DuplicateVersion);
        }
        match (self.latest_version(), version.preceding_version_uid()) {
            (None, None) => {}
            (None, Some(_)) | (Some(_), None) => {
                return Err(CommitError::PrecedingVersionMismatch);
            }
            (Some(latest), Some(preceding)) => {
                if latest.uid() != preceding {
                    return Err(CommitError::NotLatest);
                }
            }
        }
        self.versions.push(version);
        Ok(())
    }

    /// The object's audit trail, oldest first (see [`RevisionHistory`]).
    ///
    /// Returns `None` for an object with no versions: [`RevisionHistory`]
    /// refuses to be empty, and an empty history object would assert that the
    /// audit trail exists and is blank.
    #[must_use]
    pub fn revision_history(&self) -> Option<RevisionHistory> {
        let items: Vec<RevisionHistoryItem> = self
            .versions
            .iter()
            .filter_map(|v| {
                RevisionHistoryItem::new(v.uid().clone(), vec![v.commit_audit().clone()]).ok()
            })
            .collect();
        RevisionHistory::new(items).ok()
    }
}

/// A set of versions committed together as one change.
///
/// The unit a user recognises: "I saved the consultation" is one contribution
/// and five compositions. openEHR restricts a contribution's own change type to
/// three of the nine codes, and this type enforces that.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Contribution {
    uid: HierObjectId,
    versions: Vec<ObjectVersionId>,
    audit: AuditDetails,
}

impl Contribution {
    /// The change types a `CONTRIBUTION.audit` may carry.
    pub const PERMITTED_CHANGE_TYPES: [&'static str; 3] = [
        terminology::audit_change_type::CREATION,
        terminology::audit_change_type::AMENDMENT,
        terminology::audit_change_type::DELETED,
    ];

    /// Builds a contribution.
    ///
    /// # Errors
    ///
    /// Returns [`ParseError`] if the version list is empty (`Versions_valid`)
    /// or if the audit's change type is not one of
    /// [`Contribution::PERMITTED_CHANGE_TYPES`].
    pub fn new(
        uid: HierObjectId,
        versions: Vec<ObjectVersionId>,
        audit: AuditDetails,
    ) -> Result<Self, ParseError> {
        if versions.is_empty() {
            return Err(ParseError::invariant("CONTRIBUTION", "Versions_valid"));
        }
        if !Self::PERMITTED_CHANGE_TYPES.contains(&audit.change_type_code()) {
            return Err(ParseError::invariant(
                "CONTRIBUTION",
                "Audit_change_type_valid",
            ));
        }
        Ok(Self {
            uid,
            versions,
            audit,
        })
    }

    /// The contribution's identifier.
    #[must_use]
    pub fn uid(&self) -> &HierObjectId {
        &self.uid
    }

    /// The versions committed in this change.
    #[must_use]
    pub fn versions(&self) -> &[ObjectVersionId] {
        &self.versions
    }

    /// The change's audit metadata.
    #[must_use]
    pub fn audit(&self) -> &AuditDetails {
        &self.audit
    }
}

/// A time-bounded validity period, used across the demographic model.
pub type DateValidity = Interval<DvDate>;

/// A reference to a node inside a version, re-exported here because
/// [`Attestation`] and the demographic model both point at one.
pub type NodeRef = LocatableRef;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::{HierObjectId, ObjectId};
    use crate::rm::data_types::DvText;

    fn audit(code: &str) -> AuditDetails {
        AuditDetails::new(
            "ehr1.example.org",
            DvDateTime::new("2026-07-31T09:15:00Z").unwrap(),
            code,
            PartyIdentified::named("Dr A Nurse").unwrap().into(),
        )
        .unwrap()
    }

    fn versioned() -> (VersionedObject<String>, ObjectRef) {
        let uid = HierObjectId::from_uid_str("87284370-2D4B-4E3D-A3F3-F303D2F4F34B").unwrap();
        let owner = ObjectRef::new("local", "EHR", ObjectId::HierObjectId(uid.clone())).unwrap();
        (
            VersionedObject::new(
                uid,
                owner.clone(),
                DvDateTime::new("2026-07-31T09:00:00Z").unwrap(),
            ),
            owner,
        )
    }

    fn version(n: u32, preceding: Option<u32>, owner: &ObjectRef, code: &str) -> Version<String> {
        let id = |v: u32| -> ObjectVersionId {
            format!("87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::{v}")
                .parse()
                .unwrap()
        };
        OriginalVersion::new(
            id(n),
            preceding.map(id),
            terminology::version_lifecycle_state::COMPLETE,
            Some(format!("content {n}")),
            audit(code),
            owner.clone(),
        )
        .unwrap()
        .into()
    }

    #[test]
    fn a_well_formed_history_commits() {
        let (mut vo, owner) = versioned();
        vo.commit(version(
            1,
            None,
            &owner,
            terminology::audit_change_type::CREATION,
        ))
        .unwrap();
        vo.commit(version(
            2,
            Some(1),
            &owner,
            terminology::audit_change_type::AMENDMENT,
        ))
        .unwrap();
        assert_eq!(vo.version_count(), 2);
        assert_eq!(
            vo.latest_version()
                .unwrap()
                .uid()
                .version_tree_id()
                .trunk_version(),
            2
        );
    }

    #[test]
    fn concurrent_writes_are_refused_rather_than_silently_ordered() {
        let (mut vo, owner) = versioned();
        vo.commit(version(
            1,
            None,
            &owner,
            terminology::audit_change_type::CREATION,
        ))
        .unwrap();
        vo.commit(version(
            2,
            Some(1),
            &owner,
            terminology::audit_change_type::AMENDMENT,
        ))
        .unwrap();
        // Two clients both read version 1 and both write version 3 against it.
        let stale = version(
            3,
            Some(1),
            &owner,
            terminology::audit_change_type::AMENDMENT,
        );
        assert_eq!(vo.commit(stale), Err(CommitError::NotLatest));
    }

    #[test]
    fn a_version_of_another_object_is_refused() {
        let (mut vo, owner) = versioned();
        let foreign = OriginalVersion::new(
            "11111111-2222-3333-4444-555555555555::ehr1.example.org::1"
                .parse()
                .unwrap(),
            None,
            terminology::version_lifecycle_state::COMPLETE,
            Some("x".to_string()),
            audit(terminology::audit_change_type::CREATION),
            owner,
        )
        .unwrap();
        assert_eq!(vo.commit(foreign.into()), Err(CommitError::WrongObject));
    }

    #[test]
    fn a_duplicate_version_id_is_refused() {
        let (mut vo, owner) = versioned();
        vo.commit(version(
            1,
            None,
            &owner,
            terminology::audit_change_type::CREATION,
        ))
        .unwrap();
        assert_eq!(
            vo.commit(version(
                1,
                None,
                &owner,
                terminology::audit_change_type::CREATION
            )),
            Err(CommitError::DuplicateVersion)
        );
    }

    #[test]
    fn a_deleted_version_may_have_no_data_and_others_may_not() {
        let (_, owner) = versioned();
        let id: ObjectVersionId = "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::2"
            .parse()
            .unwrap();
        // Version 2, so it names version 1. This test built it with no
        // predecessor until `Preceding_version_uid_validity` was enforced, and
        // the fixture was itself an instance of the state the invariant
        // forbids — which is how `A-23` came to be believable: the impossible
        // version was easy enough to construct that a test did it by accident.
        let preceding: ObjectVersionId =
            "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::1"
                .parse()
                .unwrap();
        assert!(
            OriginalVersion::<String>::new(
                id.clone(),
                Some(preceding.clone()),
                terminology::version_lifecycle_state::DELETED,
                None,
                audit(terminology::audit_change_type::DELETED),
                owner.clone(),
            )
            .is_ok()
        );
        assert!(
            OriginalVersion::<String>::new(
                id,
                Some(preceding),
                terminology::version_lifecycle_state::COMPLETE,
                None,
                audit(terminology::audit_change_type::CREATION),
                owner,
            )
            .is_err()
        );
    }

    #[test]
    fn a_version_number_and_its_predecessor_must_agree() {
        let (_, owner) = versioned();
        let first: ObjectVersionId = "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::1"
            .parse()
            .unwrap();
        let second: ObjectVersionId = "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::2"
            .parse()
            .unwrap();
        let build = |uid: ObjectVersionId, preceding: Option<ObjectVersionId>| {
            OriginalVersion::new(
                uid,
                preceding,
                terminology::version_lifecycle_state::COMPLETE,
                Some("content".to_owned()),
                audit(terminology::audit_change_type::CREATION),
                owner.clone(),
            )
        };

        // The two legal shapes.
        assert!(build(first.clone(), None).is_ok());
        assert!(build(second.clone(), Some(first.clone())).is_ok());

        // A first version claiming a history that does not exist.
        assert_eq!(
            build(first, Some(second.clone())).unwrap_err().to_string(),
            ParseError::invariant("VERSION", "Preceding_version_uid_validity").to_string()
        );
        // A successor starting a second history in the same container. The
        // store refuses this only once the container has a head, so committing
        // it into an empty one succeeded (`A-23`).
        assert_eq!(
            build(second, None).unwrap_err().to_string(),
            ParseError::invariant("VERSION", "Preceding_version_uid_validity").to_string()
        );
    }

    #[test]
    fn contribution_change_types_are_restricted() {
        let uid = HierObjectId::from_uid_str("87284370-2D4B-4E3D-A3F3-F303D2F4F34B").unwrap();
        let vs: Vec<ObjectVersionId> = vec![
            "87284370-2D4B-4E3D-A3F3-F303D2F4F34B::s.example::1"
                .parse()
                .unwrap(),
        ];
        assert!(
            Contribution::new(
                uid.clone(),
                vs.clone(),
                audit(terminology::audit_change_type::CREATION)
            )
            .is_ok()
        );
        // `synthesis` is a valid AUDIT_DETAILS change type and not a valid
        // CONTRIBUTION one.
        assert!(
            Contribution::new(
                uid.clone(),
                vs,
                audit(terminology::audit_change_type::SYNTHESIS)
            )
            .is_err()
        );
        assert!(
            Contribution::new(
                uid,
                Vec::new(),
                audit(terminology::audit_change_type::CREATION)
            )
            .is_err()
        );
    }

    #[test]
    fn party_proxy_infers_its_class_without_a_type_tag() {
        let related: PartyProxy = serde_json::from_str(
            r#"{"name":"Jane","relationship":{"value":"mother","defining_code":{"terminology_id":{"value":"openehr"},"code_string":"10"}}}"#,
        )
        .unwrap();
        assert_eq!(related.type_name(), "PARTY_RELATED");
        assert!(!related.is_subject());

        let identified: PartyProxy = serde_json::from_str(r#"{"name":"Dr A Nurse"}"#).unwrap();
        assert_eq!(identified.type_name(), "PARTY_IDENTIFIED");

        let subject: PartyProxy = serde_json::from_str("{}").unwrap();
        assert_eq!(subject.type_name(), "PARTY_SELF");
        assert!(subject.is_subject());
    }

    #[test]
    fn a_self_related_party_counts_as_the_subject() {
        // The trap: code that checks only for PARTY_SELF treats an entry whose
        // subject is PARTY_RELATED(0|self|) as being about somebody else.
        let self_related = PartyRelated::new(
            PartyIdentified::named("The patient").unwrap(),
            terminology::subject_relationship::SELF,
        )
        .unwrap();
        assert!(PartyProxy::Related(self_related).is_subject());
    }

    #[test]
    fn version_at_time_skips_incomparable_commit_times() {
        let (mut vo, owner) = versioned();
        vo.commit(version(
            1,
            None,
            &owner,
            terminology::audit_change_type::CREATION,
        ))
        .unwrap();
        // Commit times carry `Z`; a local-time query is not comparable with
        // them, and answering "the latest" would be a guess about the zone.
        let local = DvDateTime::new("2026-07-31T10:00:00").unwrap();
        assert!(vo.version_at_time(&local).is_none());
        let utc = DvDateTime::new("2026-07-31T10:00:00Z").unwrap();
        assert!(vo.version_at_time(&utc).is_some());
    }

    /// An `AUDIT_DETAILS` reports every field it was built with.
    ///
    /// Seven mutants lived in these accessors (`lib:A-09`): `system_id` could
    /// answer `""` or `"xyzzy"`, `description` could answer `None`, and
    /// `is_creation`/`is_deletion` could each be a constant.
    ///
    /// This is the provenance every committed version carries — who changed
    /// what, when, and on whose system — and it is inside the hash chain
    /// (`db:M3.16`). An accessor that lies produces a record that reads back
    /// wrong while the digest still verifies, because the digest is taken over
    /// the stored bytes and not over what the accessor says about them.
    #[test]
    fn audit_details_report_the_change_they_record() {
        let a = audit(terminology::audit_change_type::CREATION)
            .with_description(Text::Plain(DvText::new("initial commit").unwrap()));

        assert_eq!(a.system_id(), "ehr1.example.org");
        assert_eq!(a.time_committed().as_str(), "2026-07-31T09:15:00Z");
        assert_eq!(a.change_type_code(), terminology::audit_change_type::CREATION);
        assert_eq!(a.description().map(Text::value), Some("initial commit"));
        assert_eq!(a.committer().name(), Some("Dr A Nurse"));

        // The two predicates are derived from the code, and each must answer
        // for itself: a creation is not a deletion.
        assert!(a.is_creation());
        assert!(!a.is_deletion());

        let deleted = audit(terminology::audit_change_type::DELETED);
        assert!(deleted.is_deletion());
        assert!(!deleted.is_creation(), "a deletion was reported as a creation");

        // A third code is neither, so neither predicate may be a constant.
        let amended = audit(terminology::audit_change_type::AMENDMENT);
        assert!(!amended.is_creation());
        assert!(!amended.is_deletion());

        // No description is absent rather than empty — "no reason was given"
        // and "the reason was blank" are different records.
        assert_eq!(audit(terminology::audit_change_type::CREATION).description(), None);

        // A system id is required, because an audit with no system says
        // nothing about where the change came from (`System_id_valid`).
        assert!(
            AuditDetails::new(
                "",
                DvDateTime::new("2026-07-31T09:15:00Z").unwrap(),
                terminology::audit_change_type::CREATION,
                PartyIdentified::named("Dr A Nurse").unwrap().into(),
            )
            .is_err()
        );
    }

    /// An `ORIGINAL_VERSION` reports its content, its attestations, and
    /// whether it was merged.
    ///
    /// `data` could answer `None` for every version — which is how a deleted
    /// version is represented, so a constant `None` makes every version look
    /// deleted. `is_merged` could be a constant or have its `!` dropped.
    #[test]
    fn an_original_version_reports_its_content_and_provenance() {
        let (_, owner) = versioned();
        let id = |v: u32| -> ObjectVersionId {
            format!("87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::{v}")
                .parse()
                .unwrap()
        };

        let v = OriginalVersion::new(
            id(1),
            None,
            terminology::version_lifecycle_state::COMPLETE,
            Some("content".to_owned()),
            audit(terminology::audit_change_type::CREATION),
            owner.clone(),
        )
        .unwrap();

        assert_eq!(v.uid(), &id(1));
        assert_eq!(v.data(), Some(&"content".to_owned()));
        assert_eq!(v.commit_audit().system_id(), "ehr1.example.org");
        assert_eq!(v.contribution(), &owner);
        assert!(v.attestations().is_empty());
        // No other input version uids means it was not merged.
        assert!(!v.is_merged());

        // A version carrying another input version *is* a merge.
        let merged = OriginalVersion::new(
            id(2),
            Some(id(1)),
            terminology::version_lifecycle_state::COMPLETE,
            Some("merged".to_owned()),
            audit(terminology::audit_change_type::AMENDMENT),
            owner.clone(),
        )
        .unwrap()
        .with_other_input_version_uid(id(1));
        assert!(merged.is_merged(), "a version with another input is a merge");
        assert_eq!(merged.data(), Some(&"merged".to_owned()));

        // A deleted version carries no data, and that is what distinguishes
        // it — so `data()` must report the difference rather than a constant.
        let deleted = OriginalVersion::new(
            id(3),
            Some(id(2)),
            // A version with no data must say it is deleted (`Data_valid`);
            // that pairing is what makes an absent `data` meaningful.
            terminology::version_lifecycle_state::DELETED,
            None::<String>,
            audit(terminology::audit_change_type::DELETED),
            owner,
        )
        .unwrap();
        assert_eq!(deleted.data(), None);
        assert!(deleted.commit_audit().is_deletion());
    }

    /// A `VERSIONED_OBJECT` reports the versions it holds and which was
    /// current when.
    ///
    /// `all_versions` could answer an empty slice and `has_version_at_time`
    /// could answer a constant (`lib:A-09`). "Was there a version of this
    /// record at that time" is the query `db:P6.11` requires a store to serve,
    /// and a constant `true` says yes for a record that did not yet exist.
    #[test]
    fn a_versioned_object_reports_its_history_and_what_was_current_when() {
        let (mut vo, owner) = versioned();
        vo.commit(version(1, None, &owner, terminology::audit_change_type::CREATION))
            .unwrap();
        vo.commit(version(
            2,
            Some(1),
            &owner,
            terminology::audit_change_type::AMENDMENT,
        ))
        .unwrap();

        assert_eq!(vo.version_count(), 2);
        assert_eq!(vo.all_versions().len(), 2, "the history was reported empty");
        assert_eq!(vo.latest_version().and_then(Version::data), Some(&"content 2".to_owned()));

        // Both commits are at 09:15:00, so a time before them has no version
        // and a time after them has one. A constant answer cannot be right for
        // both.
        let before: DvDateTime = "2026-07-31T09:00:00Z".parse().unwrap();
        let after: DvDateTime = "2026-07-31T10:00:00Z".parse().unwrap();
        assert!(
            !vo.has_version_at_time(&before),
            "a version was reported before the record existed"
        );
        assert!(vo.has_version_at_time(&after));
        assert!(vo.version_at_time(&before).is_none());
        assert!(vo.version_at_time(&after).is_some());
    }

    /// A party reports the name, identifiers and reference it was built with.
    ///
    /// Eight mutants lived in these accessors (`lib:A-09`). `identifiers`
    /// could answer an empty slice and `external_ref` could answer `None` for
    /// every party — which is who the patient, the composer, or the committer
    /// *is*. `PARTY_IDENTIFIED.Basic_validity` exists because a party with none
    /// of the three identifies nobody; an accessor that hides two of them
    /// leaves a record that satisfies the invariant and reads as anonymous.
    #[test]
    fn a_party_reports_every_way_it_identifies_someone() {
        let nhs = DvIdentifier::new("943-476-5919").unwrap();
        let person = PartyRef::new(
            "demographic",
            "PERSON",
            ObjectId::HierObjectId(
                HierObjectId::from_uid_str("6BA7B810-9DAD-11D1-80B4-00C04FD430C8").unwrap(),
            ),
        )
        .unwrap();

        let full = PartyIdentified::new(
            Some("Dr A Nurse".to_owned()),
            vec![nhs.clone()],
            Some(person.clone()),
        )
        .unwrap();
        assert_eq!(full.name(), Some("Dr A Nurse"));
        assert_eq!(full.identifiers(), &[nhs.clone()][..]);
        assert_eq!(full.external_ref(), Some(&person));

        // Each of the three alone is enough to identify someone, and each must
        // be readable — so no accessor may be constant across these.
        let by_name = PartyIdentified::named("Dr A Nurse").unwrap();
        assert_eq!(by_name.name(), Some("Dr A Nurse"));
        assert!(by_name.identifiers().is_empty());
        assert_eq!(by_name.external_ref(), None);

        let by_id = PartyIdentified::new(None, vec![nhs.clone()], None).unwrap();
        assert_eq!(by_id.name(), None);
        assert_eq!(by_id.identifiers(), &[nhs][..]);

        let by_ref = PartyIdentified::new(None, Vec::new(), Some(person.clone())).unwrap();
        assert_eq!(by_ref.external_ref(), Some(&person));

        // None of the three: refused (`Basic_validity`). An empty name is
        // refused separately (`Name_valid`).
        assert!(PartyIdentified::new(None, Vec::new(), None).is_err());
        assert!(PartyIdentified::named("").is_err());

        // Through the proxy, which is what an audit and a composition hold.
        let proxy: PartyProxy = full.into();
        assert_eq!(proxy.name(), Some("Dr A Nurse"));
        assert_eq!(proxy.identifiers().len(), 1);
        assert_eq!(proxy.external_ref(), Some(&person));
        assert!(!proxy.is_subject(), "an identified party is not the subject");

        // `PARTY_SELF` is the subject of the record. Anonymous carries no
        // reference; the other constructor carries one, and the accessor must
        // tell them apart.
        let anonymous = PartySelf::anonymous();
        assert_eq!(anonymous.external_ref(), None);
        let known = PartySelf::with_external_ref(person.clone());
        assert_eq!(known.external_ref(), Some(&person));
        assert_ne!(anonymous, known);

        let self_proxy: PartyProxy = anonymous.into();
        assert!(self_proxy.is_subject(), "PARTY_SELF is the subject of the record");
        assert_eq!(self_proxy.name(), None);
        assert!(self_proxy.identifiers().is_empty());
    }

    /// A locatable reports its uid, links, and feeder audit.
    ///
    /// All three accessors could answer nothing (`lib:A-09`). The feeder audit
    /// is the provenance of imported data — which system sent it, when, and as
    /// what — and a `LINK` is the relation between two records. Both are
    /// optional in openEHR, so a constant "absent" is indistinguishable from
    /// the common case and nothing downstream notices.
    #[test]
    fn a_locatable_reports_its_identity_links_and_provenance() {
        let bare = LocatableAttrs::named("Encounter", "at0000").unwrap();
        assert_eq!(bare.archetype_node_id(), "at0000");
        assert_eq!(bare.uid(), None);

        let uid = UidBasedId::from("6BA7B810-9DAD-11D1-80B4-00C04FD430C8"
            .parse::<HierObjectId>()
            .unwrap());
        let link = Link::new(
            Text::Plain(DvText::new("follow-up").unwrap()),
            Text::Plain(DvText::new("issue").unwrap()),
            DvEhrUri::new("ehr://example.org/records/1").unwrap(),
        );
        let feeder = FeederAudit::new(
            FeederAuditDetails::new("lab.example.org")
                .unwrap()
                .with_time("2026-07-30T08:00:00Z".parse().unwrap()),
        )
        .with_originating_item_id(DvIdentifier::new("LAB-7").unwrap());

        let attrs = LocatableAttrs::named("Encounter", "at0000")
            .unwrap()
            .with_uid(uid.clone())
            .with_link(link.clone())
            .with_feeder_audit(feeder);
        assert_eq!(attrs.uid(), Some(&uid));

        // `links` and `feeder_audit` are defaults on the `Locatable` trait, so
        // they are only reachable through a concrete class.
        let full = crate::rm::data_structures::Element::new(
            attrs,
            DataValue::Text(DvText::new("value").unwrap()),
        );
        assert_eq!(Locatable::uid(&full), Some(&uid));
        assert_eq!(full.links(), &[link][..]);
        let audit = full.feeder_audit().expect("a feeder audit was recorded");
        assert_eq!(audit.originating_system_audit().system_id(), "lab.example.org");
        assert_eq!(
            audit.originating_system_audit().time().map(DvDateTime::as_str),
            Some("2026-07-30T08:00:00Z")
        );
        assert_eq!(audit.originating_system_item_ids().len(), 1);
        // No original content was kept, and that is different from keeping an
        // empty one.
        assert_eq!(audit.original_content(), None);

        // `version_id` has no builder — it arrives only by deserialization —
        // so this is the one path that reads it back at all.
        let details: FeederAuditDetails = serde_json::from_str(
            r#"{"system_id":"lab.example.org","version_id":"rev-42"}"#,
        )
        .expect("deserialize");
        assert_eq!(details.version_id(), Some("rev-42"));
        assert_eq!(details.system_id(), "lab.example.org");
        assert_eq!(details.time(), None);
        // And absent when it was not sent.
        let plain = FeederAuditDetails::new("lab.example.org").unwrap();
        assert_eq!(plain.version_id(), None);
    }

    /// The remaining optional attributes of the change-control envelope.
    ///
    /// Nine accessors could each answer nothing (`lib:A-09`). `is_deleted` is
    /// the one that matters most — a constant `true` reports every version as
    /// logically deleted — and the collections are the ones that go quiet:
    /// an empty `attestations` or `versions` is indistinguishable from the
    /// common case, so nothing downstream notices.
    #[test]
    fn the_optional_parts_of_a_version_and_its_contribution_are_reported() {
        let (_, owner) = versioned();
        let id = |v: u32| -> ObjectVersionId {
            format!("87284370-2D4B-4E3D-A3F3-F303D2F4F34B::ehr1.example.org::{v}")
                .parse()
                .unwrap()
        };
        let attestation = Attestation::new(
            audit(terminology::audit_change_type::ATTESTATION),
            Text::Plain(DvText::new("countersigned").unwrap()),
            false,
        );

        let original = OriginalVersion::new(
            id(1),
            None,
            terminology::version_lifecycle_state::COMPLETE,
            Some("content".to_owned()),
            audit(terminology::audit_change_type::CREATION),
            owner.clone(),
        )
        .unwrap()
        .with_attestation(attestation.clone())
        .with_other_input_version_uid(id(1));

        // Read on the concrete `ORIGINAL_VERSION` as well as through the
        // `VERSION` enum: they are separate accessors, and testing only the
        // enum leaves the concrete one free to answer nothing.
        assert_eq!(original.attestations().len(), 1, "an attestation was dropped");
        assert_eq!(
            original.attestations()[0].reason().value(),
            "countersigned"
        );

        let live: Version<String> = original.into();
        assert!(!live.is_deleted(), "a complete version was reported deleted");
        assert_eq!(live.attestations().len(), 1, "an attestation was dropped");
        assert_eq!(live.other_input_version_uids(), &[id(1)][..]);

        let deleted: Version<String> = OriginalVersion::new(
            id(2),
            Some(id(1)),
            terminology::version_lifecycle_state::DELETED,
            None::<String>,
            audit(terminology::audit_change_type::DELETED),
            owner.clone(),
        )
        .unwrap()
        .into();
        assert!(deleted.is_deleted());
        // Both must be answerable, so `is_deleted` cannot be a constant.
        assert_ne!(live.is_deleted(), deleted.is_deleted());
        // And an unattested version says so rather than reporting one.
        assert!(deleted.attestations().is_empty());

        // A CONTRIBUTION lists the versions it committed. Reporting none makes
        // a change set that changed nothing, which `Versions_valid` forbids at
        // construction — so an empty accessor contradicts the invariant.
        let contribution = Contribution::new(
            HierObjectId::from_uid_str("6BA7B810-9DAD-11D1-80B4-00C04FD430C8").unwrap(),
            vec![id(1), id(2)],
            audit(terminology::audit_change_type::CREATION),
        )
        .unwrap();
        assert_eq!(contribution.versions(), &[id(1), id(2)][..]);
        assert_eq!(contribution.audit().system_id(), "ehr1.example.org");
        assert!(
            Contribution::new(
                HierObjectId::from_uid_str("6BA7B810-9DAD-11D1-80B4-00C04FD430C8").unwrap(),
                Vec::new(),
                audit(terminology::audit_change_type::CREATION),
            )
            .is_err(),
            "a contribution with no versions was accepted"
        );
    }

    /// The optional attributes of an `ARCHETYPED`, a `PARTICIPATION` and a
    /// `FEEDER_AUDIT`.
    ///
    /// Each accessor could answer `None` for every instance. A template id
    /// says which template shaped the data; a participation's time says *when*
    /// someone took part, which is not the same as when the record was
    /// committed; and the original content is the pre-conversion form an
    /// import kept.
    #[test]
    fn optional_attributes_are_absent_only_when_they_were_not_recorded() {
        // ARCHETYPED: with and without a template.
        let bare = Archetyped::new("openEHR-EHR-COMPOSITION.encounter.v1", "1.1.0").unwrap();
        assert_eq!(bare.template_id(), None);
        assert_eq!(bare.rm_version(), "1.1.0");
        let templated = Archetyped::new("openEHR-EHR-COMPOSITION.encounter.v1", "1.1.0")
            .unwrap()
            .with_template("vital_signs.v1")
            .unwrap();
        assert_eq!(
            templated.template_id().map(ToString::to_string),
            Some("vital_signs.v1".to_owned())
        );

        // PARTICIPATION: a time interval is optional and distinct from the
        // commit time.
        let performer: PartyProxy = PartyIdentified::named("Dr A Nurse").unwrap().into();
        let p = Participation::new(
            Text::Plain(DvText::new("performer").unwrap()),
            performer.clone(),
        );
        assert_eq!(p.time(), None);
        let window = Interval::closed(
            DvDateTime::new("2026-07-31T09:00:00Z").unwrap(),
            DvDateTime::new("2026-07-31T09:30:00Z").unwrap(),
        )
        .unwrap();
        let timed = Participation::new(
            Text::Plain(DvText::new("performer").unwrap()),
            performer,
        )
        .with_time(window.clone());
        assert_eq!(timed.time(), Some(&window));

        // FEEDER_AUDIT: the original content an import kept, if any.
        let plain = FeederAudit::new(FeederAuditDetails::new("lab.example.org").unwrap());
        assert_eq!(plain.original_content(), None);
        // Must be a DV_ENCAPSULATED (`Original_content_encapsulated`): the
        // point is to keep the pre-conversion payload, not a description of it.
        let original = DataValue::Parsable(
            crate::rm::data_types::DvParsable::new("OBX|1|NM|...", "HL7v2").unwrap(),
        );
        let kept = FeederAudit::new(FeederAuditDetails::new("lab.example.org").unwrap())
            .with_original_content(original.clone())
            .unwrap();
        assert_eq!(kept.original_content(), Some(&original));

        // PARTY_SELF: `anonymous` is the default shape, so a mutant replacing
        // it with `Default::default()` is only visible beside a non-default
        // one.
        let anonymous = PartySelf::anonymous();
        assert_eq!(anonymous.external_ref(), None);
        assert_eq!(anonymous, PartySelf::default());
    }
}