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
// SPDX-FileCopyrightText: Veredictum contributors
// SPDX-License-Identifier: Apache-2.0

//! Response-header assertion evaluation.
//!
//! The executed half of the catalogue's `outcomes.*.headers` declarations.
//!
//! Evaluation runs only when the step's observation matched the expected
//! outcome kind, since the declared headers belong to that outcome's wire
//! expectation. A failed matcher is a conformance failure of the row (law (b)),
//! never an inconclusive error: the exchange completed, and the spec sentence
//! the binding cites assigns the header.
//!
//! Two declaration-level modifiers gate whether a matcher is judged at all
//! (both defined on [`crate::model::binding::HeaderExpectation`], which
//! carries the decisive spec sentences):
//!
//! - `optional: true` (authored bare as `present?`) — the presence of the
//!   header is a SHOULD or MAY, so an absent or blank header satisfies the
//!   expectation outright while a header that is there is judged in full, which
//!   keeps a MUST-strength form biting.
//! - `applies: { its_rest: ">=1.1.0" }` — the rule is dated by the released
//!   text itself (the `W/` weakness indicator and the read/DELETE `Location`
//!   deprecation are both "Prior to Release 1.1.0" changes). A party whose
//!   declared spec versions do not satisfy the floor is not judged on it;
//!   everything else on the outcome still is.
//!
//! Matcher semantics (the closed [`HeaderMatcher`] vocabulary):
//!
//! - `present` — the header exists with a non-empty value.
//! - `present-with-body` — the header exists with a non-empty value WHEN the
//!   response carries a content body, and carries no criterion when it does
//!   not: `Resources.md` §JSON Format "Proper header `Content-Type:
//!   application/json` MUST be present in the response of the service unless
//!   the response has no content body (HTTP status code `204`)" (§XML Format
//!   and §Simplified Formats carry the identical sentence).
//! - `absent` — the header must not exist (e.g. `Location` on reads —
//!   overview §Location "MUST NOT be used to indicate an alternate
//!   representation").
//! - `negotiated` — the header's media token (parameters stripped) equals
//!   the request's negotiated `Accept` token.
//! - `latest-version-uid` — the stale-precondition rule (overview §"If-Match
//!   and accidental overwrites": the 412 "SHOULD return also latest
//!   `version_uid` in the `ETag`"): the entity-tag's payload (weak/quoted
//!   wrapper stripped) equals the latest version uid this row committed FOR
//!   THE VERSIONED OBJECT the request addressed, compared case-insensitively
//!   (BASE `master05` §Composite Identifiers and Case). When the row
//!   committed nothing to that object, the matcher degrades to `present` —
//!   honest, never a false red.
//! - `pattern:<regex>` — full-value match after `<name>` placeholders resolve
//!   (`resolve_placeholders`): a STRUCTURAL token substitutes its released
//!   grammar, any other name substitutes the regex-escaped scalar of the
//!   same-named case variable, and anything else is a loud refusal.
//! - a literal — template-rendered against the case variables, exact match.

#![allow(
    clippy::disallowed_types,
    reason = "dev/verification tooling over JSON artifacts (the catalogue, results, wire \
              exchanges), whose shapes belong to the artifacts and the SUT; the carriers \
              here are cfg(test)-only, so #[expect] would be unfulfilled in the non-test build"
)]

use std::collections::BTreeMap;

use crate::exec::assertions;
use crate::exec::state::VarStore;
use crate::model::binding::{HeaderExpectation, HeaderMatcher, WireExpectation};
use crate::party::SpecVersions;

/// The request-side context a matcher may need.
#[derive(Debug, Default)]
pub struct RequestContext<'a> {
    /// The `Accept` value the driver sent (the negotiated type).
    pub accept: Option<&'a str>,
    /// The latest version uid committed on this row FOR THE VERSIONED OBJECT
    /// this request addressed (the newest successful `version_uid` binding
    /// capture naming that object), for `latest-version-uid`. `None` when the
    /// row committed nothing to it.
    pub last_version_uid: Option<&'a str>,
    /// The party statement's declared spec versions — the right-hand side of
    /// a version-dated expectation's `applies` floor. `None` (a
    /// statement-blind sweep) declares nothing, so a dated rule is out of
    /// scope exactly as it is for a party that omits the component.
    pub spec_versions: Option<&'a SpecVersions>,
}

/// Evaluate every declared header expectation of `expectation` against the
/// response headers; returns one failure line per violated expectation.
///
/// `body` is the observed response body, which the `present-with-body` matcher
/// needs: its criterion exists only when the response carries content.
#[must_use]
pub fn evaluate(
    expectation: &WireExpectation,
    response_headers: &BTreeMap<String, String>,
    body: Option<&serde_json::Value>,
    ctx: &RequestContext<'_>,
    vars: &VarStore,
) -> Vec<String> {
    let Some(declared) = expectation.headers.as_deref() else {
        return Vec::new();
    };
    let mut failures = Vec::new();
    for (name, declarations) in declared {
        for header in declarations.all() {
            if !in_scope(header, ctx) {
                continue;
            }
            let observed = header_value(response_headers, name);
            // Nothing to judge when the server exercised a SHOULD/MAY latitude
            // and omitted the header; one that IS there still faces the matcher.
            if header.optional && observed.is_none_or(|v| v.trim().is_empty()) {
                continue;
            }
            if let Some(failure) = judge(name, &header.matcher, observed, body, ctx, vars) {
                failures.push(failure);
            }
        }
    }
    failures
}

