veredictum 0.1.3

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

//! Shields.io badge endpoints, derived from the verdict report.
//!
//! A badge is a pure function of `(VerdictReport, CapabilityMatrix, case
//! counts)` — the same inputs the verdict pipeline already takes — so it is
//! computed here, beside the tier predicates, rather than re-derived by
//! whatever publishes it.
//!
//! The count a badge shows quantifies over
//! [`crate::verdict::tier_members`], the same capability set its
//! verdict is judged on, with the same `Passed` evidence predicate. That is what
//! makes a badge like `FAIL 5/5 capabilities` unrepresentable rather than merely
//! guarded against: there is one rule, so there is nothing for a second
//! derivation to contradict.
//!
//! No openEHR spec governs badges — our own publication surface.

#![allow(
    clippy::disallowed_types,
    reason = "the JSON carriers here are cfg(test)-only fixtures over the catalogue \
              artifacts (dev/verification tooling), so #[expect] would be unfulfilled in \
              the non-test build"
)]

use serde::Serialize;

use crate::ids::CapabilityName;
use crate::model::capability::CapabilityMatrix;
use crate::party::{OutcomeStatus, Results};
use crate::perf::{ClassVerdict, PerfClass};
use crate::verdict::{
    Evidence, PerformanceVerdict, ProfileVerdict, SecBasicVerdict, VerdictReport, tier_members,
};
use crate::vocab::Tier;

/// A shields.io endpoint document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Badge {
    /// The endpoint-schema version shields.io expects.
    #[serde(rename = "schemaVersion")]
    pub schema_version: u8,
    /// The badge's left-hand label.
    pub label: String,
    /// The badge's right-hand message.
    pub message: String,
    /// The badge colour.
    pub color: String,
}

/// A badge together with the file it publishes as.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedBadge {
    /// File name, relative to the run's output directory.
    pub file: String,
    /// The endpoint document.
    pub badge: Badge,
}

/// The per-case status counts the overall badge reads.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct CaseCounts {
    /// Cases whose outcome was `passed`.
    pub passed: usize,
    /// Cases whose outcome was `failed`.
    pub failed: usize,
    /// Cases whose outcome was `errored`.
    pub errored: usize,
}

impl CaseCounts {
    /// The counts a results document reports.
    #[must_use]
    pub fn of(results: &Results) -> Self {
        let count = |status: OutcomeStatus| {
            results
                .outcomes
                .iter()
                .filter(|o| o.status == status)
                .count()
        };
        Self {
            passed: count(OutcomeStatus::Passed),
            failed: count(OutcomeStatus::Failed),
            errored: count(OutcomeStatus::Errored),
        }
    }

    /// Cases the run actually drove — the denominator the overall badge shows.
    #[must_use]
    pub const fn driven(&self) -> usize {
        self.passed + self.failed + self.errored
    }

    /// Rows that are red in any sense.
    #[must_use]
    pub const fn red(&self) -> usize {
        self.failed + self.errored
    }
}

/// Every badge for a run, in publication order.
#[must_use]
pub fn badges(
    report: &VerdictReport,
    matrix: &CapabilityMatrix,
    cases: CaseCounts,
) -> Vec<NamedBadge> {
    let mut out: Vec<NamedBadge> = report
        .profiles
        .iter()
        .map(|(tier, verdict)| profile_badge(*tier, *verdict, report, matrix))
        .collect();
    if let Some(security) = report.security {
        out.push(security_badge(security, report, matrix));
    }
    out.push(performance_badge(&report.performance));
    out.push(overall_badge(&report.profiles, cases));
    out
}

