veredictum 0.1.4

The independent conformance instrument for openEHR clinical data repositories: a machine-readable catalogue of spec-cited test cases, executed against any running CDR, judged by pure-function verdicts
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
// SPDX-FileCopyrightText: Veredictum contributors
// SPDX-License-Identifier: Apache-2.0

//! The pure assertion evaluators — verdict logic over canonical-JSON
//! values, shared by the live driver and the transcript player so any two
//! conformant runners compute identical verdicts.
//!
//! Wire-dependent assertion families (`version`, `signature`,
//! `instance_of`) need reads the driver performs; their FACT comparison
//! still happens here so the judgement stays pure.

#![expect(
    clippy::disallowed_types,
    reason = "dev/verification tooling over JSON artifacts (the catalogue, results, wire \
              exchanges), whose shapes belong to the artifacts and the SUT"
)]

use serde_json::Value;
use std::collections::BTreeMap;

use reqwest::StatusCode;

use crate::exec::resultset;
use crate::exec::state::{Captured, VarStore};
use crate::model::assertion::{Assertion, ColumnSpec, IgnoreSpec, RowsSpec};
use crate::refgrammar::{Segment, Template, ValueRef};
use crate::vocab::{CellComparison, IgnoreSetName, ResultSetMatch};

/// One assertion failure (stable, human-readable — lands in the outcome
/// record and the report).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AssertionFailure(pub String);

/// Which channel an assertion failure belongs to.
///
/// A finding against the server needs a value the server actually served. An
/// assertion the run could not judge at all proves nothing about the SUT, so
/// it takes the inconclusive channel beside a transport fault (ISO/IEC 9646
/// *inconclusive*; interpreter law (c), [`crate::exec`]).
///
/// The two are distinguished as types rather than by reading the message,
/// because a classification branching on a substring changes the moment a
/// message is reworded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AssertionOutcome {
    /// The SUT served a value, and it differs from the asserted one — a
    /// conformance finding, so the row FAILS (law b).
    Mismatch(String),
    /// The assertion cannot be judged on this ITS or on this run: the fact
    /// has no released read, the container the assertion names resolves to
    /// no single family, the authored pattern carries a token outside its
    /// closed vocabulary, or a prerequisite the assertion reads was never
    /// bound. The row is INCONCLUSIVE (law c), attributed to the runner or
    /// the catalogue, never to the server.
    Unjudgeable(String),
}

impl AssertionOutcome {
    /// The one-line reason, whichever channel this outcome carries.
    #[must_use]
    pub fn reason(&self) -> &str {
        match self {
            Self::Mismatch(reason) | Self::Unjudgeable(reason) => reason,
        }
    }
}

impl From<AssertionFailure> for AssertionOutcome {
    /// A pure judge compares a value the SUT SERVED against the authored one,
    /// so its failure is a conformance mismatch by construction. Only the
    /// wire-side resolution that precedes a judge can be unjudgeable, and
    /// those sites name the variant themselves.
    fn from(failure: AssertionFailure) -> Self {
        Self::Mismatch(failure.0)
    }
}

/// Resolve an RM path segment sequence (`context/setting`,
/// `content[0]/data/events[0]/...`) over a canonical-JSON value.
///
/// Supported addressing: object attributes and `[<index>]` list positions —
/// the subset the catalogue's field assertions use.
#[must_use]
pub fn resolve_path<'a>(root: &'a Value, path: &str) -> Option<&'a Value> {
    let mut current = root;
    for raw in path.split('/').filter(|s| !s.is_empty()) {
        let (attr, index) = match raw.split_once('[') {
            Some((attr, rest)) => {
                let index: usize = rest.strip_suffix(']')?.parse().ok()?;
                (attr, Some(index))
            }
            None => (raw, None),
        };
        if !attr.is_empty() {
            current = current.get(attr)?;
        }
        if let Some(i) = index {
            current = current.get(i)?;
        }
    }
    Some(current)
}

/// Render a template against the store (captures become their scalar
/// values; other reference kinds must have been pre-resolved by the driver).
///
/// # Errors
/// A message when a capture is unbound or non-scalar.
pub fn render_template(template: &Template, vars: &VarStore) -> Result<String, String> {
    let mut out = String::new();
    for segment in template.segments() {
        match segment {
            Segment::Lit(s) => out.push_str(s),
            Segment::Ref(ValueRef::Capture { name, .. }) => match vars.get(name) {
                Some(Captured::Scalar(s)) => out.push_str(s),
                Some(_) => return Err(format!("capture {name} is not scalar")),
                None => return Err(format!("capture {name} is not bound")),
            },
            Segment::Ref(other) => {
                return Err(format!("reference {other} must be resolved by the driver"));
            }
        }
    }
    Ok(out)
}

/// Strip the named ignore-sets and explicit paths from a value (top-level
/// path removal; nested server-assigned paths use `/`-separated forms).
///
/// A `**` segment matches zero or more intervening attribute steps, so
/// `**/uid` names one attribute wherever it occurs in a recursive RM
/// structure. Recursive containment is an RM shape, not a fixture depth:
/// `FOLDER.folders` is `List<FOLDER>` (RM common `folder.adoc`), so an
/// ignore-set that could only be written per depth would silently
/// under-cover a deeper tree.
#[must_use]
pub fn strip_ignored(value: &Value, ignored_paths: &[String]) -> Value {
    fn remove(value: &mut Value, segments: &[&str]) {
        let Some((head, rest)) = segments.split_first() else {
            return;
        };
        if *head == "**" {
            // Zero intervening steps: apply the remainder here …
            remove(value, rest);
            // … or one-or-more: descend and retry the same pattern.
            match value {
                Value::Object(map) => {
                    for child in map.values_mut() {
                        remove(child, segments);
                    }
                }
                Value::Array(items) => {
                    for item in items {
                        remove(item, segments);
                    }
                }
                _ => {}
            }
            return;
        }
        match value {
            Value::Object(map) => {
                if rest.is_empty() {
                    map.remove(*head);
                } else if let Some(next) = map.get_mut(*head) {
                    remove(next, rest);
                }
            }
            Value::Array(items) => {
                for item in items {
                    remove(item, segments);
                }
            }
            _ => {}
        }
    }
    let mut out = value.clone();
    for path in ignored_paths {
        let segments: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
        remove(&mut out, &segments);
    }
    out
}

/// A FLAT body: a one-level object whose keys are path-formed strings.
fn is_flat_map(value: &Value) -> bool {
    match value {
        Value::Object(map) => {
            !map.is_empty()
                && map.keys().any(|k| k.contains('/'))
                && map.values().all(|v| !matches!(v, Value::Object(_)))
        }
        _ => false,
    }
}

/// Fold a committed FLAT document's `ctx/*` input-convenience keys onto the
/// RM-tree flat paths a read-back expresses them at, per ITS-REST
/// `simplified_formats` master06 §Context Information: `ctx/participation_*`
/// → `{root}/context/_participation:{i}|*`, `ctx/health_care_facility|*` →
/// `{root}/context/_health_care_facility|*`, and the declared
/// `ctx/id_namespace`/`ctx/id_scheme` defaults expand onto every folded
/// party that carries an `|id` ("default namespace/scheme for external
/// references" — master06 §ID Namespace and Scheme). Pure default-setters
/// whose targets the ignore-set covers (`ctx/time`, `ctx/setting`,
/// composer) pass through untouched for the ignore pass.
fn fold_flat_ctx(committed: &BTreeMap<String, Value>, root: &str) -> BTreeMap<String, Value> {
    let id_namespace = committed.get("ctx/id_namespace").cloned();
    let id_scheme = committed.get("ctx/id_scheme").cloned();
    let mut out: BTreeMap<String, Value> = BTreeMap::new();
    let mut folded_id_carriers: Vec<String> = Vec::new();
    for (key, value) in committed {
        if let Some(rest) = key.strip_prefix("ctx/participation_") {
            // participation_<field>[:i] — default index 0.
            let (field, index) = match rest.split_once(':') {
                Some((f, i)) => (f, i),
                None => (rest, "0"),
            };
            let target = format!("{root}/context/_participation:{index}|{field}");
            if field == "id" {
                folded_id_carriers.push(format!("{root}/context/_participation:{index}"));
            }
            out.insert(target, value.clone());
        } else if let Some(rest) = key.strip_prefix("ctx/health_care_facility|") {
            if rest == "id" {
                folded_id_carriers.push(format!("{root}/context/_health_care_facility"));
            }
            out.insert(
                format!("{root}/context/_health_care_facility|{rest}"),
                value.clone(),
            );
        } else if key == "ctx/id_namespace" || key == "ctx/id_scheme" {
            // consumed as qualifiers below
        } else {
            out.insert(key.clone(), value.clone());
        }
    }
    for carrier in folded_id_carriers {
        if let Some(ns) = &id_namespace {
            out.insert(format!("{carrier}|id_namespace"), ns.clone());
        }
        if let Some(scheme) = &id_scheme {
            out.insert(format!("{carrier}|id_scheme"), scheme.clone());
        }
    }
    out
}

/// Whether a FLAT key falls under an ignore path: the `ctx/*` default-setter
/// spellings map to their master06 targets (`ctx/time` →
/// `context/start_time`, `ctx/setting` → `context/setting`, `ctx/composer_*`
/// → `composer`); any other key matches when its post-root path starts with
/// the ignore path (`uid` also matches the flat `_uid` spelling).
fn flat_key_ignored(key: &str, ignored_paths: &[String]) -> bool {
    let effective: &str = match key {
        "ctx/time" => "context/start_time",
        "ctx/end_time" => "context/end_time",
        "ctx/setting" => "context/setting",
        k if k.starts_with("ctx/composer") => "composer",
        k => k.split_once('/').map_or(k, |(_, rest)| rest),
    };
    let effective = effective.replace("/_uid", "/uid");
    let effective = effective.strip_prefix('_').unwrap_or(&effective);
    ignored_paths.iter().any(|p| {
        effective == p.as_str()
            || effective.starts_with(&format!("{p}/"))
            || effective.starts_with(&format!("{p}|"))
    })
}

/// Canonicalize a FLAT key by eliding every `:0` first-element index
/// (`a:0/b`, `a:0|x`, trailing `a:0`) — the index is optional on the wire
/// (`simplified_formats` master04 §Field Identifiers), so both spellings
/// name the same datum.
fn dezero(key: &str) -> String {
    let inner = key.replace(":0/", "/").replace(":0|", "|");
    inner
        .strip_suffix(":0")
        .map_or(inner.clone(), ToOwned::to_owned)
}