/// Whether a version-dated expectation is in scope for the declaring party.
fn in_scope(header: &HeaderExpectation, ctx: &RequestContext<'_>) -> bool {
    match &header.applies {
        None => true,
        Some(applies) => ctx
            .spec_versions
            .is_some_and(|versions| applies.satisfied_by(versions)),
    }
}

/// Case-insensitive header lookup (RFC 9110 §5.1: field names are
/// case-insensitive; reqwest lowercases, but the map is the transcript seam
/// so the lookup must not depend on that).
fn header_value<'a>(headers: &'a BTreeMap<String, String>, name: &str) -> Option<&'a str> {
    headers
        .iter()
        .find(|(k, _)| k.eq_ignore_ascii_case(name))
        .map(|(_, v)| v.as_str())
}

/// Judge one matcher; `None` = satisfied, `Some(reason)` = failed.
fn judge(
    name: &str,
    matcher: &HeaderMatcher,
    observed: Option<&str>,
    body: Option<&serde_json::Value>,
    ctx: &RequestContext<'_>,
    vars: &VarStore,
) -> Option<String> {
    match matcher {
        HeaderMatcher::Present => match observed {
            Some(v) if !v.trim().is_empty() => None,
            _ => Some(format!("header {name}: expected present, got none")),
        },
        HeaderMatcher::PresentWithBody => {
            // The MUST is exempted for a response with no content body, so a
            // body-less response carries no criterion at all.
            crate::exec::bodies::content(body)?;
            match observed {
                Some(v) if !v.trim().is_empty() => None,
                _ => Some(format!(
                    "header {name}: the response carries a content body, so the header must be present, got none"
                )),
            }
        }
        HeaderMatcher::Absent => observed.map(|v| {
            format!("header {name}: expected absent, got {v:?} (the binding's cited spec sentence forbids it on this outcome)")
        }),
        HeaderMatcher::Negotiated => {
            let Some(accept) = ctx.accept.map(media_token) else {
                // The endpoint default was negotiated, so nothing here is
                // sound to compare against.
                return None;
            };
            match observed {
                Some(v) if media_token(v).eq_ignore_ascii_case(accept) => None,
                Some(v) => Some(format!(
                    "header {name}: expected the negotiated media type {accept:?}, got {v:?}"
                )),
                None => Some(format!(
                    "header {name}: expected the negotiated media type {accept:?}, got none"
                )),
            }
        }
        HeaderMatcher::LatestVersionUid => match observed {
            None => Some(format!(
                "header {name}: expected the latest version uid, got none"
            )),
            Some(v) => {
                let payload = strip_entity_tag(v);
                if payload.is_empty() {
                    return Some(format!(
                        "header {name}: expected the latest version uid, got an empty entity tag"
                    ));
                }
                match ctx.last_version_uid {
                    // Compared case-insensitively: OBJECT_VERSION_ID is a
                    // composite identifier (BASE master05 §Composite
                    // Identifiers and Case).
                    Some(latest) if payload.eq_ignore_ascii_case(latest) => None,
                    Some(latest) => Some(format!(
                        "header {name}: expected the latest version uid {latest:?}, got {payload:?}"
                    )),
                    // The row committed nothing to the addressed object, so
                    // presence is all the runner can soundly assert.
                    None => None,
                }
            }
        },
        HeaderMatcher::Pattern(pattern) => {
            let Some(v) = observed else {
                return Some(format!(
                    "header {name}: expected a value matching {pattern:?}, got none"
                ));
            };
            let resolved = match resolve_placeholders(pattern, vars) {
                Ok(resolved) => resolved,
                Err(missing) => {
                    return Some(format!(
                        "header {name}: pattern {pattern:?} names <{missing}>, which is \
                         neither a captured/with-supplied case variable nor a structural \
                         token (<n>, <system_id>, <versioned_object_uid>, <template_hrid>) — \
                         refusing the vacuous wildcard (FerroEHR#1852)"
                    ));
                }
            };
            match regex::Regex::new(&format!("^(?:{resolved})$")) {
                Ok(re) if re.is_match(v) => None,
                Ok(_) => Some(format!(
                    "header {name}: value {v:?} does not match {pattern:?} (resolved: {resolved:?})"
                )),
                // The parse-time probe compiled the wildcarded form, so a
                // resolved form that no longer compiles is a runner bug.
                Err(e) => Some(format!(
                    "header {name}: resolved pattern {resolved:?} does not compile: {e}"
                )),
            }
        }
        HeaderMatcher::Literal(template) => {
            let Some(v) = observed else {
                return Some(format!("header {name}: expected a value, got none"));
            };
            match assertions::render_template(template, vars) {
                Ok(want) if want == v => None,
                Ok(want) => Some(format!("header {name}: expected {want:?}, got {v:?}")),
                Err(e) => Some(format!(
                    "header {name}: literal template unresolvable ({e}) — declared value cannot be checked"
                )),
            }
        }
    }
}