/// The badge for one platform profile.
///
/// A `NOT CLAIMED` tier shows no count: a count is only meaningful beside a
/// computed verdict, and `NOT CLAIMED 3/5` invites the misread a bare token
/// avoids.
fn profile_badge(
    tier: Tier,
    verdict: ProfileVerdict,
    report: &VerdictReport,
    matrix: &CapabilityMatrix,
) -> NamedBadge {
    let members = tier_members(tier, matrix);
    let token = token_of(verdict);
    let noun = if tier == Tier::Options {
        "optional capabilities"
    } else {
        "capabilities"
    };
    let amount = if members.is_empty() || verdict == ProfileVerdict::NotClaimed {
        String::new()
    } else {
        format!(
            " {}/{} {noun}",
            passed_count(report, &members),
            members.len()
        )
    };
    NamedBadge {
        file: format!("badge-{}.json", slug(tier)),
        badge: Badge {
            schema_version: 1,
            label: format!("openEHR CNF {}", label(tier)),
            message: format!("{}{amount}", shout(token)),
            color: colour(token).to_owned(),
        },
    }
}

/// The SEC-BASIC badge, over the required Security-family capabilities.
fn security_badge(
    verdict: SecBasicVerdict,
    report: &VerdictReport,
    matrix: &CapabilityMatrix,
) -> NamedBadge {
    let members = tier_members(Tier::SecBasic, matrix);
    let token = match verdict {
        SecBasicVerdict::Pass => "pass",
        SecBasicVerdict::Fail => "fail",
    };
    NamedBadge {
        file: "badge-sec-basic.json".to_owned(),
        badge: Badge {
            schema_version: 1,
            label: "openEHR CNF SEC-BASIC".to_owned(),
            message: format!(
                "{} {}/{} capabilities",
                shout(token),
                passed_count(report, &members),
                members.len()
            ),
            color: colour(token).to_owned(),
        },
    }
}

/// The measured-performance badge.
///
/// It always NAMES the class it speaks about: a bare verdict is meaningless
/// without the volumetric class it was measured against. An un-measured run says
/// so, rather than letting a stale badge outlive its record.
fn performance_badge(performance: &[PerformanceVerdict]) -> NamedBadge {
    let highest = |classes: Vec<PerfClass>| -> Option<PerfClass> {
        // `PerfClass::ALL` is the ladder in ascending order, so its index IS the
        // rank — no second ordering to keep in step with it.
        PerfClass::ALL
            .iter()
            .rev()
            .find(|c| classes.contains(c))
            .copied()
    };
    let earned = highest(
        performance
            .iter()
            .filter(|p| p.verdict == ClassVerdict::Earned)
            .map(|p| p.class)
            .collect(),
    );
    let measured = highest(performance.iter().map(|p| p.class).collect());
    let (message, color) = match (earned, measured) {
        (Some(class), _) => (format!("class {} earned", class.token()), "brightgreen"),
        (None, Some(class)) => (format!("class {} not earned", class.token()), "red"),
        (None, None) => ("not measured".to_owned(), "lightgrey"),
    };
    NamedBadge {
        file: "badge-performance.json".to_owned(),
        badge: Badge {
            schema_version: 1,
            label: "openEHR CNF performance".to_owned(),
            message,
            color: color.to_owned(),
        },
    }
}

/// The overall badge.
///
/// Full green ONLY on a completely clean run: a red row anywhere — even in an
/// OPTIONS-tier capability that cannot fail CORE or STANDARD — is never an
/// acceptable resting state, because green comes from fixing the guilty
/// component and a brightgreen badge over a visible failure invites a misread. A
/// passing-tier run with red rows goes yellow and names the count.
fn overall_badge(profiles: &[(Tier, ProfileVerdict)], cases: CaseCounts) -> NamedBadge {
    let passing = |tier: Tier| {
        profiles
            .iter()
            .any(|(t, v)| *t == tier && *v == ProfileVerdict::Pass)
    };
    let tiers_pass = passing(Tier::Core) && passing(Tier::Standard);
    let driven = cases.driven();
    let passed = cases.passed;
    let (message, color) = if tiers_pass && cases.red() == 0 {
        (
            format!("CORE+STANDARD PASS · {passed}/{driven} cases"),
            "brightgreen",
        )
    } else if tiers_pass {
        (
            format!(
                "CORE+STANDARD PASS · {passed}/{driven} cases ({} failing)",
                cases.red()
            ),
            "yellow",
        )
    } else {
        (format!("NOT PASSING · {passed}/{driven} cases"), "red")
    };
    NamedBadge {
        file: "badge.json".to_owned(),
        badge: Badge {
            schema_version: 1,
            label: "openEHR conformance".to_owned(),
            message,
            color: color.to_owned(),
        },
    }
}