/// Flatten a STRUCTURED body into its FLAT key form per the
/// `simplified_formats` master04 STRUCTURED->FLAT algorithm: object keys
/// join with `/`, array elements append `:{i}` to their segment,
/// `|`-prefixed attribute keys append without a separator, and the
/// empty-string key is the element's main value.
fn flatten_structured(value: &Value, prefix: &str, out: &mut BTreeMap<String, Value>) {
    match value {
        Value::Object(map) => {
            for (key, child) in map {
                let next = if key.is_empty() {
                    prefix.to_owned()
                } else if let Some(attr) = key.strip_prefix('|') {
                    format!("{prefix}|{attr}")
                } else if prefix.is_empty() {
                    key.clone()
                } else {
                    format!("{prefix}/{key}")
                };
                flatten_structured(child, &next, out);
            }
        }
        Value::Array(items) => {
            for (i, item) in items.iter().enumerate() {
                flatten_structured(item, &format!("{prefix}:{i}"), out);
            }
        }
        leaf => {
            out.insert(prefix.to_owned(), leaf.clone());
        }
    }
}

/// STRUCTURED is recognized by its attribute-key shape: `|`-prefixed or
/// empty-string keys somewhere in the tree (master04 §Structured format) —
/// canonical JSON never carries either, so a canonical body is never
/// misread as simplified.
fn has_simplified_leaf_keys(value: &Value) -> bool {
    match value {
        Value::Object(map) => map
            .iter()
            .any(|(k, v)| k.is_empty() || k.starts_with('|') || has_simplified_leaf_keys(v)),
        Value::Array(items) => items.iter().any(has_simplified_leaf_keys),
        _ => false,
    }
}

/// A simplified body in either wire form, as a FLAT key map: a FLAT body
/// verbatim, a STRUCTURED body via the master04 flattening. `None` for
/// canonical/other bodies (a canonical COMPOSITION carries `_type`).
fn simplified_as_flat(value: &Value) -> Option<BTreeMap<String, Value>> {
    let Value::Object(map) = value else {
        return None;
    };
    if is_flat_map(value) {
        return Some(map.iter().map(|(k, v)| (k.clone(), v.clone())).collect());
    }
    if !map.is_empty()
        && map.keys().all(|k| !k.contains('/'))
        && !map.contains_key("_type")
        && (map.contains_key("ctx") || has_simplified_leaf_keys(value))
    {
        let mut out = BTreeMap::new();
        flatten_structured(value, "", &mut out);
        return Some(out);
    }
    None
}

/// FLAT round-trip equivalence: fold the committed side's ctx keys onto the
/// read-back's RM-path forms (master06), drop ignore-set keys from both sides,
/// then require every committed entry to appear in the read-back with an equal
/// value (keys compared in their `:0`-elided canonical form, master04 §Field
/// Identifiers). Read-back surplus is tolerated, because the export is the full
/// RM projection of the committed data (`simplified_formats` master04), so the
/// round-trip guarantee is that no committed datum is lost or altered. (No
/// openEHR spec defines a round-trip comparator — our own design over the
/// master04 and master06 semantics.)
fn flat_equivalent(
    actual: &BTreeMap<String, Value>,
    committed: &BTreeMap<String, Value>,
    ignored_paths: &[String],
) -> bool {
    let root = actual
        .keys()
        .find(|k| !k.starts_with("ctx/"))
        .and_then(|k| k.split(['/', ':']).next())
        .unwrap_or_default()
        .to_owned();
    let normalized: BTreeMap<String, &Value> = actual.iter().map(|(k, v)| (dezero(k), v)).collect();
    let folded = fold_flat_ctx(committed, &root);
    folded
        .iter()
        .filter(|(k, _)| !flat_key_ignored(k, ignored_paths))
        .all(|(k, want)| {
            normalized
                .get(&dezero(k))
                .is_some_and(|got| resultset::cells_equal(got, want))
        })
}

/// The `equivalent` comparison.
///
/// Structural equality after stripping the resolved ignore paths from both
/// sides, with numeric leaves compared by value through the result-set cell
/// rule and canonical `_type` self-tag presence normalized (`rm_cells_equal`).
/// FLAT bodies take the master06-aware round-trip rule (`flat_equivalent`).
#[must_use]
pub fn equivalent(actual: &Value, expected: &Value, ignored_paths: &[String]) -> bool {
    if let (Some(a), Some(e)) = (simplified_as_flat(actual), simplified_as_flat(expected)) {
        return flat_equivalent(&a, &e, ignored_paths);
    }
    let a = strip_ignored(actual, ignored_paths);
    let b = strip_ignored(expected, ignored_paths);
    rm_cells_equal(&a, &b)
}

/// Canonical-RM structural equality for `equivalent`: the result-set cell rule
/// everywhere, except that a `_type` self-tag present on only one side of an
/// object is not a content difference. ITS-REST overview Resources.md §JSON
/// Format makes `_type` presence conditional ("should be used to specify the RM
/// type whenever polymorphism is involved, or when the underlying definition in
/// RM type is abstract") while the MUST governs its value, so a codec that
/// self-tags every object and a sparsely tagged committed twin describe the same
/// RM content. Present on both sides, the tags must be equal, which keeps a
/// genuine polymorphic-type substitution detectable.
fn rm_cells_equal(a: &Value, b: &Value) -> bool {
    match (a, b) {
        (Value::Object(x), Value::Object(y)) => {
            let keys: std::collections::BTreeSet<&str> = x
                .keys()
                .chain(y.keys())
                .map(String::as_str)
                .filter(|k| *k != "_type")
                .collect();
            let type_tags_agree = match (x.get("_type"), y.get("_type")) {
                (Some(ta), Some(tb)) => ta == tb,
                _ => true,
            };
            type_tags_agree
                && keys.iter().all(|k| match (x.get(*k), y.get(*k)) {
                    (Some(va), Some(vb)) => rm_cells_equal(va, vb),
                    _ => false,
                })
        }
        (Value::Array(x), Value::Array(y)) => {
            x.len() == y.len() && x.iter().zip(y).all(|(va, vb)| rm_cells_equal(va, vb))
        }
        _ => resultset::cells_equal(a, b),
    }
}

/// Resolve the `ignoring:` list into concrete paths: named sets come from
/// the binding (`server_assigned`) and the selectors vocabulary
/// (`ctx_defaults`); explicit paths pass through.
#[must_use]
pub fn resolve_ignore_sets(
    specs: &[IgnoreSpec],
    server_assigned: &[String],
    ctx_defaults: &[String],
) -> Vec<String> {
    let mut paths = Vec::new();
    for spec in specs {
        match spec {
            IgnoreSpec::Named(IgnoreSetName::ServerAssigned) => {
                paths.extend(server_assigned.iter().cloned());
            }
            IgnoreSpec::Named(IgnoreSetName::CtxDefaults) => {
                paths.extend(ctx_defaults.iter().cloned());
            }
            IgnoreSpec::Path(p) => paths.push(p.clone()),
        }
    }
    paths
}

/// Evaluate a `field` assertion over a response body.
///
/// # Errors
/// [`AssertionFailure`] describing the violated predicate.
#[expect(
    clippy::too_many_arguments,
    reason = "mirrors the assertion's field set"
)]
pub fn eval_field(
    body: &Value,
    path: &str,
    equals: Option<&Value>,
    not_equals: Option<&Value>,
    exists: Option<bool>,
    absent: Option<bool>,
    matches: Option<&str>,
    absent_or_matches: Option<&str>,
) -> Result<(), AssertionFailure> {
    let found = resolve_path(body, path);
    if let Some(true) = exists {
        return found
            .map(|_| ())
            .ok_or_else(|| AssertionFailure(format!("{path}: expected present, is absent")));
    }
    if let Some(true) = absent {
        return match found {
            None => Ok(()),
            Some(v) => Err(AssertionFailure(format!(
                "{path}: expected absent, found {v}"
            ))),
        };
    }
    if let Some(pattern) = absent_or_matches {
        return match found {
            None => Ok(()),
            Some(actual) => match_serialized(path, actual, pattern),
        };
    }
    let Some(actual) = found else {
        return Err(AssertionFailure(format!(
            "{path}: path resolves to nothing"
        )));
    };
    if let Some(want) = equals {
        if resultset::cells_equal(actual, want) {
            return Ok(());
        }
        return Err(AssertionFailure(format!(
            "{path}: {actual} != expected {want}"
        )));
    }
    if let Some(reject) = not_equals {
        if resultset::cells_equal(actual, reject) {
            return Err(AssertionFailure(format!(
                "{path}: equals the client-supplied value {reject} (must be server-set)"
            )));
        }
        return Ok(());
    }
    if let Some(pattern) = matches {
        return match_serialized(path, actual, pattern);
    }
    Ok(())
}

/// Match one resolved field value's serialized form against a regex, shared by
/// the `matches` and `absent_or_matches` predicates.
fn match_serialized(path: &str, actual: &Value, pattern: &str) -> Result<(), AssertionFailure> {
    let re = regex::Regex::new(pattern)
        .map_err(|e| AssertionFailure(format!("{path}: pattern does not compile: {e}")))?;
    let text = match actual {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    };
    if re.is_match(&text) {
        return Ok(());
    }
    Err(AssertionFailure(format!(
        "{path}: {text:?} does not match {pattern:?}"
    )))
}

/// Evaluate the aggregate `unique` assertion over the per-row stores
/// (law e: collected across all rows, evaluated once).
///
/// # Errors
/// [`AssertionFailure`] naming the duplicate value.
pub fn eval_unique(
    over: &crate::ids::CaptureName,
    all_rows: &[VarStore],
) -> Result<(), AssertionFailure> {
    let mut seen: Vec<&str> = Vec::new();
    for (row, store) in all_rows.iter().enumerate() {
        let Some(value) = store.scalar(over) else {
            continue; // rows that never bound the capture do not participate
        };
        if seen.contains(&value) {
            return Err(AssertionFailure(format!(
                "unique over ${{{over}}}: value {value:?} repeats at row {row}"
            )));
        }
        seen.push(value);
    }
    Ok(())
}

/// Evaluate a `returns` assertion against a (scalar-shaped) body.
///
/// # Errors
/// [`AssertionFailure`] describing the mismatch.
pub fn eval_returns(
    body: &Value,
    equals: Option<&Value>,
    matches: Option<&str>,
    omits: Option<&str>,
) -> Result<(), AssertionFailure> {
    if let Some(want) = equals {
        if resultset::cells_equal(body, want) {
            return Ok(());
        }
        return Err(AssertionFailure(format!(
            "returns: {body} != expected {want}"
        )));
    }
    let text = match body {
        Value::String(s) => s.clone(),
        other => other.to_string(),
    };
    if let Some(pattern) = matches {
        let re = regex::Regex::new(pattern)
            .map_err(|e| AssertionFailure(format!("returns pattern does not compile: {e}")))?;
        if !re.is_match(&text) {
            return Err(AssertionFailure(format!(
                "returns: {text:?} does not match {pattern:?}"
            )));
        }
    }
    if let Some(pattern) = omits {
        let re = regex::Regex::new(pattern).map_err(|e| {
            AssertionFailure(format!("returns omits pattern does not compile: {e}"))
        })?;
        if re.is_match(&text) {
            return Err(AssertionFailure(format!(
                "returns: {text:?} matches {pattern:?} but must omit it"
            )));
        }
    }
    Ok(())
}

