openehr 0.2.0

openEHR Reference Model types, validation, paths, AQL parsing, and change-control security primitives
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
//! Reference Model invariant checking.
//!
//! # Why this exists when the constructors already check
//!
//! Every builder in this crate enforces the invariants of the class it builds.
//! **Deserialization does not.** `serde` writes fields directly, so a
//! `COMPOSITION` read from JSON has never passed through `Composition::new`,
//! and an `ELEMENT` read from JSON can carry a `value` *and* a `null_flavour`
//! — a combination no constructor here will produce and every openEHR
//! implementation must be prepared to receive.
//!
//! So there are two gates, and they are not redundant:
//!
//! | Gate | Covers | Enforced by |
//! | --- | --- | --- |
//! | construction | data this program builds | `Result`-returning builders |
//! | validation | data this program **receives** | this module |
//!
//! A service that deserializes a composition and stores it without calling
//! [`Validate::validate`] has no invariant checking at all, whatever its
//! constructors do.
//!
//! # What it reports, and what it cannot
//!
//! Validation here is **RM-level**: the invariants stated in the openEHR class
//! definitions. It is not archetype validation. Checking that
//! `openEHR-EHR-OBSERVATION.blood_pressure.v2` permits exactly these elements
//! at these node ids requires the archetype, and archetypes are out of scope
//! (`S1.4`). A composition that passes here can still violate its archetype,
//! and the documentation says so rather than letting "valid" be read as more
//! than it is.
//!
//! ```
//! use openehr::validation::Validate;
//! use openehr::rm::data_structures::Element;
//!
//! // An ELEMENT that serde built with both a value and a null flavour: no
//! // constructor produces it, and a sender can still send it.
//! let json = r#"{
//!   "name": {"value": "Systolic"},
//!   "archetype_node_id": "at0004",
//!   "value": {"_type": "DV_COUNT", "magnitude": 1},
//!   "null_flavour": {"value": "unknown", "defining_code":
//!     {"terminology_id": {"value": "openehr"}, "code_string": "253"}}
//! }"#;
//! let element: Element = serde_json::from_str(json).unwrap();
//! let report = element.validate();
//! assert!(!report.is_empty());
//! assert_eq!(report.violations()[0].invariant, "Inv_null_flavour_indicated");
//! ```

use crate::error::{ValidationReport, Violation};
use crate::rm::common::{Attestation, Locatable as _, Participation, PartyProxy};
use crate::rm::data_structures::{Cluster, Element, Event, History, Item, ItemStructure};
use crate::rm::data_types::{DataValue, DvCodedText, DvOrdered, DvQuantity, OrderedAttrs, Text};
use crate::rm::ehr::{Composition, ContentItem, EhrStatus, Entry, EventContext, Section};

/// Accumulates violations while walking a structure, tracking where it is.
#[derive(Debug, Default)]
pub struct Context {
    path: Vec<String>,
    report: ValidationReport,
}

impl Context {
    /// A fresh context rooted at the object being validated.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Records a violation at the current path.
    pub fn violation(
        &mut self,
        class: &'static str,
        invariant: &'static str,
        detail: &'static str,
    ) {
        self.report.push(Violation {
            path: self.path.join(""),
            class,
            invariant,
            detail,
        });
    }

    /// Runs `f` with one more path segment pushed.
    fn nested<F: FnOnce(&mut Self)>(&mut self, segment: String, f: F) {
        self.path.push(segment);
        f(self);
        self.path.pop();
    }

    /// The accumulated report.
    #[must_use]
    pub fn finish(self) -> ValidationReport {
        self.report
    }
}

/// Checks a structure's Reference Model invariants.
pub trait Validate {
    /// Walks the structure, recording every violation found.
    fn visit(&self, ctx: &mut Context);

    /// Validates the structure and returns everything that failed.
    fn validate(&self) -> ValidationReport {
        let mut ctx = Context::new();
        self.visit(&mut ctx);
        ctx.finish()
    }

    /// Validates and converts to a `Result`.
    ///
    /// # Errors
    ///
    /// Returns the [`ValidationReport`] if any invariant failed.
    fn validate_ok(&self) -> Result<(), ValidationReport> {
        self.validate().into_result()
    }
}