/// The media token of a `Content-Type`/`Accept` value — parameters
/// (`; charset=…`) stripped, whitespace trimmed (RFC 9110 §8.3).
fn media_token(value: &str) -> &str {
    value.split(';').next().unwrap_or(value).trim()
}

/// The payload of an entity tag: the weak indicator and surrounding quotes
/// stripped (`W/"x"` → `x`; `"x"` → `x`; bare stays bare) — the same
/// tolerance the SUT-side decode grants (overview §"`ETag` and Last-Modified"
/// weak form + §"Deprecated headers" bare form).
pub(crate) fn strip_entity_tag(value: &str) -> &str {
    let v = value.trim();
    let v = v
        .strip_prefix("W/")
        .or_else(|| v.strip_prefix("w/"))
        .unwrap_or(v);
    v.trim_matches('"')
}

/// The `version_tree_id` segment of an `OBJECT_VERSION_ID`: a trunk ordinal,
/// optionally a dotted branch triple (BASE `base_types` master05 §Syntaxes,
/// `version_tree_id = trunk_version, [ '.', branch_number, '.',
/// branch_version ]`).
pub(crate) const VERSION_TREE_ID: &str = r"[1-9][0-9]*(?:\.[0-9]+\.[0-9]+)?";

/// A `uid` — an ISO OID, a UUID, or a reverse-domain internet id (BASE
/// `base_types` master05 §Syntaxes: `uid = iso_oid | uuid | internet_id`).
///
/// BOTH composite segments of an `OBJECT_VERSION_ID` the matcher vocabulary
/// names are this one production — `object_id = uid` and
/// `creating_system_id = uid` — so they share the fragment. None of the three
/// alternatives admits `:` or `"`, which anchors it to its own
/// `::`-delimited segment by construction.
pub(crate) const UID: &str = concat!(
    r"(?:[0-9A-Fa-f]+(?:-[0-9A-Fa-f]+){4}",
    r"|[0-9]+(?:\.[0-9]+)*",
    r"|(?:[A-Za-z0-9]|[A-Za-z][A-Za-z0-9_-]*[A-Za-z0-9])",
    r"(?:\.(?:[A-Za-z0-9]|[A-Za-z][A-Za-z0-9_-]*[A-Za-z0-9]))*)",
);

/// An archetype/template human-readable identifier: an optional publisher
/// namespace, the 3-part qualified RM class name, the concept id, and the
/// `.v` release version (AM Identification master03 §Human-readable
/// Identifier (HRID) + master04 §Artefact Versioning).
const ARCHETYPE_HRID: &str = concat!(
    r"(?:[A-Za-z][A-Za-z0-9_-]*(?:\.[A-Za-z][A-Za-z0-9_-]*)*::)?",
    r"[A-Za-z][A-Za-z0-9_]+-[A-Za-z][A-Za-z0-9_]+-[A-Za-z][A-Za-z0-9_]+",
    r"\.[A-Za-z][A-Za-z0-9_-]+",
    r"\.v[0-9]+\.[0-9]+\.[0-9]+(?:-(?:rc|alpha)(?:\.[0-9]+)?)?",
);

/// The regex fragment a STRUCTURAL placeholder name denotes, or `None` when
/// the name is not one of the closed structural vocabulary.
///
/// A structural token names a segment whose LEXICAL FORM a released spec
/// defines, so the matcher asserts that grammar instead of an identity, and it
/// OUTRANKS a same-named case variable: the two names below are server-assigned
/// or resolved identities that no request argument spells and that the response
/// itself is the source of, so binding either would compare the response with
/// itself. Every other name must resolve to a case variable.
#[must_use]
pub fn structural_token(name: &str) -> Option<&'static str> {
    match name {
        "n" => Some(VERSION_TREE_ID),
        // NOTE: BASE base_types master05 §Syntaxes — `object_id` and
        // `creating_system_id` are BOTH `uid`, and neither is spelled by a
        // request argument (server-assigned / a deployment fact).
        "system_id" | "versioned_object_uid" => Some(UID),
        // NOTE: AM Identification master03 §HRID — the stored ADL2 template
        // identity is the RESOLVED HRID no request argument spells; an ADL 1.4
        // `template_id` is a free string, so that name stays case-variable.
        "template_hrid" => Some(ARCHETYPE_HRID),
        _ => None,
    }
}