/// Evaluate a `returns` assertion against one exchange's status and body.
///
/// A Boolean SM return (`has_directory`, `has_path`, `has_query`) is realized
/// on the wire as PRESENCE: 2xx = TRUE, the mapped not-found = FALSE — the
/// response body is the resource (or empty per `Prefer`), never a boolean
/// literal (SM `openehr_platform` `I_EHR_DIRECTORY` / `I_DEFINITION_QUERY`
/// `has_*`: Boolean; ITS-REST realizes them as GET). Every other predicate
/// compares the served body, through [`eval_returns`].
///
/// # Errors
/// [`AssertionFailure`] describing the mismatch.
pub fn eval_returns_wire(
    status: StatusCode,
    body: &Value,
    equals: Option<&Value>,
    matches: Option<&str>,
    omits: Option<&str>,
) -> Result<(), AssertionFailure> {
    let Some(Value::Bool(want)) = equals else {
        return eval_returns(body, equals, matches, omits);
    };
    let observed = status.is_success();
    if observed == *want {
        return Ok(());
    }
    Err(AssertionFailure(format!(
        "returns: wire presence {observed} != expected {want} (status {})",
        status.as_u16()
    )))
}

/// Evaluate an `instance_of` assertion structurally: the served body
/// self-identifies as the named RM type.
///
/// # Errors
/// [`AssertionFailure`] naming the type the body carries, or its absence.
pub fn eval_instance_of(body: &Value, rm_type: &str) -> Result<(), AssertionFailure> {
    match body.get("_type").and_then(Value::as_str) {
        Some(t) if t == rm_type => Ok(()),
        Some(t) => Err(AssertionFailure(format!(
            "instance_of: body is {t}, expected {rm_type}"
        ))),
        None => Err(AssertionFailure(format!(
            "instance_of: body carries no _type (expected {rm_type})"
        ))),
    }
}

/// One `result_set` expectation whose rows are already resolved to values.
#[derive(Debug, Clone, Copy)]
pub struct ResolvedResultSet<'a> {
    /// How the expected rows are compared against the served ones.
    pub match_mode: ResultSetMatch,
    /// The expected rows; `None` where the assertion carries none.
    pub rows: Option<&'a [Value]>,
    /// The exact row count, for `match: count`.
    pub count: Option<u64>,
    /// The expected column aliases, when the row asserts them.
    pub columns: Option<&'a [ColumnSpec]>,
    /// The declared cell comparison; the default is the exact lexeme.
    pub cells: CellComparison,
}

/// Compare a served `RESULT_SET` against a resolved expectation.
///
/// Returns the non-gating divergences the declared cell mode tolerated, one
/// line each — empty under the default exact comparison.
///
/// # Errors
/// [`AssertionFailure`] describing the first divergence that gates, or the
/// absence of any comparable expectation.
pub fn eval_result_set_against(
    body: &Value,
    expectation: ResolvedResultSet<'_>,
) -> Result<Vec<String>, AssertionFailure> {
    let ResolvedResultSet {
        match_mode,
        rows,
        count,
        columns,
        cells,
    } = expectation;
    let mut cmp = resultset::CellComparator::new(cells);
    if let Some(cols) = columns {
        let names: Vec<String> = cols.iter().map(|c| c.name.clone()).collect();
        resultset::compare_columns(body, &names).map_err(|e| AssertionFailure(e.0))?;
    }
    let outcome = match (match_mode, rows, count) {
        (ResultSetMatch::Count, _, Some(n)) => resultset::compare_count(body, n),
        (ResultSetMatch::Ordered, Some(rows), _) => {
            resultset::compare_ordered(body, rows, &mut cmp)
        }
        (ResultSetMatch::Set, Some(rows), _) => resultset::compare_bag(body, rows, &mut cmp),
        (ResultSetMatch::Contains, Some(rows), _) => {
            resultset::compare_contains(body, rows, &mut cmp)
        }
        _ => {
            return Err(AssertionFailure(
                "result_set: no comparable expectation resolved".into(),
            ));
        }
    };
    outcome.map_err(|e| AssertionFailure(e.0))?;
    Ok(recorded_divergences(&cmp))
}

/// The comparator's tolerated divergences, one reportable line each.
fn recorded_divergences(cmp: &resultset::CellComparator) -> Vec<String> {
    cmp.divergences()
        .iter()
        .map(|d| {
            format!(
                "result_set: {d} — ITS-REST docs/overview/Resources.md §Datetime format puts the \
                 served spelling at SHOULD strength, so the row still passes"
            )
        })
        .collect()
}

/// The XML Schema instance namespace, whose `type` attribute selects the
/// concrete type of an element declared with an abstract one
/// (<https://www.w3.org/TR/xmlschema-1/#xsi_type>).
const XSI_NAMESPACE: &str = "http://www.w3.org/2001/XMLSchema-instance";

/// The judged facts of an XML document entity's ROOT element.
#[derive(Debug, Clone, PartialEq, Eq)]
struct XmlRootElement {
    /// The root's LOCAL name.
    local: String,
    /// The namespace URI the root resolves to, when the document binds one.
    namespace: Option<String>,
    /// The root's `xsi:type`, when present: the `QName`'s LOCAL part and the
    /// namespace URI its prefix resolves to (absent when the `QName` is
    /// unprefixed and the document binds no default namespace).
    xsi_type: Option<(String, Option<String>)>,
}

/// The `xsi:type` an element carries, resolved: the `QName`'s LOCAL part and the
/// namespace URI its prefix resolves to.
///
/// The attribute is identified by its resolved NAME (the XML Schema instance
/// namespace + local `type`), never by the literal prefix `xsi`, which a
/// document is free to spell any way it binds it. Its VALUE is a `QName` and
/// resolves by the `QName`-in-content rule — an unprefixed `QName` takes the
/// document's DEFAULT namespace — which `resolve_element` implements.
///
/// # Errors
/// A message when an attribute is malformed or its value is not valid UTF-8,
/// or when the `xsi:type` `QName` carries a prefix the document never bound.
fn root_xsi_type(
    reader: &mut quick_xml::NsReader<&[u8]>,
    start: &quick_xml::events::BytesStart<'_>,
) -> Result<Option<(String, Option<String>)>, AssertionFailure> {
    for attribute in start.attributes() {
        let attribute = attribute
            .map_err(|e| AssertionFailure(format!("xml_root: body is not well-formed XML: {e}")))?;
        let (attribute_ns, attribute_local) =
            reader.resolver_mut().resolve_attribute(attribute.key);
        let is_xsi_type = attribute_local.as_ref() == b"type"
            && matches!(
                attribute_ns,
                quick_xml::name::ResolveResult::Bound(ns) if ns.as_ref() == XSI_NAMESPACE.as_bytes()
            );
        if !is_xsi_type {
            continue;
        }
        // Attribute-value normalization per XML 1.0 §3.3.3 (the version every
        // published ITS-XML schema and canonical openEHR document is written
        // in — `<?xml version="1.0"?>`): entity references resolved, tab/CR/LF
        // folded to spaces, before the value is read as a QName.
        let value = attribute
            .normalized_value(quick_xml::XmlVersion::Implicit1_0)
            .map_err(|e| AssertionFailure(format!("xml_root: xsi:type is not readable: {e}")))?;
        let (type_ns, type_local) = reader
            .resolver_mut()
            .resolve_element(quick_xml::name::QName(value.as_bytes()));
        let namespace = match type_ns {
            quick_xml::name::ResolveResult::Bound(ns) => {
                Some(String::from_utf8_lossy(ns.as_ref()).into_owned())
            }
            quick_xml::name::ResolveResult::Unbound => None,
            quick_xml::name::ResolveResult::Unknown(prefix) => {
                return Err(AssertionFailure(format!(
                    "xml_root: the xsi:type QName's prefix `{}` is not bound to any namespace",
                    String::from_utf8_lossy(&prefix)
                )));
            }
        };
        return Ok(Some((
            String::from_utf8_lossy(type_local.as_ref()).into_owned(),
            namespace,
        )));
    }
    Ok(None)
}

/// The root element of an XML document entity: its LOCAL name, the namespace
/// URI it resolves to when the document binds one, and its `xsi:type` when it
/// carries one.
///
/// Namespace resolution is delegated to `quick_xml::NsReader` rather than
/// pattern-matched out of the text: a conforming document may bind the
/// namespace with any prefix (or as the default `xmlns`), and only a real
/// resolver relates the root's prefix to the URI in scope for it. The
/// `xsi:type` VALUE is a `QName` too and resolves by the `QName`-in-content rule —
/// an unprefixed `QName` takes the DEFAULT namespace — which is what
/// `resolve_element` implements.
///
/// The whole document is read to end-of-input, not just its first tag: a
/// payload that is not well-formed cannot be valid against any schema either,
/// so the same §"XML Format" MUST that fixes the root also rules it out.
///
/// # Errors
/// A message when the payload is not a well-formed XML document entity.
fn xml_root_element(text: &str) -> Result<XmlRootElement, AssertionFailure> {
    let mut reader = quick_xml::NsReader::from_str(text);
    let mut root: Option<XmlRootElement> = None;
    // Element balance, tracked here rather than left to the reader's
    // configuration: at end of input an unclosed element is a truncated
    // document, which no schema can validate.
    let mut depth: i64 = 0;
    loop {
        let (resolved, event) = reader
            .read_resolved_event()
            .map_err(|e| AssertionFailure(format!("xml_root: body is not well-formed XML: {e}")))?;
        if matches!(event, quick_xml::events::Event::Start(_)) {
            depth += 1;
        } else if matches!(event, quick_xml::events::Event::End(_)) {
            depth -= 1;
        }
        match event {
            quick_xml::events::Event::Eof => break,
            quick_xml::events::Event::Start(e) | quick_xml::events::Event::Empty(e)
                if root.is_none() =>
            {
                let local = String::from_utf8_lossy(e.local_name().as_ref()).into_owned();
                let namespace = match resolved {
                    quick_xml::name::ResolveResult::Bound(ns) => {
                        Some(String::from_utf8_lossy(ns.as_ref()).into_owned())
                    }
                    quick_xml::name::ResolveResult::Unbound => None,
                    quick_xml::name::ResolveResult::Unknown(prefix) => {
                        return Err(AssertionFailure(format!(
                            "xml_root: the root element's prefix `{}` is not bound to any namespace",
                            String::from_utf8_lossy(&prefix)
                        )));
                    }
                };
                let xsi_type = root_xsi_type(&mut reader, &e)?;
                root = Some(XmlRootElement {
                    local,
                    namespace,
                    xsi_type,
                });
            }
            // The prolog (declaration, doctype, comments, whitespace) before
            // the root, and the whole content after it: read through, so an
            // ill-formed document fails rather than passing on its first tag.
            _ => {}
        }
    }
    if depth != 0 {
        return Err(AssertionFailure(
            "xml_root: body is not well-formed XML: the document ends with unclosed elements"
                .to_owned(),
        ));
    }
    root.ok_or_else(|| AssertionFailure("xml_root: body carries no XML element at all".to_owned()))
}