/// Checks the invariants shared by every `LOCATABLE`.
fn check_locatable<L: crate::rm::common::Locatable>(node: &L, ctx: &mut Context) {
    if node.archetype_node_id().is_empty() {
        ctx.violation(
            "LOCATABLE",
            "Archetype_node_id_valid",
            "archetype_node_id is empty, so the node cannot be reached by any path",
        );
    }
    // openEHR's `LOCATABLE.Name_valid` is only `name /= Void` — an *empty* name
    // breaks `DV_TEXT.Value_valid` instead, and attributing it to `Name_valid`
    // would send a reader to the wrong class definition (`L10.4`).
    if node.name().value().is_empty() {
        ctx.nested("/name".to_owned(), |c| {
            c.violation("DV_TEXT", "Valid_value", "value is empty");
        });
    }
    // An archetype root whose archetype id constrains a different RM class is
    // the single most common structural error in hand-built or
    // transform-produced instances: an OBSERVATION archetype id on an
    // EVALUATION node. Nothing downstream detects it, and the data looks fine.
    if let Some(details) = node.archetype_details() {
        let entity = details.archetype_id().rm_entity();
        if entity != node.rm_type_name() {
            ctx.violation(
                "ARCHETYPED",
                "Archetype_id_rm_entity_matches",
                "archetype id constrains a different RM class than the node it annotates",
            );
        }
        if details.rm_version().is_empty() {
            ctx.violation("ARCHETYPED", "Rm_version_valid", "rm_version is empty");
        }
    }
}

/// Checks a `DV_CODED_TEXT` against the openEHR support terminology.
fn check_coded_text(coded: &DvCodedText, ctx: &mut Context) {
    if coded.check_openehr_rubric() == Some(false) {
        ctx.violation(
            "DV_CODED_TEXT",
            "Value_is_rubric",
            "value does not match the openEHR rubric for defining_code",
        );
    }
}

/// Checks the two `DV_ORDERED` invariants that relate a value to its own
/// recorded reference range.
///
/// `is_abnormal` is the value's own answer to "am I outside my normal range?",
/// which is `None` when no range was recorded — see [`DvOrdered::is_abnormal`].
fn check_ordered(attrs: &OrderedAttrs, is_abnormal: Option<bool>, ctx: &mut Context) {
    let Some(status) = attrs.normal_status() else {
        return;
    };
    // `Normal_status_validity`: the status comes from the openEHR
    // "normal statuses" code set — the HL7 abnormal-flag letters. A status
    // outside it is not comparable with anything, and a renderer will show it
    // verbatim next to a result.
    if !crate::terminology::normal_status::GROUP.contains(status.code_string()) {
        ctx.violation(
            "DV_ORDERED",
            "Normal_status_validity",
            "normal_status is not from the openEHR normal-statuses code set",
        );
    }
    // `Normal_range_and_status_consistency`: with both a range and a status
    // present, `N` and "inside the range" must agree. They disagree when a
    // result is copied from one system and its flag from another — exactly the
    // case where a clinician sees a normal flag beside an abnormal number.
    if let Some(abnormal) = is_abnormal {
        let says_normal = status.code_string() == crate::terminology::normal_status::NORMAL;
        if says_normal == abnormal {
            ctx.violation(
                "DV_ORDERED",
                "Normal_range_and_status_consistency",
                "normal_status and the value's position in its normal_range disagree",
            );
        }
    }
}

/// Checks a `DV_TEXT`-typed attribute that openEHR requires to come from a
/// terminology group **when it happens to be coded**.
///
/// `PARTICIPATION.function`, `PARTICIPATION.mode`, and `ATTESTATION.reason` are
/// all shaped this way: the attribute is `DV_TEXT` because the useful
/// vocabulary lives in external terminologies, and the openEHR group applies
/// only if the value is a `DV_CODED_TEXT` from openEHR's own terminology.
/// Checking unconditionally would reject a SNOMED-coded participation function,
/// which is the commonest real case.
fn check_optional_group(
    text: &Text,
    group: crate::terminology::Group,
    class: &'static str,
    invariant: &'static str,
    ctx: &mut Context,
) {
    let Text::Coded(coded) = text else {
        return;
    };
    check_coded_text(coded, ctx);
    if coded.defining_code().is_openehr() && !group.contains(coded.defining_code().code_string()) {
        ctx.violation(
            class,
            invariant,
            "coded value is not from its openEHR group",
        );
    }
}