/// Substitute `<name>` placeholders in a matcher pattern.
///
/// A structural token ([`structural_token`]) inserts its released grammar; any
/// other name inserts the regex-escaped scalar of the same-named case variable.
/// A placeholder that is neither is a loud error, never a silent `.*` wildcard,
/// because a matcher like `W/"<versioned_object_uid>::…"` degrading to a
/// near-tautology asserts nothing.
///
/// # Errors
/// The name of the first placeholder that is neither a case variable nor a
/// structural token.
fn resolve_placeholders(pattern: &str, vars: &VarStore) -> Result<String, String> {
    let mut out = String::new();
    let mut rest = pattern;
    while let Some(start) = rest.find('<') {
        let (head, tail) = rest.split_at(start);
        out.push_str(head);
        if let Some(end) = tail.find('>') {
            let name = tail.get(1..end).unwrap_or_default();
            let captured = crate::ids::CaptureName::parse(name)
                .ok()
                .and_then(|n| vars.scalar(&n).map(str::to_owned));
            match (structural_token(name), captured) {
                (Some(grammar), _) => out.push_str(grammar),
                (None, Some(value)) => out.push_str(&regex::escape(&value)),
                (None, None) => return Err(name.to_owned()),
            }
            rest = tail.get(end + 1..).unwrap_or_default();
        } else {
            out.push_str(tail);
            rest = "";
        }
    }
    out.push_str(rest);
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::exec::state::Captured;
    use crate::ids::CaptureName;

    fn expectation(headers_yaml: &serde_json::Value) -> WireExpectation {
        serde_json::from_value(serde_json::json!({
            "status": 200,
            "headers": headers_yaml
        }))
        .unwrap()
    }

    fn response(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
            .collect()
    }

    fn ctx<'a>() -> RequestContext<'a> {
        RequestContext::default()
    }

    fn versions(its_rest: &str) -> SpecVersions {
        SpecVersions {
            its_rest: Some(its_rest.to_owned()),
            ..SpecVersions::default()
        }
    }

    #[test]
    fn present_and_absent_are_enforced() {
        let e = expectation(&serde_json::json!({ "ETag": "present", "Location": "absent" }));
        let ok = response(&[("etag", "W/\"x::sys::1\"")]);
        assert!(evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty());

        let bad = response(&[("location", "/somewhere")]);
        let failures = evaluate(&e, &bad, None, &ctx(), &VarStore::default());
        assert_eq!(failures.len(), 2, "{failures:?}");
        assert!(failures[0].contains("ETag"));
        assert!(failures[1].contains("Location"));
    }

    #[test]
    fn present_optional_never_fails() {
        let e = expectation(&serde_json::json!({ "Preference-Applied": "present?" }));
        assert!(evaluate(&e, &response(&[]), None, &ctx(), &VarStore::default()).is_empty());
    }

    /// `present-with-body` is the exact shape of the `Resources.md` §JSON
    /// Format sentence: the `Content-Type` MUST binds a response that carries
    /// content, and the "unless the response has no content body" clause makes
    /// a body-less response carry no criterion at all.
    #[test]
    fn present_with_body_binds_only_a_response_that_carries_content() {
        let e = expectation(&serde_json::json!({ "Content-Type": "present-with-body" }));
        let detail = serde_json::json!({ "message": "Error message" });

        let typed = response(&[("content-type", "application/json")]);
        assert!(evaluate(&e, &typed, Some(&detail), &ctx(), &VarStore::default()).is_empty());

        let untyped = evaluate(
            &e,
            &response(&[]),
            Some(&detail),
            &ctx(),
            &VarStore::default(),
        );
        assert_eq!(untyped.len(), 1, "{untyped:?}");
        assert!(untyped[0].contains("carries a content body"), "{untyped:?}");
        // A blank value is no declaration either.
        let blank = response(&[("content-type", "  ")]);
        assert_eq!(
            evaluate(&e, &blank, Some(&detail), &ctx(), &VarStore::default()).len(),
            1
        );

        // No body: no criterion, whether or not the header is there.
        assert!(evaluate(&e, &response(&[]), None, &ctx(), &VarStore::default()).is_empty());
        assert!(evaluate(&e, &typed, None, &ctx(), &VarStore::default()).is_empty());
        // The same three shapes the body selectors treat as no content.
        for empty in [serde_json::Value::Null, serde_json::json!("   ")] {
            assert!(
                evaluate(
                    &e,
                    &response(&[]),
                    Some(&empty),
                    &ctx(),
                    &VarStore::default()
                )
                .is_empty(),
                "{empty} is not a content body"
            );
        }
    }

    /// The media-type half of the error-body criterion accepts every spelling
    /// RFC 9110 §8.3 permits for one declared type — the parameter list and the
    /// case of the type name are both the sender's choice — and refuses a
    /// different type. A pattern that failed on `charset` would redden every
    /// conformant 400 row it is declared on.
    #[test]
    fn the_error_body_media_type_pattern_accepts_the_declared_type_only() {
        let e = expectation(&serde_json::json!({
            "Content-Type": { "match": "pattern:(?i)application/json(?:\\s*;.*)?", "optional": true }
        }));
        for value in [
            "application/json",
            "application/json; charset=utf-8",
            "application/json;charset=UTF-8",
            "Application/JSON",
        ] {
            let ok = response(&[("content-type", value)]);
            assert!(
                evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty(),
                "{value} is the declared type"
            );
        }
        for value in ["application/xml", "text/plain", "application/jsonx"] {
            let bad = response(&[("content-type", value)]);
            assert_eq!(
                evaluate(&e, &bad, None, &ctx(), &VarStore::default()).len(),
                1,
                "{value} is not the declared type"
            );
        }
        // Optional presence: an absent header is the presence criterion's
        // business, never this one's.
        assert!(evaluate(&e, &response(&[]), None, &ctx(), &VarStore::default()).is_empty());
    }

    /// Several expectations on ONE header are all judged, each keeping its own
    /// strength and its own dating: the 412 `ETag` carries the latest
    /// `version_uid` for every release (overview §"If-Match and accidental
    /// overwrites") and the `W/` weakness indicator from Release 1.1.0
    /// (§"Deprecated headers").
    #[test]
    fn a_header_sequence_judges_every_declared_expectation() {
        let e = expectation(&serde_json::json!({
            "ETag": [
                "latest-version-uid",
                { "match": "pattern:W/\"[^\"]+\"", "applies": { "its_rest": ">=1.1.0" } }
            ]
        }));
        let v11 = versions("1.1.0");
        let judged = RequestContext {
            last_version_uid: Some("abc::sys::2"),
            spec_versions: Some(&v11),
            ..RequestContext::default()
        };

        let weak = response(&[("etag", "W/\"abc::sys::2\"")]);
        assert!(evaluate(&e, &weak, None, &judged, &VarStore::default()).is_empty());

        // The bare form carries the right identity and still fails the dated
        // form rule, so only the second expectation reports.
        let bare = response(&[("etag", "\"abc::sys::2\"")]);
        let failures = evaluate(&e, &bare, None, &judged, &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(failures[0].contains("does not match"), "{failures:?}");

        // A 1.0.3 declarant is out of scope for the dated form rule, and the
        // undated identity rule still bites on a stale tag.
        let v103 = versions("1.0.3");
        let dated_out = RequestContext {
            last_version_uid: Some("abc::sys::2"),
            spec_versions: Some(&v103),
            ..RequestContext::default()
        };
        assert!(evaluate(&e, &bare, None, &dated_out, &VarStore::default()).is_empty());
        let stale = response(&[("etag", "\"abc::sys::1\"")]);
        let failures = evaluate(&e, &stale, None, &dated_out, &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(failures[0].contains("latest version uid"), "{failures:?}");
    }

    #[test]
    fn negotiated_compares_the_media_token() {
        let e = expectation(&serde_json::json!({ "Content-Type": "negotiated" }));
        let ctx = RequestContext {
            accept: Some("application/json"),
            ..RequestContext::default()
        };
        let ok = response(&[("content-type", "application/json; charset=utf-8")]);
        assert!(evaluate(&e, &ok, None, &ctx, &VarStore::default()).is_empty());
        let bad = response(&[("content-type", "application/openehr.wt+json")]);
        assert_eq!(
            evaluate(&e, &bad, None, &ctx, &VarStore::default()).len(),
            1
        );
    }

    #[test]
    fn latest_version_uid_compares_case_insensitively() {
        let e = expectation(&serde_json::json!({ "ETag": "latest-version-uid" }));
        let ctx = RequestContext {
            last_version_uid: Some("abc::sys::2"),
            ..RequestContext::default()
        };
        // BASE master05 §Composite Identifiers and Case: case differences name
        // the same identifier.
        let ok = response(&[("etag", "W/\"ABC::SYS::2\"")]);
        assert!(evaluate(&e, &ok, None, &ctx, &VarStore::default()).is_empty());
        let stale = response(&[("etag", "W/\"abc::sys::1\"")]);
        assert_eq!(
            evaluate(&e, &stale, None, &ctx, &VarStore::default()).len(),
            1
        );
        let missing = response(&[]);
        assert_eq!(
            evaluate(&e, &missing, None, &ctx, &VarStore::default()).len(),
            1
        );
    }

    #[test]
    fn pattern_resolves_placeholders_from_vars() {
        // `contribution_uid` is an identity name, so the case variable is what
        // the matcher pins.
        let e = expectation(&serde_json::json!({
            "ETag": "pattern:W/\"<contribution_uid>::<system_id>::<n>\""
        }));
        let mut vars = VarStore::default();
        vars.set(
            CaptureName::parse("contribution_uid").unwrap(),
            Captured::Scalar("abc-123".to_owned()),
        );
        let ok = response(&[("etag", "W/\"abc-123::any.system::2\"")]);
        assert!(evaluate(&e, &ok, None, &ctx(), &vars).is_empty());
        // A different resolved uid fails; the structural tokens resolve to
        // their grammars, never to a `.*` wildcard.
        let bad = response(&[("etag", "W/\"other-uid::any.system::2\"")]);
        assert_eq!(evaluate(&e, &bad, None, &ctx(), &vars).len(), 1);
        let empty_system = response(&[("etag", "W/\"abc-123::::2\"")]);
        assert_eq!(evaluate(&e, &empty_system, None, &ctx(), &vars).len(), 1);
        let zero_led = response(&[("etag", "W/\"abc-123::any.system::02\"")]);
        assert_eq!(evaluate(&e, &zero_led, None, &ctx(), &vars).len(), 1);
    }

    /// The `object_id` segment is the BASE `base_types` master05 §Syntaxes
    /// `uid` (UUID, ISO OID, or reverse-domain internet id) and nothing else,
    /// so a create-time `ETag` whose container id is server-assigned is still a
    /// real assertion rather than a refusal.
    #[test]
    fn object_id_token_is_the_released_uid_grammar() {
        let e = expectation(&serde_json::json!({
            "ETag": "pattern:W/\"<versioned_object_uid>::<system_id>::1\""
        }));
        for uid in [
            "019fcd81-9968-7511-90d8-9f9750ea042a",
            "1.2.840.113554.1.2.2",
            "uk.nhs.ehr1",
            "a",
        ] {
            let etag = format!("W/\"{uid}::ferroehr.local::1\"");
            let ok = response(&[("etag", etag.as_str())]);
            assert!(
                evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty(),
                "{uid} is a released uid form"
            );
        }
        for payload in ["::ferroehr.local::1", "-bad::ferroehr.local::1"] {
            let etag = format!("W/\"{payload}\"");
            let bad = response(&[("etag", etag.as_str())]);
            assert_eq!(
                evaluate(&e, &bad, None, &ctx(), &VarStore::default()).len(),
                1,
                "{payload} is not a released uid form"
            );
        }
    }

    /// `creating_system_id` is the SAME `uid` production as `object_id`
    /// (BASE `base_types` master05 §Syntaxes), so the emitting system's id is
    /// asserted as that grammar rather than as "any `::`-free text".
    #[test]
    fn system_id_token_is_the_released_uid_grammar() {
        let e = expectation(&serde_json::json!({ "ETag": "pattern:W/\"<system_id>\"" }));
        for system_id in [
            "ferroehr.local",
            "openEHRSys.example.com",
            "uk.nhs.ehr1",
            "1.2.840.113554",
            "8849182c-82ad-4088-a07f-48ead4180515",
        ] {
            let etag = format!("W/\"{system_id}\"");
            let ok = response(&[("etag", etag.as_str())]);
            assert!(
                evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty(),
                "{system_id} is a released uid form"
            );
        }
        for payload in ["a::b", "sys\\\"tem", "not a uid!", ""] {
            let etag = format!("W/\"{payload}\"");
            let bad = response(&[("etag", etag.as_str())]);
            assert_eq!(
                evaluate(&e, &bad, None, &ctx(), &VarStore::default()).len(),
                1,
                "{payload} is not a released uid form"
            );
        }
    }

    /// A structural token outranks a same-named case variable. A step may pass
    /// a full version uid as the `versioned_object_uid` path argument, which
    /// `operations/composition_get.yaml` expressly permits, and substituting it
    /// into the matcher would produce a doubled `::sys::n` tail.
    #[test]
    fn structural_tokens_outrank_a_same_named_variable() {
        let e = expectation(&serde_json::json!({
            "ETag": "pattern:W/\"<versioned_object_uid>::<system_id>::<n>\""
        }));
        let mut vars = VarStore::default();
        vars.set(
            CaptureName::parse("versioned_object_uid").unwrap(),
            Captured::Scalar("019fcd6c-d514-7703-9491-b2c8d8413408::ferroehr.local::1".to_owned()),
        );
        let ok = response(&[(
            "etag",
            "W/\"019fcd6c-d514-7703-9491-b2c8d8413408::ferroehr.local::1\"",
        )]);
        assert!(evaluate(&e, &ok, None, &ctx(), &vars).is_empty());
    }

    /// `<template_hrid>` is the AM Identification master03 §Human-readable
    /// Identifier form (with the master04 release version), so the ADL2
    /// upload/read `ETag` asserts the RESOLVED HRID rather than the possibly
    /// partial prefix the request addressed.
    #[test]
    fn template_hrid_token_is_the_archetype_hrid_grammar() {
        let e = expectation(&serde_json::json!({ "ETag": "pattern:W/\"<template_hrid>\"" }));
        for hrid in [
            "openEHR-EHR-COMPOSITION.cnf_minimal.v1.0.0",
            "org.openehr::openEHR-EHR-OBSERVATION.blood_pressure.v2.1.0",
            "openEHR-EHR-COMPOSITION.cnf_minimal.v1.0.0-rc.3",
        ] {
            let etag = format!("W/\"{hrid}\"");
            let ok = response(&[("etag", etag.as_str())]);
            assert!(
                evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty(),
                "{hrid} is a released HRID"
            );
        }
        // The ADDRESSED prefix is not the resolved HRID: no release version.
        let prefix = response(&[("etag", "W/\"openEHR-EHR-COMPOSITION.cnf_minimal.v1\"")]);
        assert_eq!(
            evaluate(&e, &prefix, None, &ctx(), &VarStore::default()).len(),
            1
        );
    }

    /// A placeholder naming neither a case variable nor a structural token is a
    /// loud failure, never a silent `.*` that turns the matcher into a
    /// tautology.
    #[test]
    fn unresolvable_placeholder_is_a_loud_failure_not_a_wildcard() {
        let e = expectation(&serde_json::json!({
            "ETag": "pattern:W/\"<no_such_capture>::x\""
        }));
        // The observed value would MATCH a `.*` degradation — the failure
        // must come from the refusal, not from a mismatch.
        let would_pass = response(&[("etag", "W/\"anything::x\"")]);
        let failures = evaluate(&e, &would_pass, None, &ctx(), &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(
            failures[0].contains("no_such_capture") && failures[0].contains("FerroEHR#1852"),
            "the failure names the unresolvable placeholder: {failures:?}"
        );
    }

    #[test]
    fn literal_renders_the_template() {
        let e = expectation(&serde_json::json!({ "Preference-Applied": "return=minimal" }));
        let ok = response(&[("preference-applied", "return=minimal")]);
        assert!(evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty());
        let bad = response(&[("preference-applied", "return=representation")]);
        assert_eq!(
            evaluate(&e, &bad, None, &ctx(), &VarStore::default()).len(),
            1
        );
    }

    #[test]
    fn header_lookup_is_case_insensitive() {
        let e = expectation(&serde_json::json!({ "Last-Modified": "present" }));
        let ok = response(&[("LAST-MODIFIED", "Wed, 22 Jul 2009 19:15:56 GMT")]);
        assert!(evaluate(&e, &ok, None, &ctx(), &VarStore::default()).is_empty());
    }

    /// `optional: true` splits SHOULD-strength presence from MUST-strength
    /// form: the query `ETag` is a SHOULD to emit (overview §"`ETag` and
    /// Last-Modified") but a MUST to weaken when emitted (§"Deprecated
    /// headers"). An omitted header passes; a malformed one still fails.
    #[test]
    fn optional_presence_still_judges_the_form_when_present() {
        let e = expectation(&serde_json::json!({
            "ETag": { "match": "pattern:W/\"[^\"]+\"", "optional": true }
        }));
        assert!(evaluate(&e, &response(&[]), None, &ctx(), &VarStore::default()).is_empty());
        let blank = response(&[("etag", "   ")]);
        assert!(evaluate(&e, &blank, None, &ctx(), &VarStore::default()).is_empty());
        let weak = response(&[("etag", "W/\"rs-1\"")]);
        assert!(evaluate(&e, &weak, None, &ctx(), &VarStore::default()).is_empty());
        let bare = response(&[("etag", "\"rs-1\"")]);
        assert_eq!(
            evaluate(&e, &bare, None, &ctx(), &VarStore::default()).len(),
            1
        );
    }

    /// A version-dated rule binds only the parties that declare the release
    /// dating it: the `W/` MUST is "Prior to Release 1.1.0" deprecation text,
    /// so a 1.0.3 declarant is not judged on it and a 1.1.0 declarant is, under
    /// the same `applies` grammar and `satisfied_by` polarity the case cores use.
    #[test]
    fn a_dated_expectation_binds_only_the_declaring_releases() {
        let e = expectation(&serde_json::json!({
            "ETag": {
                "match": "pattern:W/\"[^\"]+\"",
                "applies": { "its_rest": ">=1.1.0" }
            }
        }));
        let bare = response(&[("etag", "\"x::sys::1\"")]);

        let v11 = versions("1.1.0");
        let judged = RequestContext {
            spec_versions: Some(&v11),
            ..RequestContext::default()
        };
        assert_eq!(
            evaluate(&e, &bare, None, &judged, &VarStore::default()).len(),
            1
        );

        let v103 = versions("1.0.3");
        let dated_out = RequestContext {
            spec_versions: Some(&v103),
            ..RequestContext::default()
        };
        assert!(evaluate(&e, &bare, None, &dated_out, &VarStore::default()).is_empty());

        // Undeclared behaves as the case-level filter does: out of scope.
        assert!(evaluate(&e, &bare, None, &ctx(), &VarStore::default()).is_empty());
    }

    /// The two modifiers are independent: dating gates whether the rule is
    /// consulted at all, optionality gates whether an absent header is a
    /// violation.
    #[test]
    fn dating_and_optionality_compose() {
        let e = expectation(&serde_json::json!({
            "ETag": {
                "match": "pattern:W/\"[^\"]+\"",
                "optional": true,
                "applies": { "its_rest": ">=1.1.0" }
            }
        }));
        let v11 = versions("1.1.0");
        let judged = RequestContext {
            spec_versions: Some(&v11),
            ..RequestContext::default()
        };
        assert!(evaluate(&e, &response(&[]), None, &judged, &VarStore::default()).is_empty());
        let bare = response(&[("etag", "\"rs-1\"")]);
        assert_eq!(
            evaluate(&e, &bare, None, &judged, &VarStore::default()).len(),
            1
        );
    }

    /// `negotiated` has nothing sound to compare against when the driver sent
    /// no `Accept`: the endpoint default was negotiated, so the matcher passes
    /// rather than inventing an expected media type.
    #[test]
    fn negotiated_without_an_accept_asserts_nothing() {
        let e = expectation(&serde_json::json!({ "Content-Type": "negotiated" }));
        let any = response(&[("content-type", "application/xml")]);
        assert!(evaluate(&e, &any, None, &ctx(), &VarStore::default()).is_empty());

        // A missing content type is its own failure line, distinct from the
        // mismatch one, so a red row says which happened.
        let negotiating = RequestContext {
            accept: Some("application/xml"),
            ..RequestContext::default()
        };
        let failures = evaluate(&e, &response(&[]), None, &negotiating, &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(failures[0].ends_with("got none"), "{failures:?}");
    }

    /// The stale-precondition rule degrades honestly: an empty entity tag is a
    /// failure, and a row that committed nothing to compare against falls back
    /// to presence rather than manufacturing a red row.
    #[test]
    fn the_latest_version_uid_matcher_degrades_to_presence() {
        let e = expectation(&serde_json::json!({ "ETag": "latest-version-uid" }));

        let empty = response(&[("etag", "W/\"\"")]);
        let with_uid = RequestContext {
            last_version_uid: Some("abc::sys::2"),
            ..RequestContext::default()
        };
        let failures = evaluate(&e, &empty, None, &with_uid, &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(failures[0].contains("empty entity tag"), "{failures:?}");

        // With nothing tracked to compare against, any non-empty tag passes.
        let anything = response(&[("etag", "\"whatever\"")]);
        assert!(evaluate(&e, &anything, None, &ctx(), &VarStore::default()).is_empty());
        assert_eq!(
            evaluate(&e, &empty, None, &ctx(), &VarStore::default()).len(),
            1
        );
    }

    /// A `pattern:` and a literal expectation both report their own
    /// missing-value line, so an absent header never reads as a form mismatch.
    #[test]
    fn a_missing_value_is_reported_by_pattern_and_literal_alike() {
        let pattern = expectation(&serde_json::json!({ "ETag": "pattern:W/\"[^\"]+\"" }));
        let failures = evaluate(&pattern, &response(&[]), None, &ctx(), &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(failures[0].contains("got none"), "{failures:?}");

        let literal = expectation(&serde_json::json!({ "Location": "/ehr/x" }));
        let failures = evaluate(&literal, &response(&[]), None, &ctx(), &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert_eq!(failures[0], "header Location: expected a value, got none");
    }

    /// A literal whose `${…}` template cannot resolve is reported as an
    /// unresolvable declaration: the value the binding declares was never
    /// checked, which must never read as the server matching it.
    #[test]
    fn an_unresolvable_literal_template_is_reported_as_uncheckable() {
        let e = expectation(&serde_json::json!({ "Location": "/ehr/${ehr_id}" }));
        let observed = response(&[("location", "/ehr/anything")]);
        let failures = evaluate(&e, &observed, None, &ctx(), &VarStore::default());
        assert_eq!(failures.len(), 1, "{failures:?}");
        assert!(
            failures[0].contains("literal template unresolvable"),
            "{failures:?}"
        );

        // Bound, the same declaration is an exact-match assertion.
        let mut vars = VarStore::default();
        vars.set(
            CaptureName::parse("ehr_id").unwrap(),
            Captured::Scalar("anything".to_owned()),
        );
        assert!(evaluate(&e, &observed, None, &ctx(), &vars).is_empty());
    }

    /// An unterminated `<` is not a placeholder: it stays in the pattern
    /// verbatim, so a mis-authored matcher fails loudly on the value it does
    /// not match instead of silently dropping the rest of the expectation.
    #[test]
    fn an_unterminated_placeholder_stays_in_the_pattern() {
        let e = expectation(&serde_json::json!({ "ETag": "pattern:W/\"<n\"" }));
        let literal_tail = response(&[("etag", "W/\"<n\"")]);
        assert!(evaluate(&e, &literal_tail, None, &ctx(), &VarStore::default()).is_empty());
        let resolved_as_grammar = response(&[("etag", "W/\"2\"")]);
        assert_eq!(
            evaluate(&e, &resolved_as_grammar, None, &ctx(), &VarStore::default()).len(),
            1,
            "an unterminated `<n` never resolves to the version-tree grammar"
        );
    }
}