/// Evaluate an `xml_root` assertion over a canonical-XML response body.
///
/// # Errors
/// [`AssertionFailure`] when the body is not an XML document entity, when the
/// root's local name differs, when its namespace is not the expected published
/// openEHR ITS-XML target namespace, or when an expected `xsi_type` is absent
/// or names another type.
pub fn eval_xml_root(
    body: &Value,
    name: &str,
    namespace: Option<crate::vocab::XmlNamespace>,
    xsi_type: Option<&str>,
) -> Result<(), AssertionFailure> {
    let Value::String(text) = body else {
        return Err(AssertionFailure(format!(
            "xml_root: expected a canonical-XML document body, got {}",
            match body {
                Value::Null => "no body".to_owned(),
                other => other.to_string().chars().take(80).collect::<String>(),
            }
        )));
    };
    let root = xml_root_element(text)?;
    let local = root.local;
    if local != name {
        return Err(AssertionFailure(format!(
            "xml_root: document root is `{local}`, expected the published document element `{name}`"
        )));
    }
    if let Some(expected) = namespace {
        match root.namespace.as_deref() {
            Some(uri) if expected.accepts(uri) => {}
            Some(uri) => {
                return Err(AssertionFailure(format!(
                    "xml_root: root `{local}` is in namespace {uri:?}, expected {}",
                    expected.token()
                )));
            }
            None => {
                return Err(AssertionFailure(format!(
                    "xml_root: root `{local}` is in NO namespace, expected {} — every published \
                     ITS-XML schema declares elementFormDefault=\"qualified\" over its \
                     targetNamespace, so a conforming document's root is namespace-qualified",
                    expected.token()
                )));
            }
        }
    }
    let Some(expected_type) = xsi_type else {
        return Ok(());
    };
    // An element whose XSD-declared type is abstract MUST name a non-abstract
    // derived type with `xsi:type` (XML Schema Part 1 §2.6.1 + §3.4.6,
    // <https://www.w3.org/TR/xmlschema-1/#xsi_type>).
    let Some((type_local, type_uri)) = root.xsi_type else {
        return Err(AssertionFailure(format!(
            "xml_root: root `{local}` carries no xsi:type, expected `{expected_type}` — the \
             published element's declared type is abstract, and an instance may not use an \
             abstract type directly"
        )));
    };
    if type_local != expected_type {
        return Err(AssertionFailure(format!(
            "xml_root: root `{local}` names concrete type `{type_local}`, expected \
             `{expected_type}`"
        )));
    }
    // The ITS-XML complexTypes are declared in each schema's own
    // `targetNamespace`, so a type QName in another namespace names another
    // schema's type — judged by the same expectation as the root.
    if let Some(expected) = namespace {
        match type_uri.as_deref() {
            Some(uri) if expected.accepts(uri) => {}
            Some(uri) => {
                return Err(AssertionFailure(format!(
                    "xml_root: xsi:type `{type_local}` is in namespace {uri:?}, expected {}",
                    expected.token()
                )));
            }
            None => {
                return Err(AssertionFailure(format!(
                    "xml_root: xsi:type `{type_local}` resolves to NO namespace, expected {} — \
                     the ITS-XML complexTypes are declared in each schema's targetNamespace",
                    expected.token()
                )));
            }
        }
    }
    Ok(())
}

/// When the driver judges an assertion's declared facts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Judgement {
    /// Judged where it is authored: on its flow step, or after the flow for a
    /// postcondition.
    PerStep,
    /// Judged once per case, after the last row (interpreter law e).
    Aggregate,
    /// Carries no pass/fail criterion of its own. Exactly two members, both
    /// adjudicated: `message_exemplar` (register AMB-217 — an error body is a
    /// MAY, so its text is never a criterion) and `state`, whose machine
    /// verification is the case its `verified_by` names.
    Informative,
}

/// The judgement the driver gives an assertion.
///
/// The match is exhaustive on purpose: a new assertion variant cannot be added
/// without classifying it here, and a [`Judgement::PerStep`] variant no
/// evaluator reaches would be an assertion authored in the catalogue and never
/// judged, which is the silent-pass class this instrument refuses.
#[must_use]
pub fn judgement_of(assertion: &Assertion) -> Judgement {
    match assertion {
        Assertion::Field { .. }
        | Assertion::Equivalent { .. }
        | Assertion::Returns { .. }
        | Assertion::ResultSet { .. }
        | Assertion::XmlRoot { .. }
        | Assertion::InstanceOf { .. }
        | Assertion::Signature { .. }
        | Assertion::Version { .. } => Judgement::PerStep,
        Assertion::Unique { .. } => Judgement::Aggregate,
        Assertion::MessageExemplar { .. } | Assertion::State { .. } => Judgement::Informative,
    }
}

/// The facts a RECORDED exchange carries: the status the server answered
/// with, and the body it served.
///
/// This is the whole ground a transcript replay judges from — a recorded
/// exchange carries no committed request payload, no corpus, no versioned
/// read and no instance posture.
#[derive(Debug, Clone, Copy)]
pub struct ExchangeFacts<'a> {
    /// The status code the recorded server answered with.
    pub status: StatusCode,
    /// The recorded response body, or [`Value::Null`] where it served none.
    pub body: &'a Value,
}

/// Whether an assertion's facts are all in a recorded exchange.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReplayJudgement {
    /// Every fact is in the exchange, so [`eval_from_exchange`] judges it.
    FromExchange,
    /// A fact rides a seam a transcript never records: the payload committed
    /// earlier in the row, a resolved corpus or capture reference, a
    /// versioned-object read, or the signing posture of the addressed
    /// instance. A replay REFUSES such an assertion rather than passing it.
    Unrecorded,
    /// Never judged on a step: aggregate (law e) or informative.
    NotPerStep,
}

/// How a transcript replay may treat one assertion.
///
/// The match is exhaustive on purpose, exactly as [`judgement_of`] is: a new
/// assertion variant cannot be added without saying whether a recorded exchange
/// decides it, so no family slips into a replay unevaluated. Two families split
/// per assertion rather than per family, because a `field` comparand carrying a
/// `${…}` reference needs the resolver, and `result_set rows.from` names a
/// corpus view over the committed-set uids provisioning bound.
#[must_use]
pub fn replay_judgement(assertion: &Assertion) -> ReplayJudgement {
    match assertion {
        Assertion::Returns { .. } | Assertion::XmlRoot { .. } | Assertion::InstanceOf { .. } => {
            ReplayJudgement::FromExchange
        }
        Assertion::Field {
            equals, not_equals, ..
        } => {
            if equals
                .iter()
                .chain(not_equals)
                .all(|value| value.literal().is_some())
            {
                ReplayJudgement::FromExchange
            } else {
                ReplayJudgement::Unrecorded
            }
        }
        Assertion::ResultSet { rows, .. } => match rows {
            Some(RowsSpec::From(_)) => ReplayJudgement::Unrecorded,
            Some(RowsSpec::Inline(_)) | None => ReplayJudgement::FromExchange,
        },
        Assertion::Equivalent { .. } | Assertion::Signature { .. } | Assertion::Version { .. } => {
            ReplayJudgement::Unrecorded
        }
        Assertion::Unique { .. } | Assertion::MessageExemplar { .. } | Assertion::State { .. } => {
            ReplayJudgement::NotPerStep
        }
    }
}