/// Checks one `PARTICIPATION`.
fn check_participation(participation: &Participation, ctx: &mut Context) {
    check_optional_group(
        participation.function(),
        crate::terminology::participation_function::GROUP,
        "PARTICIPATION",
        "Function_valid",
        ctx,
    );
    if let Some(mode) = participation.mode() {
        check_coded_text(mode, ctx);
        if mode.defining_code().is_openehr()
            && !crate::terminology::participation_mode::GROUP
                .contains(mode.defining_code().code_string())
        {
            ctx.violation(
                "PARTICIPATION",
                "Mode_valid",
                "mode is not from the openEHR participation-mode group",
            );
        }
    }
    check_party(
        participation.performer(),
        "PARTICIPATION",
        "Performer_valid",
        ctx,
    );
}

/// Checks one `ATTESTATION`.
///
/// Not reachable from a `COMPOSITION`: attestations hang off a `VERSION`, which
/// is why this is public — a caller validating a version calls it directly.
pub fn check_attestation(attestation: &Attestation, ctx: &mut Context) {
    check_optional_group(
        attestation.reason(),
        crate::terminology::attestation_reason::GROUP,
        "ATTESTATION",
        "Reason_valid",
        ctx,
    );
    check_party(
        attestation.audit().committer(),
        "AUDIT_DETAILS",
        "Committer_valid",
        ctx,
    );
}

impl Validate for DataValue {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::CodedText(t) => check_coded_text(t, ctx),
            Self::Ordinal(o) => {
                check_coded_text(o.symbol(), ctx);
                check_ordered(o.ordered_attrs(), o.is_abnormal(), ctx);
            }
            Self::Scale(s) => {
                check_coded_text(s.symbol(), ctx);
                check_ordered(s.ordered_attrs(), s.is_abnormal(), ctx);
            }
            Self::Count(c) => check_ordered(c.ordered_attrs(), c.is_abnormal(), ctx),
            Self::Quantity(q) => {
                if !q.magnitude().is_finite() {
                    ctx.violation(
                        "DV_QUANTITY",
                        "Magnitude_finite",
                        "magnitude is not a finite number",
                    );
                }
                if q.units().is_empty() {
                    ctx.violation("DV_QUANTITY", "Units_valid", "units is empty");
                }
                // `precision >= -1`, not `>= 0`: -1 is openEHR's stated
                // "unlimited decimal places", not an out-of-range value.
                if q.precision()
                    .is_some_and(|p| p < DvQuantity::UNLIMITED_PRECISION)
                {
                    ctx.violation(
                        "DV_QUANTITY",
                        "Precision_valid",
                        "precision is below -1, the unlimited-precision sentinel",
                    );
                }
                check_ordered(q.ordered_attrs(), q.is_abnormal(), ctx);
            }
            Self::Proportion(p) => {
                if p.denominator() == 0.0 {
                    ctx.violation("DV_PROPORTION", "Valid_denominator", "denominator is zero");
                }
                if p.kind().requires_integral() && !p.is_integral() {
                    ctx.violation(
                        "DV_PROPORTION",
                        "Fraction_validity",
                        "a fractional kind has a non-integral numerator or denominator",
                    );
                }
                // `precision = 0 implies is_integral`: declaring precision zero
                // asserts the parts really are whole numbers.
                if p.precision() == Some(0) && !p.is_integral() {
                    ctx.violation(
                        "DV_PROPORTION",
                        "Precision_validity",
                        "precision is 0 but a part has a fractional component",
                    );
                }
                check_ordered(p.ordered_attrs(), p.is_abnormal(), ctx);
            }
            Self::Multimedia(m) => {
                if !m.has_content() {
                    ctx.violation(
                        "DV_MULTIMEDIA",
                        "Not_empty",
                        "neither inline data nor a uri is present",
                    );
                }
                if m.verify_integrity() == crate::rm::data_types::IntegrityCheck::Failed {
                    ctx.violation(
                        "DV_MULTIMEDIA",
                        "Integrity_check_validity",
                        "the recorded digest does not match the inline data",
                    );
                }
            }
            Self::Text(t) if t.value().is_empty() => {
                ctx.violation("DV_TEXT", "Valid_value", "value is empty");
            }
            _ => {}
        }
    }
}