/// How many of `members` carry executed passing evidence.
///
/// The predicate is `Evidence::Passed` and nothing else, matching
/// `required_all_passed`: an excused or unrealized capability does not satisfy
/// its tier, so it must not be counted as if it did.
fn passed_count(report: &VerdictReport, members: &[CapabilityName]) -> usize {
    members
        .iter()
        .filter(|name| {
            report
                .capabilities
                .iter()
                .any(|(n, e)| n == *name && *e == Evidence::Passed)
        })
        .count()
}

const fn token_of(verdict: ProfileVerdict) -> &'static str {
    match verdict {
        ProfileVerdict::Pass => "pass",
        ProfileVerdict::Fail => "fail",
        ProfileVerdict::NotClaimed => "not_claimed",
    }
}

fn shout(token: &str) -> String {
    token.to_uppercase().replace('_', " ")
}

fn colour(token: &str) -> &'static str {
    match token {
        "pass" => "brightgreen",
        "fail" => "red",
        _ => "lightgrey",
    }
}

const fn slug(tier: Tier) -> &'static str {
    match tier {
        Tier::Core => "core",
        Tier::Standard => "standard",
        Tier::Options => "options",
        Tier::SecBasic => "sec-basic",
        Tier::EnterpriseD => "enterprise-d",
        Tier::EnterpriseM => "enterprise-m",
        Tier::EnterpriseX => "enterprise-x",
    }
}