/// Evaluate one assertion from a recorded exchange alone.
///
/// Returns the non-gating divergences a passing assertion tolerated. An
/// assertion [`replay_judgement`] classifies [`ReplayJudgement::Unrecorded`]
/// answers [`AssertionOutcome::Unjudgeable`], never a pass, so no replay
/// reproduces a verdict over something nobody evaluated.
///
/// # Errors
/// [`AssertionOutcome::Mismatch`] for a served value that contradicts the
/// assertion, [`AssertionOutcome::Unjudgeable`] for a fact the exchange does
/// not carry.
pub fn eval_from_exchange(
    assertion: &Assertion,
    facts: ExchangeFacts<'_>,
) -> Result<Vec<String>, AssertionOutcome> {
    let unrecorded = || {
        AssertionOutcome::Unjudgeable(format!(
            "{}: the recorded exchange carries no ground for this family",
            assertion.family()
        ))
    };
    match replay_judgement(assertion) {
        ReplayJudgement::NotPerStep => return Ok(Vec::new()),
        ReplayJudgement::Unrecorded => return Err(unrecorded()),
        ReplayJudgement::FromExchange => {}
    }
    let body = facts.body;
    let judged: Result<(), AssertionFailure> = match assertion {
        Assertion::Field {
            path,
            equals,
            not_equals,
            exists,
            absent,
            matches,
            absent_or_matches,
        } => eval_field(
            body,
            path,
            equals
                .as_ref()
                .and_then(crate::model::value::TemplatedValue::literal)
                .as_ref(),
            not_equals
                .as_ref()
                .and_then(crate::model::value::TemplatedValue::literal)
                .as_ref(),
            *exists,
            *absent,
            matches.as_deref(),
            absent_or_matches.as_deref(),
        ),
        Assertion::Returns {
            equals,
            matches,
            omits,
        } => eval_returns_wire(
            facts.status,
            body,
            equals.as_ref(),
            matches.as_deref(),
            omits.as_deref(),
        ),
        Assertion::XmlRoot {
            name,
            namespace,
            xsi_type,
        } => eval_xml_root(body, name, *namespace, xsi_type.as_deref()),
        Assertion::InstanceOf { rm_type, .. } => eval_instance_of(body, rm_type),
        Assertion::ResultSet {
            match_mode,
            rows,
            count,
            columns,
            cells,
        } => {
            let inline: Option<Vec<Value>> = match rows {
                Some(RowsSpec::Inline(rows)) => {
                    Some(rows.iter().map(|r| Value::Array(r.clone())).collect())
                }
                Some(RowsSpec::From(_)) | None => None,
            };
            return eval_result_set_against(
                body,
                ResolvedResultSet {
                    match_mode: *match_mode,
                    rows: inline.as_deref(),
                    count: *count,
                    columns: columns.as_deref(),
                    cells: cells.unwrap_or_default(),
                },
            )
            .map_err(AssertionOutcome::from);
        }
        // Every remaining family is Unrecorded or NotPerStep, both answered
        // above; the arm keeps the dispatch total without a panic.
        Assertion::Equivalent { .. }
        | Assertion::Signature { .. }
        | Assertion::Version { .. }
        | Assertion::Unique { .. }
        | Assertion::MessageExemplar { .. }
        | Assertion::State { .. } => return Err(unrecorded()),
    };
    judged.map(|()| Vec::new()).map_err(AssertionOutcome::from)
}

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

    /// Every assertion variant's judgement, pinned by name.
    ///
    /// Reclassifying a judged family as informative is how a whole catalogue
    /// chapter goes back to passing on an arm that evaluates nothing, so the
    /// classification is a test, not a convention.
    #[test]
    fn every_assertion_variant_declares_when_it_is_judged() {
        let cases: &[(Value, Judgement)] = &[
            (
                json!({ "assert": "field", "path": "uid/value", "exists": true }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "equivalent", "to": "committed" }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "returns", "equals": true }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "result_set", "match": "count", "count": 1 }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "xml_root", "name": "composition" }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "instance_of", "rm_type": "COMPOSITION" }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "signature", "of": "${v1}", "present": true }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "version", "count": 1 }),
                Judgement::PerStep,
            ),
            (
                json!({ "assert": "unique", "over": "${new_ehr_id}", "aggregate": true }),
                Judgement::Aggregate,
            ),
            (
                json!({ "assert": "message_exemplar", "text": "EHR not found" }),
                Judgement::Informative,
            ),
            (
                json!({ "assert": "state", "text": "the EHR exists" }),
                Judgement::Informative,
            ),
        ];
        for (document, expected) in cases {
            let assertion: Assertion = serde_json::from_value(document.clone())
                .unwrap_or_else(|e| panic!("{document} does not parse: {e}"));
            assert_eq!(
                judgement_of(&assertion),
                *expected,
                "{document} changed judgement"
            );
        }
    }

    /// Every assertion variant's replay classification, pinned by name.
    ///
    /// A family silently reclassified `FromExchange` would let a
    /// verification-pack entry reproduce a verdict over an assertion the replay
    /// never evaluated, so the classification is a test, not a convention.
    #[test]
    fn every_assertion_variant_declares_what_a_recorded_exchange_decides() {
        let cases: &[(Value, ReplayJudgement)] = &[
            (
                json!({ "assert": "field", "path": "uid/value", "exists": true }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "field", "path": "ehr_id/value", "equals": "fixed" }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "field", "path": "ehr_id/value", "equals": "${first_ehr_id}" }),
                ReplayJudgement::Unrecorded,
            ),
            (
                json!({ "assert": "equivalent", "to": "committed" }),
                ReplayJudgement::Unrecorded,
            ),
            (
                json!({ "assert": "returns", "equals": true }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "result_set", "match": "count", "count": 1 }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "result_set", "match": "ordered", "rows": [["a"]] }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "result_set", "match": "ordered",
                        "rows": { "from": "${ds:cnf.set.bp-10#magnitude_ge_140_by_uid}" } }),
                ReplayJudgement::Unrecorded,
            ),
            (
                json!({ "assert": "xml_root", "name": "composition" }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "instance_of", "rm_type": "COMPOSITION" }),
                ReplayJudgement::FromExchange,
            ),
            (
                json!({ "assert": "signature", "of": "${v1}", "present": true }),
                ReplayJudgement::Unrecorded,
            ),
            (
                json!({ "assert": "version", "count": 1 }),
                ReplayJudgement::Unrecorded,
            ),
            (
                json!({ "assert": "unique", "over": "${new_ehr_id}", "aggregate": true }),
                ReplayJudgement::NotPerStep,
            ),
            (
                json!({ "assert": "message_exemplar", "text": "EHR not found" }),
                ReplayJudgement::NotPerStep,
            ),
            (
                json!({ "assert": "state", "text": "the EHR exists" }),
                ReplayJudgement::NotPerStep,
            ),
        ];
        for (document, expected) in cases {
            let assertion: Assertion = serde_json::from_value(document.clone())
                .unwrap_or_else(|e| panic!("{document} does not parse: {e}"));
            assert_eq!(
                replay_judgement(&assertion),
                *expected,
                "{document} changed its replay classification"
            );
        }
    }

    /// The recorded-exchange dispatch judges what it classified judgeable and
    /// answers unjudgeable for the rest, never a pass. An unjudgeable outcome
    /// errors its row (law c), while a contradicted assertion fails it (law b).
    #[test]
    fn the_recorded_dispatch_judges_or_refuses_but_never_passes_silently() {
        let body = json!({ "_type": "EHR", "ehr_id": { "value": "e-1" } });
        let facts = ExchangeFacts {
            status: StatusCode::OK,
            body: &body,
        };
        let parse = |document: Value| -> Assertion {
            serde_json::from_value(document).expect("the assertion parses")
        };

        assert_eq!(
            eval_from_exchange(
                &parse(json!({ "assert": "instance_of", "rm_type": "EHR" })),
                facts
            ),
            Ok(Vec::new())
        );
        let mismatch = eval_from_exchange(
            &parse(json!({ "assert": "instance_of", "rm_type": "FOLDER" })),
            facts,
        )
        .expect_err("a body of another type contradicts the assertion");
        assert!(
            matches!(mismatch, AssertionOutcome::Mismatch(_)),
            "{mismatch:?}"
        );

        // A family whose ground the exchange does not carry is inconclusive,
        // and it never comes back as a pass.
        let unjudgeable = eval_from_exchange(
            &parse(json!({ "assert": "equivalent", "to": "committed" })),
            facts,
        )
        .expect_err("no committed payload is recorded");
        assert!(
            matches!(unjudgeable, AssertionOutcome::Unjudgeable(_)),
            "{unjudgeable:?}"
        );

        // Aggregate and informative families are not judged on a step at all.
        assert_eq!(
            eval_from_exchange(
                &parse(json!({ "assert": "state", "text": "the EHR exists" })),
                facts
            ),
            Ok(Vec::new())
        );
    }

    /// The wire-presence rule a Boolean `returns` is judged by (SM
    /// `openehr_platform` `I_EHR_DIRECTORY.has_directory`: Boolean, realized
    /// by ITS-REST as a GET whose 2xx IS the TRUE).
    #[test]
    fn a_boolean_returns_is_judged_by_wire_presence() {
        let body = Value::Null;
        assert!(eval_returns_wire(StatusCode::OK, &body, Some(&json!(true)), None, None).is_ok());
        assert!(
            eval_returns_wire(
                StatusCode::NOT_FOUND,
                &body,
                Some(&json!(false)),
                None,
                None
            )
            .is_ok()
        );
        assert!(
            eval_returns_wire(StatusCode::NOT_FOUND, &body, Some(&json!(true)), None, None)
                .is_err()
        );
        // A non-Boolean predicate compares the served body, not the status.
        assert!(
            eval_returns_wire(StatusCode::OK, &json!("v1.2"), None, Some("^v1\\."), None).is_ok()
        );
    }

    #[test]
    fn path_resolution_addresses_objects_and_lists() {
        let body = json!({
            "context": { "setting": { "value": "other care" } },
            "content": [ { "data": { "events": [ { "time": "t0" } ] } } ]
        });
        assert_eq!(
            resolve_path(&body, "context/setting/value").unwrap(),
            &json!("other care")
        );
        assert_eq!(
            resolve_path(&body, "content[0]/data/events[0]/time").unwrap(),
            &json!("t0")
        );
        assert!(resolve_path(&body, "content[1]").is_none());
    }

    #[test]
    fn recursive_ignore_segment_strips_every_depth() {
        // A FOLDER tree (RM common `folder.adoc`: `folders: List<FOLDER>`),
        // with a uid on the root and on each nested node.
        let tree = json!({
            "_type": "FOLDER",
            "uid": { "_type": "OBJECT_VERSION_ID", "value": "r::s::1" },
            "folders": [
                {
                    "_type": "FOLDER",
                    "uid": { "_type": "HIER_OBJECT_ID", "value": "a" },
                    "name": { "value": "emergency" },
                    "folders": [
                        { "_type": "FOLDER", "uid": { "value": "b" }, "name": { "value": "episode" } }
                    ]
                }
            ]
        });
        // A depth-anchored path reaches only the root.
        let shallow = strip_ignored(&tree, &["uid".to_owned()]);
        assert!(shallow.get("uid").is_none());
        assert!(shallow["folders"][0].get("uid").is_some());
        // `**/uid` reaches the root and every nested node.
        let deep = strip_ignored(&tree, &["**/uid".to_owned()]);
        assert!(deep.get("uid").is_none());
        assert!(deep["folders"][0].get("uid").is_none());
        assert!(deep["folders"][0]["folders"][0].get("uid").is_none());
        // Nothing else is touched.
        assert_eq!(deep["folders"][0]["name"]["value"], json!("emergency"));
        assert_eq!(
            deep["folders"][0]["folders"][0]["name"]["value"],
            json!("episode")
        );
    }

    #[test]
    fn field_predicates() {
        let body =
            json!({ "is_queryable": true, "audit": { "time_committed": "2026-07-21T10:00:00Z" } });
        assert!(
            eval_field(
                &body,
                "is_queryable",
                Some(&json!(true)),
                None,
                None,
                None,
                None,
                None
            )
            .is_ok()
        );
        assert!(
            eval_field(
                &body,
                "is_queryable",
                None,
                None,
                Some(true),
                None,
                None,
                None
            )
            .is_ok()
        );
        assert!(eval_field(&body, "subject", None, None, None, Some(true), None, None).is_ok());
        // the server-set predicate: stored time must differ from the client value
        assert!(
            eval_field(
                &body,
                "audit/time_committed",
                None,
                Some(&json!("1990-01-01T00:00:00Z")),
                None,
                None,
                None,
                None
            )
            .is_ok()
        );
        assert!(
            eval_field(
                &body,
                "audit/time_committed",
                None,
                Some(&json!("2026-07-21T10:00:00Z")),
                None,
                None,
                None,
                None
            )
            .is_err()
        );
    }

    #[test]
    fn equivalence_strips_normative_ignore_sets_only() {
        let committed = json!({ "name": { "value": "v1" }, "content": [{"x": 1}] });
        let served = json!({
            "uid": { "value": "generated::sut::1" },
            "name": { "value": "v1" },
            "content": [{"x": 1}]
        });
        assert!(equivalent(&served, &committed, &["uid".to_owned()]));
        assert!(!equivalent(&served, &committed, &[])); // nothing stripped -> uid differs
    }

    #[test]
    fn xml_root_judges_the_published_element_and_its_namespace() {
        use crate::vocab::XmlNamespace;

        let v1 = Value::String(
            r#"<?xml version="1.0" encoding="UTF-8"?>
               <composition xmlns="http://schemas.openehr.org/v1"><name/></composition>"#
                .to_owned(),
        );
        assert!(eval_xml_root(&v1, "composition", Some(XmlNamespace::Published), None).is_ok());
        assert!(eval_xml_root(&v1, "composition", Some(XmlNamespace::V1), None).is_ok());
        assert!(eval_xml_root(&v1, "composition", Some(XmlNamespace::V2), None).is_err());

        // A prefix binding is equally conforming — only the URI is asserted.
        let prefixed = Value::String(
            r#"<oe:composition xmlns:oe="http://schemas.openehr.org/v2"/>"#.to_owned(),
        );
        assert!(
            eval_xml_root(
                &prefixed,
                "composition",
                Some(XmlNamespace::Published),
                None
            )
            .is_ok()
        );

        // The defect this assertion exists for: a root in NO namespace, against
        // schemas that are elementFormDefault="qualified" over a targetNamespace.
        let unqualified = Value::String(r#"<composition archetype_node_id="x"/>"#.to_owned());
        let failure = eval_xml_root(
            &unqualified,
            "composition",
            Some(XmlNamespace::Published),
            None,
        )
        .expect_err("an unqualified root must fail");
        assert!(failure.0.contains("NO namespace"), "{failure:?}");
        // …and the name-only row still passes it, which is why the namespace
        // fact needs its own assertion rather than a regex over the body.
        assert!(eval_xml_root(&unqualified, "composition", None, None).is_ok());

        let wrong_name =
            Value::String(r#"<folder xmlns="http://schemas.openehr.org/v1"/>"#.to_owned());
        assert!(eval_xml_root(&wrong_name, "composition", None, None).is_err());

        // A JSON body is not an XML document entity.
        assert!(
            eval_xml_root(
                &json!({ "_type": "COMPOSITION" }),
                "composition",
                None,
                None
            )
            .is_err()
        );
        assert!(eval_xml_root(&Value::Null, "composition", None, None).is_err());
        // Malformed XML fails loudly rather than silently passing.
        let malformed = Value::String("<composition>".to_owned());
        assert!(eval_xml_root(&malformed, "composition", None, None).is_err());
    }

    /// `ALL/Version.xsd` publishes `<xs:element name="version" type="VERSION"/>`
    /// over `<xs:complexType name="VERSION" abstract="true">`, and XML Schema
    /// Part 1 §2.6.1 + §3.4.6 (<https://www.w3.org/TR/xmlschema-1/#xsi_type>)
    /// forbid an instance from using an abstract type directly. On that root the
    /// concrete class is a judged fact, and it is what tells an
    /// `ORIGINAL_VERSION` response apart from an `IMPORTED_VERSION` one.
    #[test]
    fn xml_root_judges_the_concrete_type_of_an_abstract_root() {
        use crate::vocab::XmlNamespace;

        let original = Value::String(
            r#"<version xmlns="http://schemas.openehr.org/v1"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xsi:type="ORIGINAL_VERSION"><uid/></version>"#
                .to_owned(),
        );
        assert!(
            eval_xml_root(
                &original,
                "version",
                Some(XmlNamespace::Published),
                Some("ORIGINAL_VERSION")
            )
            .is_ok()
        );
        // The discrimination the attribute exists for.
        let failure = eval_xml_root(
            &original,
            "version",
            Some(XmlNamespace::Published),
            Some("IMPORTED_VERSION"),
        )
        .expect_err("a different concrete type must fail");
        assert!(failure.0.contains("ORIGINAL_VERSION"), "{failure:?}");

        // The prefix is the document's own choice, on the attribute NAME and
        // inside the QName VALUE alike; both resolve, neither is matched.
        let prefixed = Value::String(
            r#"<oe:version xmlns:oe="http://schemas.openehr.org/v1"
                           xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
                           i:type="oe:IMPORTED_VERSION"/>"#
                .to_owned(),
        );
        assert!(
            eval_xml_root(
                &prefixed,
                "version",
                Some(XmlNamespace::Published),
                Some("IMPORTED_VERSION")
            )
            .is_ok()
        );

        // An abstract root with no xsi:type at all is invalid against the
        // published schema, and says so.
        let bare = Value::String(r#"<version xmlns="http://schemas.openehr.org/v1"/>"#.to_owned());
        let failure = eval_xml_root(
            &bare,
            "version",
            Some(XmlNamespace::Published),
            Some("ORIGINAL_VERSION"),
        )
        .expect_err("an abstract root must name its concrete type");
        assert!(failure.0.contains("no xsi:type"), "{failure:?}");
        // …and a row that does not assert the type still passes it, which is
        // why the concrete class needs its own field.
        assert!(eval_xml_root(&bare, "version", Some(XmlNamespace::Published), None).is_ok());

        // A type QName from a foreign namespace names another schema's type.
        let foreign = Value::String(
            r#"<version xmlns="http://schemas.openehr.org/v1"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xmlns:x="http://example.org/other"
                        xsi:type="x:ORIGINAL_VERSION"/>"#
                .to_owned(),
        );
        let failure = eval_xml_root(
            &foreign,
            "version",
            Some(XmlNamespace::Published),
            Some("ORIGINAL_VERSION"),
        )
        .expect_err("a foreign type namespace must fail");
        assert!(failure.0.contains("example.org"), "{failure:?}");

        // An unbound prefix on the QName is a defect, not a silent local name.
        let unbound = Value::String(
            r#"<version xmlns="http://schemas.openehr.org/v1"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xsi:type="nope:ORIGINAL_VERSION"/>"#
                .to_owned(),
        );
        assert!(
            eval_xml_root(
                &unbound,
                "version",
                Some(XmlNamespace::Published),
                Some("ORIGINAL_VERSION")
            )
            .is_err()
        );
    }

    #[test]
    fn unique_is_aggregate_across_rows() {
        let name = crate::ids::CaptureName::parse("new_ehr_id").unwrap();
        let mut a = VarStore::default();
        a.set(name.clone(), Captured::Scalar("id-1".into()));
        let mut b = VarStore::default();
        b.set(name.clone(), Captured::Scalar("id-2".into()));
        assert!(eval_unique(&name, &[a.clone(), b]).is_ok());
        let mut c = VarStore::default();
        c.set(name.clone(), Captured::Scalar("id-1".into()));
        assert!(eval_unique(&name, &[a, c]).is_err());
    }

    /// A FLAT body is "key-value pairs at a single level in JSON where …
    /// keys are full WT paths" and "context fields MUST use `ctx/` prefix"
    /// (ITS-REST `docs/simplified_formats/master04-basic_concepts.adoc`
    /// §Format variants → Flat format), which is exactly the shape this
    /// predicate reads: path-formed keys, no nested object under any of them.
    #[test]
    fn a_flat_body_is_recognized_by_its_single_level_of_path_keys() {
        let flat = json!({
            "ctx/language": "en",
            "vital_signs/body_temperature:0/any_event:0/temperature|magnitude": 37.5,
            "vital_signs/body_temperature:0/any_event:0/temperature|unit": "°C"
        });
        assert!(is_flat_map(&flat));
        // A canonical body nests, and carries no path-formed key.
        assert!(!is_flat_map(&json!({
            "_type": "COMPOSITION",
            "name": { "value": "Vital signs" }
        })));
        // One path-formed key is not enough if a value still nests.
        assert!(!is_flat_map(&json!({
            "vital_signs/x|magnitude": 1,
            "nested": { "a": 1 }
        })));
        assert!(!is_flat_map(&json!({})), "an empty object is not a body");
        assert!(!is_flat_map(&json!([])), "an array is not a FLAT map");
    }

    /// The STRUCTURED→FLAT algorithm: "build path by concatenating property
    /// names with forward slash", "for properties with a pipe prefix, append
    /// to a parent path with pipe", "unwrap arrays" and "preserve instance
    /// indices" (ITS-REST
    /// `docs/simplified_formats/master04-basic_concepts.adoc` §Conversion
    /// Between Formats → Structured to Flat). The empty-string key is the
    /// element's own main value, so it flattens onto the parent path itself.
    #[test]
    fn a_structured_body_flattens_onto_its_flat_key_form() {
        let structured = json!({
            "vital_signs": [ {
                "body_temperature": [ {
                    "any_event": [ {
                        "temperature": [ { "|magnitude": 37.5, "|unit": "°C" } ],
                        "time": [ { "": "2026-07-21T10:00:00Z" } ]
                    } ]
                } ]
            } ]
        });
        let mut flat = BTreeMap::new();
        flatten_structured(&structured, "", &mut flat);
        let keys: Vec<&str> = flat.keys().map(String::as_str).collect();
        assert_eq!(
            keys,
            vec![
                "vital_signs:0/body_temperature:0/any_event:0/temperature:0|magnitude",
                "vital_signs:0/body_temperature:0/any_event:0/temperature:0|unit",
                "vital_signs:0/body_temperature:0/any_event:0/time:0",
            ]
        );
        assert_eq!(
            flat.get("vital_signs:0/body_temperature:0/any_event:0/temperature:0|magnitude"),
            Some(&json!(37.5))
        );
    }

    /// The attribute-key shape is what tells a simplified body from a
    /// canonical one: `|`-prefixed and empty-string keys are STRUCTURED
    /// spellings (master04 §Format variants), and canonical JSON carries
    /// neither — it carries `_type`.
    #[test]
    fn a_canonical_body_is_never_read_as_a_simplified_one() {
        let canonical = json!({
            "_type": "COMPOSITION",
            "name": { "_type": "DV_TEXT", "value": "Vital signs" }
        });
        assert!(!has_simplified_leaf_keys(&canonical));
        assert!(
            simplified_as_flat(&canonical).is_none(),
            "a canonical body has no FLAT reading"
        );
        // A STRUCTURED body does, and it comes back flattened.
        let structured = json!({ "vital_signs": [ { "temperature": [ { "|magnitude": 1 } ] } ] });
        assert!(has_simplified_leaf_keys(&structured));
        let flat = simplified_as_flat(&structured).expect("a STRUCTURED body reads as FLAT");
        assert_eq!(
            flat.keys().map(String::as_str).collect::<Vec<_>>(),
            vec!["vital_signs:0/temperature:0|magnitude"]
        );
        // A FLAT body reads as itself, verbatim.
        let already_flat = json!({ "ctx/language": "en", "vitals/temp|magnitude": 37.5 });
        assert_eq!(
            simplified_as_flat(&already_flat).map(|m| m.len()),
            Some(2),
            "a FLAT body is its own key map"
        );
        assert!(simplified_as_flat(&json!("text")).is_none());
    }

    /// The committed side's `ctx/*` input keys name the same data the
    /// read-back expresses at RM paths: `ctx/participation_<field>:<i>` and
    /// `ctx/health_care_facility|<attr>` (ITS-REST
    /// `docs/simplified_formats/master06-context_information.adoc`
    /// §Participation, §`health_care_facility`), with `ctx/id_namespace` and
    /// `ctx/id_scheme` as the declared defaults for external references
    /// (§ID Namespace and Scheme) rather than data of their own.
    #[test]
    fn the_ctx_input_keys_fold_onto_the_paths_a_read_back_uses() {
        let committed: BTreeMap<String, Value> = [
            ("ctx/participation_name:1".to_owned(), json!("Lara Markham")),
            ("ctx/participation_id:1".to_owned(), json!("198")),
            ("ctx/participation_function".to_owned(), json!("performer")),
            ("ctx/health_care_facility|id".to_owned(), json!("9091")),
            ("ctx/id_namespace".to_owned(), json!("HOSPITAL-NS")),
            ("ctx/id_scheme".to_owned(), json!("HOSPITAL-NS")),
            ("ctx/language".to_owned(), json!("en")),
            ("vitals/temperature|magnitude".to_owned(), json!(37.5)),
        ]
        .into_iter()
        .collect();

        let folded = fold_flat_ctx(&committed, "vitals");
        assert_eq!(
            folded.get("vitals/context/_participation:1|name"),
            Some(&json!("Lara Markham"))
        );
        assert_eq!(
            folded.get("vitals/context/_participation:0|function"),
            Some(&json!("performer")),
            "an index-free participation key is the first participation"
        );
        assert_eq!(
            folded.get("vitals/context/_health_care_facility|id"),
            Some(&json!("9091"))
        );
        // The declared defaults expand onto every folded party carrying an id,
        // and never survive as keys of their own.
        assert_eq!(
            folded.get("vitals/context/_participation:1|id_namespace"),
            Some(&json!("HOSPITAL-NS"))
        );
        assert_eq!(
            folded.get("vitals/context/_health_care_facility|id_scheme"),
            Some(&json!("HOSPITAL-NS"))
        );
        assert!(!folded.contains_key("ctx/id_namespace"));
        assert!(!folded.contains_key("ctx/id_scheme"));
        // Everything else passes through untouched, ctx defaults included:
        // the ignore pass is what excuses them.
        assert_eq!(folded.get("ctx/language"), Some(&json!("en")));
        assert_eq!(
            folded.get("vitals/temperature|magnitude"),
            Some(&json!(37.5))
        );
    }

    /// The ignore pass reads a FLAT key at the RM path it names: the
    /// `ctx/*` default-setter spellings map onto their master06 targets
    /// (`ctx/time` → `context/start_time`, `ctx/setting` → `context/setting`,
    /// `ctx/composer_*` → `composer`), and any other key matches when its
    /// post-root path falls under the ignored path.
    #[test]
    fn a_flat_key_is_ignored_at_the_rm_path_it_names() {
        let ignored = [
            "context/start_time".to_owned(),
            "context/setting".to_owned(),
            "composer".to_owned(),
            "uid".to_owned(),
        ];
        assert!(flat_key_ignored("ctx/time", &ignored));
        assert!(flat_key_ignored("ctx/setting", &ignored));
        assert!(flat_key_ignored("ctx/composer_name", &ignored));
        assert!(flat_key_ignored("ctx/composer_id", &ignored));
        // The post-root path is what is compared, so the root segment of a
        // read-back key never has to be enumerated.
        assert!(flat_key_ignored("vitals/context/start_time", &ignored));
        assert!(flat_key_ignored("vitals/uid|value", &ignored));
        // The flat `_uid` spelling of the same RM attribute is the same datum.
        assert!(flat_key_ignored("vitals/_uid", &ignored));
        // A datum nobody ignored stays compared.
        assert!(!flat_key_ignored("vitals/temperature|magnitude", &ignored));
        assert!(!flat_key_ignored("ctx/end_time", &ignored));
        assert!(flat_key_ignored(
            "ctx/end_time",
            &["context/end_time".to_owned()]
        ));
    }

    /// Keys are compared in one canonical spelling, so a first-element index
    /// written out and one left off name the same datum.
    #[test]
    fn the_first_element_index_is_elided_before_keys_are_compared() {
        assert_eq!(
            dezero("vitals:0/temperature:0|magnitude"),
            "vitals/temperature|magnitude"
        );
        assert_eq!(dezero("vitals/events:0"), "vitals/events");
        assert_eq!(
            dezero("vitals:1/temperature:2|magnitude"),
            "vitals:1/temperature:2|magnitude",
            "only the FIRST element's index is elidable"
        );
        assert_eq!(
            dezero("vitals/temperature|magnitude"),
            "vitals/temperature|magnitude"
        );
    }

    /// The FLAT round-trip rule: every committed datum must come back with an
    /// equal value, read-back surplus is tolerated (the export is the full RM
    /// projection of the committed data, master04 §Format variants), and an
    /// ignored path is compared on neither side.
    #[test]
    fn a_flat_round_trip_loses_no_committed_datum_and_tolerates_surplus() {
        let committed = json!({
            "ctx/language": "en",
            "ctx/time": "2026-07-21T10:00:00Z",
            "vitals/temperature|magnitude": 37.5,
            "vitals/temperature|unit": "°C"
        });
        let read_back = json!({
            "vitals/temperature:0|magnitude": 37.5,
            "vitals/temperature:0|unit": "°C",
            "vitals/context/start_time": "2026-07-21T10:00:04Z",
            "vitals/category|code_string": "433",
            "vitals/_uid": "8849182c-82ad-4088-a07f-48ead4180515::sut::1",
            "ctx/language": "en"
        });
        let ignored = ["context/start_time".to_owned(), "uid".to_owned()];
        assert!(
            equivalent(&read_back, &committed, &ignored),
            "the read-back carries every committed datum"
        );

        // A changed datum is a failure, surplus or not.
        let altered = json!({
            "vitals/temperature:0|magnitude": 38.5,
            "vitals/temperature:0|unit": "°C",
            "ctx/language": "en"
        });
        assert!(!equivalent(&altered, &committed, &ignored));

        // A dropped datum is a failure too.
        let lossy = json!({
            "vitals/temperature:0|magnitude": 37.5,
            "ctx/language": "en"
        });
        assert!(!equivalent(&lossy, &committed, &ignored));

        // Without the ignore set the server-set start_time is compared, and
        // the committed `ctx/time` no longer matches it.
        assert!(!equivalent(&read_back, &committed, &[]));
    }

    /// ITS-REST overview `Resources.md` §JSON Format makes the `_type`
    /// self-tag CONDITIONAL while the requirement governs its VALUE, so a
    /// fully self-tagging codec and a sparsely tagged committed twin describe
    /// the same RM content — but two DIFFERENT tags are a real polymorphic
    /// substitution and stay detectable.
    #[test]
    fn a_type_self_tag_present_on_one_side_only_is_not_a_content_difference() {
        let served = json!({
            "_type": "COMPOSITION",
            "name": { "_type": "DV_TEXT", "value": "Vital signs" }
        });
        let committed = json!({ "name": { "value": "Vital signs" } });
        assert!(equivalent(&served, &committed, &[]));

        let substituted = json!({
            "_type": "COMPOSITION",
            "name": { "_type": "DV_CODED_TEXT", "value": "Vital signs" }
        });
        let tagged_committed = json!({
            "name": { "_type": "DV_TEXT", "value": "Vital signs" }
        });
        assert!(
            !equivalent(&substituted, &tagged_committed, &[]),
            "two different concrete types are not the same content"
        );
        // Array length is content, never padding.
        assert!(!equivalent(
            &json!({ "content": [1, 2] }),
            &json!({ "content": [1] }),
            &[]
        ));
    }

    /// The named ignore-sets come from the two artifacts that define them —
    /// the binding's `server_assigned` list and the selectors vocabulary's
    /// `ctx_defaults` — and an explicit path passes through as written.
    #[test]
    fn named_ignore_sets_expand_from_their_own_artifacts() {
        use crate::model::assertion::IgnoreSpec;

        let specs = vec![
            IgnoreSpec::Named(IgnoreSetName::ServerAssigned),
            IgnoreSpec::Named(IgnoreSetName::CtxDefaults),
            IgnoreSpec::Path("content[0]/uid".to_owned()),
        ];
        let resolved = resolve_ignore_sets(
            &specs,
            &["uid".to_owned(), "**/uid".to_owned()],
            &["context/start_time".to_owned()],
        );
        assert_eq!(
            resolved,
            vec![
                "uid".to_owned(),
                "**/uid".to_owned(),
                "context/start_time".to_owned(),
                "content[0]/uid".to_owned(),
            ],
            "the sets expand in the order the row declares them"
        );
        assert!(
            resolve_ignore_sets(&[], &["uid".to_owned()], &[]).is_empty(),
            "a row that ignores nothing strips nothing"
        );
    }

    /// The `returns` predicates over a scalar-shaped body: an equal value, a
    /// pattern that must match, and a pattern that must NOT appear.
    #[test]
    fn returns_predicates_judge_the_whole_body() {
        assert!(eval_returns(&json!(3), Some(&json!(3)), None, None).is_ok());
        let failure = eval_returns(&json!(3), Some(&json!(4)), None, None).expect_err("3 is not 4");
        assert!(failure.0.contains("!= expected"), "{failure:?}");

        assert!(eval_returns(&json!("v1.2.3"), None, Some(r"^v\d+\.\d+"), None).is_ok());
        assert!(eval_returns(&json!("draft"), None, Some(r"^v\d+"), None).is_err());

        // `omits` is the negative direction: the body must not carry it.
        assert!(eval_returns(&json!("public data"), None, None, Some("secret")).is_ok());
        let leaked = eval_returns(&json!("carries a secret"), None, None, Some("secret"))
            .expect_err("a body that must omit the pattern carries it");
        assert!(leaked.0.contains("must omit"), "{leaked:?}");

        // A pattern that does not compile is reported as such, never as a
        // silently passing row.
        let broken = eval_returns(&json!("x"), None, Some("("), None)
            .expect_err("an uncompilable pattern is a failure");
        assert!(broken.0.contains("does not compile"), "{broken:?}");
        let broken = eval_returns(&json!("x"), None, None, Some("("))
            .expect_err("an uncompilable omits pattern is a failure");
        assert!(broken.0.contains("does not compile"), "{broken:?}");
    }

    /// The `field` predicates that the existing battery leaves open: a
    /// pattern over a resolved leaf, a path that resolves to nothing, and an
    /// `absent` expectation the body contradicts.
    #[test]
    fn field_predicates_report_the_predicate_they_violated() {
        let body = json!({
            "system_id": "sut.example.org",
            "versions": [ { "uid": { "value": "a::b::1" } } ]
        });
        assert!(
            eval_field(
                &body,
                "system_id",
                None,
                None,
                None,
                None,
                Some(r"\.org$"),
                None
            )
            .is_ok()
        );
        let failure = eval_field(
            &body,
            "system_id",
            None,
            None,
            None,
            None,
            Some(r"^\d+$"),
            None,
        )
        .expect_err("an identifier is not digits");
        assert!(failure.0.contains("does not match"), "{failure:?}");

        let failure = eval_field(
            &body,
            "missing/leaf",
            Some(&json!(1)),
            None,
            None,
            None,
            None,
            None,
        )
        .expect_err("an unresolvable path cannot be compared");
        assert!(failure.0.contains("resolves to nothing"), "{failure:?}");

        let failure = eval_field(&body, "system_id", None, None, None, Some(true), None, None)
            .expect_err("a present attribute is not absent");
        assert!(failure.0.contains("expected absent"), "{failure:?}");

        let failure = eval_field(&body, "audit", None, None, Some(true), None, None, None)
            .expect_err("an absent attribute is not present");
        assert!(failure.0.contains("expected present"), "{failure:?}");

        // An uncompilable pattern is a failure, not a pass.
        assert!(eval_field(&body, "system_id", None, None, None, None, Some("("), None).is_err());
        // A row with no predicate at all asserts only that the path resolves.
        assert!(
            eval_field(
                &body,
                "versions[0]/uid/value",
                None,
                None,
                None,
                None,
                None,
                None
            )
            .is_ok()
        );
    }

    /// The optional-member predicate stays silent on an absent member and
    /// judges a present one, which is what an OPTIONAL member carrying a
    /// declared shape needs (ITS-REST `docs/query/Response.md` §Metadata).
    #[test]
    fn absent_or_matches_passes_on_absence_and_judges_on_presence() {
        let body = json!({ "meta": { "_created": "2026-07-21T10:00:00Z" } });
        // Absent: nothing to judge, so the row passes.
        assert!(
            eval_field(
                &body,
                "meta/_generator",
                None,
                None,
                None,
                None,
                None,
                Some("^x")
            )
            .is_ok()
        );
        assert!(
            eval_field(
                &body,
                "meta/_created",
                None,
                None,
                None,
                None,
                None,
                Some(r"^\d{4}-\d{2}-\d{2}T")
            )
            .is_ok()
        );
        let failure = eval_field(
            &body,
            "meta/_created",
            None,
            None,
            None,
            None,
            None,
            Some(r"^\d+$"),
        )
        .expect_err("an extended ISO 8601 date-time is not a run of digits");
        assert!(failure.0.contains("does not match"), "{failure:?}");
    }

    /// A malformed index step addresses nothing rather than panicking or
    /// silently dropping the step: an assertion over a mis-authored path
    /// reports "resolves to nothing" instead of passing over the whole body.
    #[test]
    fn a_malformed_index_step_resolves_to_nothing() {
        let body = json!({ "versions": [{ "uid": "a" }, { "uid": "b" }] });
        assert_eq!(
            resolve_path(&body, "versions[1]/uid"),
            Some(&json!("b")),
            "the well-formed index addresses its element"
        );
        // A non-numeric index, an unterminated one, and an index past the end.
        for path in ["versions[x]/uid", "versions[0/uid", "versions[9]/uid"] {
            assert_eq!(resolve_path(&body, path), None, "{path}");
        }
        // A bare index step with no attribute indexes the CURRENT value.
        assert_eq!(resolve_path(&body, "versions/[0]/uid"), Some(&json!("a")));
        // A leading and a doubled separator are empty steps, which are skipped.
        assert_eq!(resolve_path(&body, "//versions[0]//uid"), Some(&json!("a")));
    }

    /// A template the driver was supposed to pre-resolve is a LOUD failure:
    /// only captures render here, so a `${row.…}` or an unbound or non-scalar
    /// capture never becomes an empty segment in a compared value.
    #[test]
    fn only_scalar_captures_render_and_everything_else_is_refused() {
        use crate::refgrammar::Template;

        let mut vars = VarStore::default();
        vars.set(
            crate::ids::CaptureName::parse("ehr_id").unwrap(),
            Captured::Scalar("e-1".to_owned()),
        );
        vars.set(
            crate::ids::CaptureName::parse("uids").unwrap(),
            Captured::List(vec!["a".to_owned()]),
        );

        let bound = Template::parse("/ehr/${ehr_id}").unwrap();
        assert_eq!(render_template(&bound, &vars).unwrap(), "/ehr/e-1");

        let non_scalar = Template::parse("${uids}").unwrap();
        assert_eq!(
            render_template(&non_scalar, &vars),
            Err("capture uids is not scalar".to_owned())
        );

        let unbound = Template::parse("${ghost}").unwrap();
        assert_eq!(
            render_template(&unbound, &vars),
            Err("capture ghost is not bound".to_owned())
        );

        let driver_side = Template::parse("${row.ehr_id}").unwrap();
        let failure = render_template(&driver_side, &vars)
            .expect_err("a row reference is the driver's to resolve");
        assert!(
            failure.contains("must be resolved by the driver"),
            "{failure}"
        );
    }

    /// An ignore path descends through objects and lists, and an empty path
    /// strips nothing — an ignore set can never quietly blank a whole body.
    #[test]
    fn an_ignore_path_descends_and_an_empty_one_strips_nothing() {
        let body = json!({
            "context": { "start_time": "t", "setting": "s" },
            "versions": [
                { "uid": "a", "commit_audit": { "time_committed": "t1" } },
                { "uid": "b", "commit_audit": { "time_committed": "t2" } }
            ]
        });

        let nested = strip_ignored(&body, &["context/start_time".to_owned()]);
        assert_eq!(nested["context"], json!({ "setting": "s" }));
        assert_eq!(nested["versions"], body["versions"], "untouched elsewhere");

        // Through a list: every element loses the named leaf.
        let through_list =
            strip_ignored(&body, &["versions/commit_audit/time_committed".to_owned()]);
        for version in through_list["versions"].as_array().unwrap() {
            assert_eq!(version["commit_audit"], json!({}));
            assert!(version["uid"].is_string(), "siblings survive");
        }

        // An empty path names nothing, so the body comes back whole.
        assert_eq!(strip_ignored(&body, &[String::new()]), body);
        assert_eq!(strip_ignored(&body, &["/".to_owned()]), body);
        // A path through a scalar leaf strips nothing rather than failing.
        assert_eq!(
            strip_ignored(&body, &["context/setting/deeper".to_owned()]),
            body
        );
    }

    /// A non-string leaf is compared as its JSON text, so a numeric or object
    /// value still faces a `matches:` predicate rather than passing untested.
    #[test]
    fn a_non_string_leaf_is_matched_as_its_json_text() {
        let body = json!({ "magnitude": 140, "uid": { "value": "a::b::1" } });
        assert!(
            eval_field(
                &body,
                "magnitude",
                None,
                None,
                None,
                None,
                Some(r"^\d+$"),
                None
            )
            .is_ok()
        );
        let failure = eval_field(&body, "magnitude", None, None, None, None, Some("^x"), None)
            .expect_err("140 does not start with x");
        assert!(failure.0.contains("\"140\""), "{failure:?}");
        assert!(eval_field(&body, "uid", None, None, None, None, Some("a::b::1"), None).is_ok());

        // `not_equals` is the server-set predicate: equal to the client's own
        // value is the failure, anything else passes.
        assert!(
            eval_field(
                &body,
                "magnitude",
                None,
                Some(&json!(1)),
                None,
                None,
                None,
                None
            )
            .is_ok()
        );
        let failure = eval_field(
            &body,
            "magnitude",
            None,
            Some(&json!(140)),
            None,
            None,
            None,
            None,
        )
        .expect_err("the value is the client-supplied one");
        assert!(failure.0.contains("must be server-set"), "{failure:?}");
    }

    /// The aggregate `unique` assertion (law e) ignores rows that never bound
    /// the capture: a row excused before it committed anything must not count
    /// as a duplicate of another excused row.
    #[test]
    fn unique_ignores_rows_that_bound_nothing() {
        let name = crate::ids::CaptureName::parse("ehr_id").unwrap();
        let mut bound = VarStore::default();
        bound.set(name.clone(), Captured::Scalar("e-1".to_owned()));
        let mut same = VarStore::default();
        same.set(name.clone(), Captured::Scalar("e-1".to_owned()));

        assert!(
            eval_unique(&name, &[VarStore::default(), VarStore::default()]).is_ok(),
            "two rows that bound nothing are not two duplicates"
        );
        assert!(eval_unique(&name, &[bound.clone(), VarStore::default()]).is_ok());
        let failure = eval_unique(&name, &[bound, VarStore::default(), same])
            .expect_err("the same id at two rows is a duplicate");
        assert!(failure.0.contains("repeats at row 2"), "{failure:?}");
    }

    /// A `returns` predicate reads a non-string body as its JSON text, so a
    /// numeric or object response is judged rather than passing untested.
    #[test]
    fn returns_predicates_read_a_non_string_body_as_its_json() {
        let count = json!(7);
        assert!(eval_returns(&count, None, Some(r"^\d$"), None).is_ok());
        let failure =
            eval_returns(&count, None, Some("^x"), None).expect_err("7 does not start with x");
        assert!(failure.0.contains("does not match"), "{failure:?}");
        assert!(eval_returns(&count, None, None, Some("nowhere")).is_ok());
        assert!(eval_returns(&count, None, None, Some("7")).is_err());

        // An uncompilable pattern is a failure on both predicate channels.
        assert!(eval_returns(&count, None, Some("("), None).is_err());
    }

    /// A namespace-qualified `xsi:type` `QName` is judged against the SAME
    /// expectation as the root, so a type from another schema's target
    /// namespace is refused even when its local name matches.
    #[test]
    fn an_xsi_type_in_the_wrong_namespace_is_refused() {
        use crate::vocab::XmlNamespace;

        // The root binds the published namespace with a PREFIX and leaves no
        // default, so the unprefixed xsi:type QName resolves to NO namespace.
        let unqualified_type = Value::String(
            r#"<oe:version xmlns:oe="http://schemas.openehr.org/v1"
                           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                           xsi:type="ORIGINAL_VERSION"/>"#
                .to_owned(),
        );
        let failure = eval_xml_root(
            &unqualified_type,
            "version",
            Some(XmlNamespace::Published),
            Some("ORIGINAL_VERSION"),
        )
        .expect_err("the type QName resolves to no namespace");
        assert!(
            failure.0.contains("resolves to NO namespace"),
            "{failure:?}"
        );
        // The same document passes when only the root's namespace is asserted.
        assert!(
            eval_xml_root(
                &unqualified_type,
                "version",
                Some(XmlNamespace::Published),
                None
            )
            .is_ok()
        );

        // A type QName bound to another namespace names another schema's type.
        let foreign_type = Value::String(
            r#"<version xmlns="http://schemas.openehr.org/v1"
                        xmlns:other="http://example.invalid/other"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xsi:type="other:ORIGINAL_VERSION"/>"#
                .to_owned(),
        );
        let failure = eval_xml_root(
            &foreign_type,
            "version",
            Some(XmlNamespace::Published),
            Some("ORIGINAL_VERSION"),
        )
        .expect_err("the type is another schema's");
        assert!(failure.0.contains("is in namespace"), "{failure:?}");

        // A prefix the document never bound is refused on both QNames.
        let unbound_type_prefix = Value::String(
            r#"<version xmlns="http://schemas.openehr.org/v1"
                        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                        xsi:type="zz:ORIGINAL_VERSION"/>"#
                .to_owned(),
        );
        let failure = eval_xml_root(&unbound_type_prefix, "version", None, Some("x"))
            .expect_err("the xsi:type prefix is unbound");
        assert!(
            failure.0.contains("is not bound to any namespace"),
            "{failure:?}"
        );

        let unbound_root_prefix = Value::String("<zz:version/>".to_owned());
        let failure = eval_xml_root(&unbound_root_prefix, "version", None, None)
            .expect_err("the root's prefix is unbound");
        assert!(
            failure.0.contains("is not bound to any namespace"),
            "{failure:?}"
        );
    }
}