impl Validate for Element {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        // openEHR: `is_null xor null_flavour = Void`. Both present and both
        // absent are each a violation, and they fail differently: both present
        // is a contradiction, both absent is an element that says nothing.
        match (self.value().is_some(), self.null_flavour().is_some()) {
            (true, true) => ctx.violation(
                "ELEMENT",
                "Inv_null_flavour_indicated",
                "an element has both a value and a null_flavour",
            ),
            (false, false) => ctx.violation(
                "ELEMENT",
                "Inv_null_flavour_indicated",
                "an element has neither a value nor a null_flavour",
            ),
            _ => {}
        }
        if self.null_reason().is_some() && self.value().is_some() {
            ctx.violation(
                "ELEMENT",
                "Inv_null_reason_valid",
                "a reason for absence is recorded on an element that has a value",
            );
        }
        if let Some(flavour) = self.null_flavour() {
            if !flavour.defining_code().is_openehr()
                || !crate::terminology::null_flavour::GROUP
                    .contains(flavour.defining_code().code_string())
            {
                ctx.violation(
                    "ELEMENT",
                    "Inv_null_flavour_valid",
                    "null_flavour is not one of the four openEHR null flavours",
                );
            }
            check_coded_text(flavour, ctx);
        }
        if let Some(value) = self.value() {
            ctx.nested("/value".to_owned(), |c| value.visit(c));
        }
    }
}

impl Validate for Cluster {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        if self.items().is_empty() {
            ctx.violation("CLUSTER", "Items_non_empty", "a cluster has no items");
        }
        for (i, item) in self.items().iter().enumerate() {
            ctx.nested(format!("/items[{i}]"), |c| item.visit(c));
        }
    }
}

impl Validate for Item {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Cluster(v) => v.visit(ctx),
            Self::Element(v) => v.visit(ctx),
        }
    }
}

impl Validate for ItemStructure {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Single(s) => {
                check_locatable(s, ctx);
                ctx.nested("/item".to_owned(), |c| s.item().visit(c));
            }
            Self::List(s) => {
                check_locatable(s, ctx);
                for (i, e) in s.items().iter().enumerate() {
                    ctx.nested(format!("/items[{i}]"), |c| e.visit(c));
                }
            }
            Self::Table(s) => {
                check_locatable(s, ctx);
                if !s.is_regular() {
                    ctx.violation(
                        "ITEM_TABLE",
                        "Rows_regular",
                        "rows do not all have the same number of columns",
                    );
                }
                for (i, r) in s.rows().iter().enumerate() {
                    ctx.nested(format!("/rows[{i}]"), |c| r.visit(c));
                }
            }
            Self::Tree(s) => {
                check_locatable(s, ctx);
                for (i, item) in s.items().iter().enumerate() {
                    ctx.nested(format!("/items[{i}]"), |c| item.visit(c));
                }
            }
        }
    }
}

impl Validate for Event {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Point(e) => {
                check_locatable(e, ctx);
                ctx.nested("/data".to_owned(), |c| e.data().visit(c));
                if let Some(state) = e.state() {
                    ctx.nested("/state".to_owned(), |c| state.visit(c));
                }
            }
            Self::Interval(e) => {
                check_locatable(e, ctx);
                if e.width().value().is_negative() {
                    ctx.violation(
                        "INTERVAL_EVENT",
                        "Width_non_negative",
                        "width is negative, so the interval ends before it starts",
                    );
                }
                check_coded_text(e.math_function(), ctx);
                ctx.nested("/data".to_owned(), |c| e.data().visit(c));
                if let Some(state) = e.state() {
                    ctx.nested("/state".to_owned(), |c| state.visit(c));
                }
            }
        }
    }
}

impl Validate for History {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        if self.events().is_empty() && self.summary().is_none() {
            ctx.violation(
                "HISTORY",
                "Events_valid",
                "a history has neither events nor a summary",
            );
        }
        if self
            .period()
            .is_some_and(|p| p.value().is_zero() || p.value().is_negative())
        {
            ctx.violation(
                "HISTORY",
                "Periodic_validity",
                "a periodic history declares a zero or negative period",
            );
        }
        // `period_consistency`: in a periodic series every event must fall on a
        // multiple of the period. A series that says it is periodic and is not
        // will be resampled or graphed on the strength of that declaration.
        if self.is_period_consistent() == Some(false) {
            ctx.violation(
                "HISTORY",
                "Period_consistency",
                "a periodic history has an event whose offset is not a multiple of the period",
            );
        }
        for (i, event) in self.events().iter().enumerate() {
            // Every event must be at or after the history's origin: an event
            // before the zero point has a negative offset, and `EVENT.offset`
            // is defined as `time - origin` with no provision for one.
            if matches!(
                event.time().partial_cmp(self.origin()),
                Some(core::cmp::Ordering::Less)
            ) {
                ctx.nested(format!("/events[{i}]"), |c| {
                    c.violation(
                        "EVENT",
                        "Time_after_origin",
                        "event time is before the history origin",
                    );
                });
            }
            ctx.nested(format!("/events[{i}]"), |c| event.visit(c));
        }
        if let Some(summary) = self.summary() {
            ctx.nested("/summary".to_owned(), |c| summary.visit(c));
        }
    }
}