const fn label(tier: Tier) -> &'static str {
    match tier {
        Tier::Core => "CORE",
        Tier::Standard => "STANDARD",
        Tier::Options => "OPTIONS",
        Tier::SecBasic => "SEC-BASIC",
        Tier::EnterpriseD => "D",
        Tier::EnterpriseM => "M",
        Tier::EnterpriseX => "X",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::verdict::Coverage;

    fn matrix() -> CapabilityMatrix {
        serde_json::from_value(serde_json::json!({
            "EhrOperations":       { "family": "Platform", "tier": "CORE",      "required": true  },
            "CompositionCrud":     { "family": "Platform", "tier": "CORE",      "required": true  },
            "AqlBasic":            { "family": "Platform", "tier": "STANDARD",  "required": true  },
            "SimplifiedFormats":   { "family": "Platform", "tier": "OPTIONS",   "required": false },
            "AuthenticatedAccess": { "family": "Security",  "tier": "SEC-BASIC", "required": true  }
        }))
        .unwrap()
    }

    fn report(
        capabilities: &[(&str, Evidence)],
        profiles: &[(Tier, ProfileVerdict)],
        security: Option<SecBasicVerdict>,
    ) -> VerdictReport {
        VerdictReport {
            review: Vec::new(),
            capabilities: capabilities
                .iter()
                .map(|(n, e)| {
                    (
                        (*n).parse::<CapabilityName>()
                            .expect("test capability name"),
                        *e,
                    )
                })
                .collect(),
            capability_tallies: Vec::new(),
            profiles: profiles.to_vec(),
            security,
            performance: Vec::new(),
            coverage: Coverage {
                selected: 0,
                driven: 0,
                passed: 0,
                failed: 0,
                inconclusive: 0,
            },
        }
    }

    fn message(badges: &[NamedBadge], file: &str) -> String {
        badges
            .iter()
            .find(|b| b.file == file)
            .unwrap_or_else(|| panic!("no {file} badge"))
            .badge
            .message
            .clone()
    }

    fn all_passed() -> Vec<(&'static str, Evidence)> {
        vec![
            ("EhrOperations", Evidence::Passed),
            ("CompositionCrud", Evidence::Passed),
            ("AqlBasic", Evidence::Passed),
            ("SimplifiedFormats", Evidence::Passed),
            ("AuthenticatedAccess", Evidence::Passed),
        ]
    }

    /// The four tier badges on a clean run, each counting the set its verdict
    /// was judged on. STANDARD is CUMULATIVE (3, not 1): a tier-local count
    /// beside a cumulative verdict is the misread this derivation exists to
    /// make impossible.
    #[test]
    fn a_clean_run_counts_the_set_each_verdict_was_judged_on() {
        let out = badges(
            &report(
                &all_passed(),
                &[
                    (Tier::Core, ProfileVerdict::Pass),
                    (Tier::Standard, ProfileVerdict::Pass),
                    (Tier::Options, ProfileVerdict::Pass),
                ],
                Some(SecBasicVerdict::Pass),
            ),
            &matrix(),
            CaseCounts {
                passed: 40,
                failed: 0,
                errored: 0,
            },
        );
        assert_eq!(message(&out, "badge-core.json"), "PASS 2/2 capabilities");
        assert_eq!(
            message(&out, "badge-standard.json"),
            "PASS 3/3 capabilities"
        );
        assert_eq!(
            message(&out, "badge-options.json"),
            "PASS 1/1 optional capabilities"
        );
        assert_eq!(
            message(&out, "badge-sec-basic.json"),
            "PASS 1/1 capabilities"
        );
        assert_eq!(
            message(&out, "badge.json"),
            "CORE+STANDARD PASS · 40/40 cases"
        );
    }

    /// A failing tier's count and its verdict agree BY CONSTRUCTION: the count
    /// falls below the total exactly when the verdict is `fail`, because both
    /// read the same members and the same evidence.
    ///
    /// This is the "FAIL 5/5 capabilities" incident, made unrepresentable. The
    /// shell derivation needed a self-check to catch it; there is nothing here
    /// for a self-check to compare.
    #[test]
    fn a_failing_tier_cannot_show_a_full_count() {
        let mut caps = all_passed();
        caps[1] = ("CompositionCrud", Evidence::Failed);
        let out = badges(
            &report(
                &caps,
                &[
                    (Tier::Core, ProfileVerdict::Fail),
                    (Tier::Standard, ProfileVerdict::Fail),
                    (Tier::Options, ProfileVerdict::Pass),
                ],
                None,
            ),
            &matrix(),
            CaseCounts {
                passed: 38,
                failed: 2,
                errored: 0,
            },
        );
        assert_eq!(message(&out, "badge-core.json"), "FAIL 1/2 capabilities");
        assert_eq!(
            message(&out, "badge-standard.json"),
            "FAIL 2/3 capabilities"
        );
        assert_eq!(
            message(&out, "badge.json"),
            "NOT PASSING · 38/40 cases",
            "a failing tier is never CORE+STANDARD PASS"
        );
    }

    /// A NOT-EVIDENCED capability does not satisfy its tier, so it is not
    /// counted as if it did — the count uses the same `Passed` predicate
    /// `required_all_passed` does, which has no excuse arm (FerroEHR#626).
    #[test]
    fn a_not_evidenced_capability_is_not_counted_as_satisfied() {
        let mut caps = all_passed();
        caps[0] = ("EhrOperations", Evidence::NotEvidenced);
        let out = badges(
            &report(&caps, &[(Tier::Core, ProfileVerdict::Fail)], None),
            &matrix(),
            CaseCounts::default(),
        );
        assert_eq!(message(&out, "badge-core.json"), "FAIL 1/2 capabilities");
    }

    /// A NOT CLAIMED tier shows no count: a count is only meaningful beside a
    /// computed verdict.
    #[test]
    fn a_not_claimed_tier_shows_a_bare_token() {
        let out = badges(
            &report(
                &all_passed(),
                &[(Tier::Standard, ProfileVerdict::NotClaimed)],
                None,
            ),
            &matrix(),
            CaseCounts::default(),
        );
        assert_eq!(message(&out, "badge-standard.json"), "NOT CLAIMED");
    }

    /// A passing pair of tiers with a red row anywhere is YELLOW, never green:
    /// a brightgreen badge over a visible failure is the misread that made the
    /// overall badge worth deriving carefully.
    #[test]
    fn a_red_row_under_passing_tiers_is_yellow_and_named() {
        let out = badges(
            &report(
                &all_passed(),
                &[
                    (Tier::Core, ProfileVerdict::Pass),
                    (Tier::Standard, ProfileVerdict::Pass),
                ],
                None,
            ),
            &matrix(),
            CaseCounts {
                passed: 39,
                failed: 0,
                errored: 1,
            },
        );
        let overall = out
            .iter()
            .find(|b| b.file == "badge.json")
            .expect("overall");
        assert_eq!(
            overall.badge.message,
            "CORE+STANDARD PASS · 39/40 cases (1 failing)"
        );
        assert_eq!(overall.badge.color, "yellow");
    }

    /// An unmeasured run says so, rather than leaving a stale class claim.
    #[test]
    fn performance_names_its_class_or_says_unmeasured() {
        let out = badges(
            &report(&all_passed(), &[], None),
            &matrix(),
            CaseCounts::default(),
        );
        assert_eq!(message(&out, "badge-performance.json"), "not measured");
    }

    /// A measured class that was NOT earned is named in red: the badge says
    /// which class was attempted, so an unearned run never reads as unmeasured.
    #[test]
    fn a_measured_but_unearned_class_is_named_in_red() {
        let mut r = report(&all_passed(), &[], None);
        r.performance = vec![PerformanceVerdict {
            case: crate::ids::CaseId::parse("PERF-hospital_sim-class_S").unwrap(),
            class: PerfClass::S,
            claimed: true,
            verdict: ClassVerdict::NotEarned,
            violations: vec!["error_rate 0.5 > max 0".to_owned()],
        }];
        let out = badges(&r, &matrix(), CaseCounts::default());
        assert_eq!(
            message(&out, "badge-performance.json"),
            "class S not earned"
        );
        let badge = out
            .iter()
            .find(|b| b.file == "badge-performance.json")
            .expect("performance badge");
        assert_eq!(badge.badge.color, "red");
    }

    /// The badge names the highest EARNED class, not the highest measured
    /// one: a run that earned POC while failing S publishes POC.
    #[test]
    fn the_performance_badge_names_the_highest_earned_class() {
        let verdict = |class, verdict| PerformanceVerdict {
            case: crate::ids::CaseId::parse("PERF-hospital_sim-class_x").unwrap(),
            class,
            claimed: true,
            verdict,
            violations: Vec::new(),
        };
        let mut r = report(&all_passed(), &[], None);
        r.performance = vec![
            verdict(PerfClass::Poc, ClassVerdict::Earned),
            verdict(PerfClass::S, ClassVerdict::NotEarned),
        ];
        let out = badges(&r, &matrix(), CaseCounts::default());
        assert_eq!(message(&out, "badge-performance.json"), "class POC earned");
        let badge = out
            .iter()
            .find(|b| b.file == "badge-performance.json")
            .expect("performance badge");
        assert_eq!(badge.badge.color, "brightgreen");
    }

    /// A failing SEC-BASIC verdict renders as `fail`, and the badge still
    /// carries the member count its verdict was judged on.
    #[test]
    fn a_failing_sec_basic_verdict_renders_as_fail() {
        let out = badges(
            &report(
                &[("AuthenticatedAccess", Evidence::Failed)],
                &[],
                Some(SecBasicVerdict::Fail),
            ),
            &matrix(),
            CaseCounts::default(),
        );
        assert_eq!(
            message(&out, "badge-sec-basic.json"),
            "FAIL 0/1 capabilities"
        );
    }

    /// Every tier has its own file slug and its own display label, so two
    /// badges can never overwrite each other or claim each other's tier.
    #[test]
    fn every_tier_carries_a_distinct_badge_slug_and_label() {
        let slugs: std::collections::BTreeSet<&str> = Tier::ALL.iter().map(|t| slug(*t)).collect();
        let labels: std::collections::BTreeSet<&str> =
            Tier::ALL.iter().map(|t| label(*t)).collect();
        assert_eq!(slugs.len(), Tier::ALL.len());
        assert_eq!(labels.len(), Tier::ALL.len());
        assert_eq!(slug(Tier::EnterpriseD), "enterprise-d");
        assert_eq!(label(Tier::EnterpriseX), "X");
    }
}