impl Validate for EventContext {
    fn visit(&self, ctx: &mut Context) {
        check_coded_text(self.setting(), ctx);
        if !self.setting().defining_code().is_openehr()
            || !crate::terminology::setting::GROUP
                .contains(self.setting().defining_code().code_string())
        {
            ctx.violation(
                "EVENT_CONTEXT",
                "Setting_valid",
                "setting is not from the openEHR setting group",
            );
        }
        if let Some(end) = self.end_time()
            && matches!(
                end.partial_cmp(self.start_time()),
                Some(core::cmp::Ordering::Less)
            )
        {
            ctx.violation(
                "EVENT_CONTEXT",
                "End_time_valid",
                "end_time is before start_time",
            );
        }
        if self.location().is_some_and(str::is_empty) {
            ctx.violation(
                "EVENT_CONTEXT",
                "location_valid",
                "location is present and empty",
            );
        }
        for (i, participation) in self.participations().iter().enumerate() {
            ctx.nested(format!("/participations[{i}]"), |c| {
                check_participation(participation, c);
            });
        }
        if let Some(other) = self.other_context() {
            ctx.nested("/other_context".to_owned(), |c| other.visit(c));
        }
    }
}

impl Validate for Entry {
    fn visit(&self, ctx: &mut Context) {
        check_locatable_entry(self, ctx);
        check_party(self.subject(), "ENTRY", "Subject_valid", ctx);
        if let Some(provider) = self.entry_attrs().provider() {
            check_party(provider, "ENTRY", "Provider_valid", ctx);
        }
        for (i, participation) in self.entry_attrs().other_participations().iter().enumerate() {
            ctx.nested(format!("/other_participations[{i}]"), |c| {
                check_participation(participation, c);
            });
        }
        match self {
            Self::Observation(o) => {
                ctx.nested("/data".to_owned(), |c| o.data().visit(c));
                if let Some(state) = o.state() {
                    ctx.nested("/state".to_owned(), |c| state.visit(c));
                }
                if let Some(protocol) = o.care_entry().protocol() {
                    ctx.nested("/protocol".to_owned(), |c| protocol.visit(c));
                }
            }
            Self::Evaluation(e) => ctx.nested("/data".to_owned(), |c| e.data().visit(c)),
            Self::AdminEntry(a) => ctx.nested("/data".to_owned(), |c| a.data().visit(c)),
            Self::Instruction(i) => {
                if i.activities().is_empty() {
                    ctx.violation(
                        "INSTRUCTION",
                        "Activities_valid",
                        "an instruction has no activities",
                    );
                }
                if i.narrative().value().is_empty() {
                    ctx.violation(
                        "INSTRUCTION",
                        "Narrative_valid",
                        "an instruction has an empty narrative",
                    );
                }
                for (n, activity) in i.activities().iter().enumerate() {
                    ctx.nested(format!("/activities[{n}]/description"), |c| {
                        activity.description().visit(c);
                    });
                }
            }
            Self::Action(a) => {
                check_coded_text(a.ism_transition().current_state(), ctx);
                if !crate::terminology::instruction_state::GROUP.contains(
                    a.ism_transition()
                        .current_state()
                        .defining_code()
                        .code_string(),
                ) {
                    ctx.violation(
                        "ISM_TRANSITION",
                        "Current_state_valid",
                        "current_state is not an Instruction State Machine state",
                    );
                }
                ctx.nested("/description".to_owned(), |c| a.description().visit(c));
            }
        }
    }
}

fn check_locatable_entry(entry: &Entry, ctx: &mut Context) {
    match entry {
        Entry::Observation(e) => check_locatable(e, ctx),
        Entry::Evaluation(e) => check_locatable(e, ctx),
        Entry::Instruction(e) => check_locatable(e, ctx),
        Entry::Action(e) => check_locatable(e, ctx),
        Entry::AdminEntry(e) => check_locatable(e, ctx),
    }
}

fn check_party(
    party: &PartyProxy,
    class: &'static str,
    invariant: &'static str,
    ctx: &mut Context,
) {
    let identified = match party {
        PartyProxy::SelfParty(_) => return,
        PartyProxy::Identified(p) => p,
        PartyProxy::Related(p) => {
            check_coded_text(p.relationship(), ctx);
            // `Relationship_valid`: the relationship comes from the openEHR
            // `subject_relationship` group. This is the attribute that says
            // whom an entry is about, so an unrecognised code means a finding
            // may be attributed to the wrong person.
            let code = p.relationship().defining_code();
            if code.is_openehr()
                && !crate::terminology::subject_relationship::GROUP.contains(code.code_string())
            {
                ctx.violation(
                    "PARTY_RELATED",
                    "Relationship_valid",
                    "relationship is not from the openEHR subject-relationship group",
                );
            }
            p.as_identified()
        }
    };
    if identified.name().is_none()
        && identified.identifiers().is_empty()
        && identified.external_ref().is_none()
    {
        ctx.violation(
            class,
            invariant,
            "an identified party has no name, no identifiers, and no external reference",
        );
    }
}

impl Validate for Section {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        for (i, item) in self.items().iter().enumerate() {
            ctx.nested(format!("/items[{i}]"), |c| item.visit(c));
        }
    }
}

impl Validate for ContentItem {
    fn visit(&self, ctx: &mut Context) {
        match self {
            Self::Section(s) => s.visit(ctx),
            Self::Entry(e) => e.visit(ctx),
        }
    }
}

impl Validate for EhrStatus {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        // `Is_archetype_root`, as for `COMPOSITION`: an EHR_STATUS is a
        // versioned, archetyped object in its own right.
        if !self.is_archetype_root() {
            ctx.violation(
                "EHR_STATUS",
                "Is_archetype_root",
                "an EHR_STATUS has no archetype_details, so it is not an archetype root",
            );
        }
        if let Some(other) = self.other_details() {
            ctx.nested("/other_details".to_owned(), |c| other.visit(c));
        }
    }
}

impl Validate for Composition {
    fn visit(&self, ctx: &mut Context) {
        check_locatable(self, ctx);
        check_coded_text(self.category(), ctx);
        if !crate::terminology::composition_category::GROUP.contains(self.category_code()) {
            ctx.violation(
                "COMPOSITION",
                "Category_validity",
                "category is not from the openEHR composition_category group",
            );
        }
        check_party(self.composer(), "COMPOSITION", "Composer_valid", ctx);
        // `Is_archetype_root`: a COMPOSITION is by definition the root of a
        // composition archetype. One without `archetype_details` cannot say
        // which archetype shaped it, and nothing downstream can validate it
        // against one.
        if !self.is_archetype_root() {
            ctx.violation(
                "COMPOSITION",
                "Is_archetype_root",
                "a composition has no archetype_details, so it is not an archetype root",
            );
        }
        // `Is_persistent_validity`: a persistent composition is a running
        // summary across many encounters, so one encounter's context would
        // assert that the whole list belongs to that visit.
        if self.is_persistent() && self.context().is_some() {
            ctx.violation(
                "COMPOSITION",
                "Is_persistent_validity",
                "a persistent composition carries an event context",
            );
        }
        if let Some(context) = self.context() {
            ctx.nested("/context".to_owned(), |c| context.visit(c));
        }
        for (i, item) in self.content().iter().enumerate() {
            ctx.nested(format!("/content[{i}]"), |c| item.visit(c));
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base::Interval;
    use crate::rm::common::{Archetyped, LocatableAttrs, PartyIdentified};
    use crate::rm::data_structures::{ItemSingle, PointEvent};
    use crate::rm::data_types::{CodePhrase, DvCount, DvDateTime, DvQuantity, DvText};
    use crate::rm::ehr::{EntryAttrs, Evaluation, Observation};
    use crate::terminology;

    fn attrs(name: &str, node: &str) -> LocatableAttrs {
        LocatableAttrs::named(name, node).unwrap()
    }

    fn structure() -> ItemStructure {
        ItemSingle::new(
            attrs("d", "at0001"),
            Element::new(attrs("v", "at0002"), DataValue::Count(DvCount::new(1))),
        )
        .into()
    }

    fn entry_attrs() -> EntryAttrs {
        EntryAttrs::about_subject(
            CodePhrase::new("ISO_639-1", "en").unwrap(),
            CodePhrase::new("IANA_character-sets", "UTF-8").unwrap(),
        )
    }

    fn composition() -> Composition {
        Composition::new(
            attrs("Encounter", "openEHR-EHR-COMPOSITION.encounter.v1").with_archetype_details(
                Archetyped::new("openEHR-EHR-COMPOSITION.encounter.v1", "1.1.0").unwrap(),
            ),
            terminology::composition_category::EVENT,
            PartyIdentified::named("Dr A Nurse").unwrap().into(),
            CodePhrase::new("ISO_639-1", "en").unwrap(),
            CodePhrase::new("ISO_3166-1", "GB").unwrap(),
        )
        .unwrap()
    }

    #[test]
    fn a_well_formed_composition_has_no_violations() {
        let c = composition().with_content(
            Evaluation::new(attrs("Problem", "at0000"), entry_attrs(), structure()).into(),
        );
        let report = c.validate();
        assert!(report.is_empty(), "{report}");
    }

    #[test]
    fn deserialization_bypasses_constructors_and_validation_catches_it() {
        // The mutation check for this whole module: if `visit` stopped
        // checking the null invariant, this element would validate clean.
        let json = r#"{
          "name": {"value": "Systolic"},
          "archetype_node_id": "at0004",
          "value": {"_type": "DV_COUNT", "magnitude": 1},
          "null_flavour": {"value": "unknown", "defining_code":
            {"terminology_id": {"value": "openehr"}, "code_string": "253"}}
        }"#;
        let element: Element = serde_json::from_str(json).unwrap();
        let report = element.validate();
        assert_eq!(report.len(), 1);
        assert_eq!(report.violations()[0].invariant, "Inv_null_flavour_indicated");
    }

    #[test]
    fn an_element_with_nothing_at_all_is_also_a_violation() {
        let json = r#"{"name": {"value": "Systolic"}, "archetype_node_id": "at0004"}"#;
        let element: Element = serde_json::from_str(json).unwrap();
        assert_eq!(element.validate().len(), 1);
    }

    #[test]
    fn an_archetype_id_on_the_wrong_class_is_reported() {
        let wrong = Evaluation::new(
            attrs("Problem", "openEHR-EHR-OBSERVATION.blood_pressure.v2").with_archetype_details(
                Archetyped::new("openEHR-EHR-OBSERVATION.blood_pressure.v2", "1.1.0").unwrap(),
            ),
            entry_attrs(),
            structure(),
        );
        let report = Entry::from(wrong).validate();
        assert_eq!(report.len(), 1);
        assert_eq!(
            report.violations()[0].invariant,
            "Archetype_id_rm_entity_matches"
        );
    }

    #[test]
    fn a_coded_text_that_contradicts_its_own_code_is_reported() {
        let json = r#"{
          "name": {"value": "Category"},
          "archetype_node_id": "at0001",
          "value": {"_type": "DV_CODED_TEXT", "value": "deletion",
            "defining_code": {"terminology_id": {"value": "openehr"}, "code_string": "249"}}
        }"#;
        let element: Element = serde_json::from_str(json).unwrap();
        let report = element.validate();
        assert_eq!(report.len(), 1);
        assert_eq!(report.violations()[0].invariant, "Value_is_rubric");
        // The path locates the offending node without repeating its content.
        assert_eq!(report.violations()[0].path, "/value");
    }

    #[test]
    fn violation_paths_locate_the_node_and_never_the_value() {
        let marker = "ZZ-DISTINCTIVE-9999";
        let bad_element: Element = serde_json::from_str(&format!(
            r#"{{"name": {{"value": "{marker}"}}, "archetype_node_id": "at0004"}}"#
        ))
        .unwrap();
        let structure: ItemStructure = ItemSingle::new(attrs("d", "at0001"), bad_element).into();
        let report = structure.validate();
        assert_eq!(report.violations()[0].path, "/item");
        assert!(!report.to_string().contains(marker), "{report}");
    }

    #[test]
    fn an_event_before_its_history_origin_is_reported() {
        let event = PointEvent::new(
            attrs("early", "at0006"),
            DvDateTime::new("2026-07-31T08:00:00Z").unwrap(),
            structure(),
        );
        let history = History::new(
            attrs("Event Series", "at0001"),
            DvDateTime::new("2026-07-31T09:00:00Z").unwrap(),
            vec![event.into()],
            None,
        )
        .unwrap();
        let observation = Observation::new(attrs("Obs", "at0000"), entry_attrs(), history);
        let report = Entry::from(observation).validate();
        assert_eq!(report.len(), 1);
        assert_eq!(report.violations()[0].invariant, "Time_after_origin");
        assert_eq!(report.violations()[0].path, "/data/events[0]");
    }

    #[test]
    fn every_violation_is_reported_not_just_the_first() {
        let json = r#"{
          "name": {"value": ""},
          "archetype_node_id": "",
          "value": {"_type": "DV_QUANTITY", "magnitude": 1.0, "units": "", "precision": -3}
        }"#;
        let element: Element = serde_json::from_str(json).unwrap();
        let report = element.validate();
        // empty node id, empty name, empty units, negative precision.
        assert_eq!(report.len(), 4, "{report}");
    }

    #[test]
    fn a_normal_flag_beside_an_abnormal_number_is_reported() {
        // `DV_ORDERED.Normal_range_and_status_consistency`. This is the
        // real-world shape of the defect: a result arrives from one system and
        // its abnormal flag from another, and the clinician sees "N" next to a
        // potassium of 9.9.
        let range = Interval::closed(
            DataValue::Quantity(DvQuantity::new(3.5, "mmol/l").unwrap()),
            DataValue::Quantity(DvQuantity::new(5.5, "mmol/l").unwrap()),
        )
        .unwrap();
        let lying = DvQuantity::new(9.9, "mmol/l")
            .unwrap()
            .with_normal_range(range.clone())
            .with_normal_status(CodePhrase::openehr(terminology::normal_status::NORMAL).unwrap());
        let report = Element::new(attrs("K", "at0004"), DataValue::Quantity(lying)).validate();
        assert_eq!(report.len(), 1, "{report}");
        assert_eq!(
            report.violations()[0].invariant,
            "Normal_range_and_status_consistency"
        );

        // The same value flagged `HHH` is consistent, and so is an in-range
        // value flagged `N`.
        let truthful = DvQuantity::new(9.9, "mmol/l")
            .unwrap()
            .with_normal_range(range.clone())
            .with_normal_status(
                CodePhrase::openehr(terminology::normal_status::VERY_HIGH).unwrap(),
            );
        assert!(
            Element::new(attrs("K", "at0004"), DataValue::Quantity(truthful))
                .validate()
                .is_empty()
        );
        let in_range = DvQuantity::new(4.2, "mmol/l")
            .unwrap()
            .with_normal_range(range)
            .with_normal_status(CodePhrase::openehr(terminology::normal_status::NORMAL).unwrap());
        assert!(
            Element::new(attrs("K", "at0004"), DataValue::Quantity(in_range))
                .validate()
                .is_empty()
        );
    }

    #[test]
    fn a_normal_status_outside_the_code_set_is_reported() {
        // `DV_ORDERED.Normal_status_validity`. A renderer shows this letter
        // verbatim beside a result, so an invented one reaches a clinician.
        let odd = DvQuantity::new(4.2, "mmol/l")
            .unwrap()
            .with_normal_status(CodePhrase::openehr("VERY-HIGH-INDEED").unwrap());
        let report = Element::new(attrs("K", "at0004"), DataValue::Quantity(odd)).validate();
        assert_eq!(report.len(), 1, "{report}");
        assert_eq!(report.violations()[0].invariant, "Normal_status_validity");
    }

    #[test]
    fn the_unlimited_precision_sentinel_validates() {
        // The mutation check for the A-01 fix: a validator requiring
        // `precision >= 0` reports a violation here, and the data is
        // conformant.
        let unlimited = DvQuantity::new(1.5, "mg")
            .unwrap()
            .with_precision(-1)
            .unwrap();
        assert!(
            Element::new(attrs("q", "at0004"), DataValue::Quantity(unlimited))
                .validate()
                .is_empty()
        );
    }

    #[test]
    fn a_valid_quantity_with_a_normal_range_still_validates() {
        let q = DvQuantity::new(4.2, "mmol/l").unwrap();
        let element = Element::new(attrs("Glucose", "at0004"), DataValue::Quantity(q));
        assert!(element.validate().is_empty());
        let _ = DvText::new("unused");
    }
}