veredictum 0.1.0-alpha.1

The independent conformance instrument for openEHR clinical data repositories: a machine-readable catalogue of spec-cited test cases, executed against any running CDR, judged by pure-function verdicts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
// SPDX-FileCopyrightText: Veredictum contributors
// SPDX-License-Identifier: Apache-2.0

//! The CNF 2.0 reference runner CLI.
//!
//! ```text
//! veredictum emit-schemas --out DIR     write the published JSON-Schema set
//! veredictum validate --root DIR [--specs DIR]
//! veredictum run --root DIR --ixit FILE --out DIR [--sut-name N] [--sut-version V] [--statement F]
//!                                       validate an artifact tree (all gates);
//!                                       --specs enables the SM/spec-ref
//!                                       resolution checks against the vendored
//!                                       spec tree (specs/openehr). The
//!                                       committed party statements beside the
//!                                       root (<root>/../party/*/statement.json)
//!                                       are swept in for the claim gates.
//! veredictum verdicts --statement F --results F --root DIR --out DIR
//!                                       compute the verdicts (pure pipeline)
//!                                       and write the report/statement/
//!                                       certificate + verdicts.json
//! veredictum perf --root DIR --ixit FILE --results FILE --class POC|S|L|R
//!                 [--hours 1|2|4|6|8|12] [--seed-workers N]
//!                                       the measured class run (conformance-
//!                                       by-measurement): seed the scale
//!                                       corpus, hold the class's offered
//!                                       load for the sustained window, merge
//!                                       the record into results.json
//! veredictum stress --root DIR --ixit FILE --out FILE
//!                   [--corpus-class POC|S|L|R]
//!                   [--step-secs N] [--bisections N] [--max-rate R]
//!                                       the step-load stress ladder to the
//!                                       maximum sustainable throughput
//!                                       (exploration only — writes
//!                                       stress.json, never results.json)
//! veredictum aql-probe --root DIR --ixit FILE --out FILE
//!                      [--corpus-class POC|S|L|R] [--requests N]
//!                                       the seeded-corpus AQL optimization
//!                                       probe: wire percentiles + DB
//!                                       statement attribution (exploration
//!                                       only — never a conformance record)
//! veredictum perf-assets --root DIR --results FILE --out DIR
//!                        [--summary FILE] [--stress FILE]
//!                                       render the published SVGs + summary
//!                                       FROM committed artifacts
//! veredictum conformance-assets --root DIR --results FILE --verdicts FILE
//!                               --out DIR [--suffix=-ehrbase]
//!                                       render the capability heat grid +
//!                                       per-chapter outcome bars FROM the
//!                                       committed party artifacts
//! ```
//!
//! Exit codes: `0` clean · `1` findings · `2` runner error.

#![expect(
    clippy::disallowed_types,
    reason = "dev/verification tooling over JSON artifacts (the catalogue, results, wire \
              exchanges) — not the application (#1694)"
)]
// Verification CLI: progress/diagnostics on the console ARE this tool's user
// interface, so stdio is the right channel here; only library crates are
// restricted to `tracing`.
#![allow(
    clippy::print_stdout,
    clippy::print_stderr,
    reason = "this IS the CLI: stdout carries the run report and stderr the \
              diagnostics; only library crates are restricted to `tracing`"
)]

use std::path::PathBuf;
use std::process::ExitCode;

use clap::{Parser, Subcommand};

use veredictum::artifacts::load_root;
use veredictum::load::compile_schema;
use veredictum::party::{Results, Statement};
use veredictum::render::{render_certificate, render_report, render_statement};
use veredictum::schema::{emit_all, render, results_schema, statement_schema};
use veredictum::validate::{Context, render_coverage_report, validate};
use veredictum::verdict::compute;

#[derive(Parser)]
#[command(
    name = "veredictum",
    about = "The independent conformance instrument for openEHR clinical data repositories",
    version
)]
struct Cli {
    #[command(subcommand)]
    command: Command,
}

#[derive(Subcommand)]
enum Command {
    /// Write the published JSON-Schema set (byte-deterministic).
    EmitSchemas {
        /// Output directory (created if missing).
        #[arg(long)]
        out: PathBuf,
    },
    /// Execute the catalogue against a live SUT (from its ixit topology)
    /// and emit results.json + the run report.
    Run {
        /// The artifact root.
        #[arg(long)]
        root: PathBuf,
        /// The ixit topology file (JSON).
        #[arg(long)]
        ixit: PathBuf,
        /// Output directory for results.json + the run summary.
        #[arg(long)]
        out: PathBuf,
        /// SUT display name.
        #[arg(long, default_value = "ferroehr")]
        sut_name: String,
        /// SUT version label.
        #[arg(long, default_value = "dev")]
        sut_version: String,
        /// Only run cases whose id contains this substring.
        #[arg(long)]
        filter: Option<String>,
        /// The party statement (ICS) — when supplied, option-gated cases
        /// whose option the ICS does not declare are recorded N/A at drive
        /// time (ISO/IEC 9646 test selection) instead of driven.
        #[arg(long)]
        statement: Option<PathBuf>,
    },
    /// Validate one artifact tree through every machine gate.
    Validate {
        /// The artifact root (schedule/, bindings/, vocab/, corpus/, registers/).
        #[arg(long)]
        root: PathBuf,
        /// The vendored openEHR spec tree; enables SM-operation and spec-ref
        /// resolution.
        #[arg(long)]
        specs: Option<PathBuf>,
        /// Also refresh `docs/conformance/coverage-report.md` from `--specs`.
        ///
        /// OFF by default: `validate` is a check verb, and a check that
        /// mutates the working tree is a trap for read-only and fenced
        /// invocations. The pipeline scripts that publish the report pass
        /// this explicitly.
        #[arg(long)]
        write_report: bool,
    },
    /// Execute the performance schedule's open-loop measured run(s) against
    /// a live SUT and merge the §8.10 measurement records into an existing
    /// results.json (conformance-by-measurement).
    Perf {
        /// The artifact root.
        #[arg(long)]
        root: PathBuf,
        /// The ixit topology file (JSON) — its environment block is
        /// mandatory for a measured run.
        #[arg(long)]
        ixit: PathBuf,
        /// The results.json to merge the measurement records into (written
        /// by a prior `run`).
        #[arg(long)]
        results: PathBuf,
        /// Select the performance case(s) of this class (POC | S | L | R).
        #[arg(long)]
        class: String,
        /// Parallel seeding workers.
        #[arg(long, default_value_t = 16)]
        seed_workers: usize,
        /// The sustained-window ladder: hours to hold the offered load —
        /// 1 (default, the case's normative window) | 2 | 4 | 6 | 8 | 12.
        /// A longer window is a STRICTER demonstration and persists like
        /// any measured run; nothing shorter than the case exists.
        #[arg(long, default_value_t = 1)]
        hours: u64,
    },
    /// Run the step-load STRESS instrument: geometric load steps to the
    /// maximum sustainable throughput — where the system breaks
    /// (exploration only; never a conformance record, and class-free by
    /// design).
    Stress {
        /// The artifact root.
        #[arg(long)]
        root: PathBuf,
        /// The ixit topology file (JSON) — its environment block is
        /// mandatory (a throughput number without the deployment described
        /// is meaningless).
        #[arg(long)]
        ixit: PathBuf,
        /// Where to write the stress report (stress.json).
        #[arg(long)]
        out: PathBuf,
        /// The class-scale corpus the stress runs on (POC | S | L | R —
        /// the standardized corpus selector): data volume + workload mix
        /// only; no class floor enters the stress report or chart.
        #[arg(long, default_value = "POC")]
        corpus_class: String,
        /// Parallel seeding workers.
        #[arg(long, default_value_t = 16)]
        seed_workers: usize,
        /// Each load step's recorded hold, seconds (short + intense by
        /// design).
        #[arg(long, default_value_t = 120)]
        step_secs: u64,
        /// Post-breach bisection refinements.
        #[arg(long, default_value_t = 3)]
        bisections: u32,
        /// The climb cap (arrivals/s).
        #[arg(long, default_value_t = 4096.0)]
        max_rate: f64,
    },
    /// Run the AQL optimization probe: fire the measurement machinery's
    /// AQL vocabulary against a live, freshly seeded SUT, record wire
    /// percentiles, and attribute the DB-side cost per probe via
    /// `pg_stat_statements` (exploration evidence for the optimization
    /// loop — never a conformance record).
    AqlProbe {
        /// The artifact root.
        #[arg(long)]
        root: PathBuf,
        /// The ixit topology file (JSON) — the `containers` block enables
        /// DB-side attribution and maintenance settling.
        #[arg(long)]
        ixit: PathBuf,
        /// Where to write the probe report (aql-probe.json).
        #[arg(long)]
        out: PathBuf,
        /// The class-scale corpus the probes run against (POC | S | L | R).
        #[arg(long, default_value = "POC")]
        corpus_class: String,
        /// Parallel seeding workers.
        #[arg(long, default_value_t = 16)]
        seed_workers: usize,
        /// Requests fired per probe.
        #[arg(long, default_value_t = 20)]
        requests: u32,
    },
    /// Render the cross-SUT stress overlay (both systems' latency-throughput
    /// curves on one canvas) FROM two committed stress reports —
    /// deterministic, both directions on equal footing.
    StressCompare {
        /// The primary SUT's committed stress.json.
        #[arg(long)]
        left: PathBuf,
        /// The primary SUT's display label.
        #[arg(long)]
        left_label: String,
        /// The comparison SUT's committed stress.json.
        #[arg(long)]
        right: PathBuf,
        /// The comparison SUT's display label.
        #[arg(long)]
        right_label: String,
        /// Where to write the overlay SVG.
        #[arg(long)]
        out: PathBuf,
    },
    /// Render the published performance SVG assets FROM a committed
    /// results.json (deterministic; CI regenerates and diffs — hand-drawn
    /// numbers are a build failure).
    PerfAssets {
        /// The artifact root (for the class-ladder floors).
        #[arg(long)]
        root: PathBuf,
        /// The committed results.json carrying the measurement records.
        #[arg(long)]
        results: PathBuf,
        /// Output directory for the SVG files.
        #[arg(long)]
        out: PathBuf,
        /// Also write the generated Markdown summary (class ladder +
        /// measured detail) to this path — the book's build-time include.
        #[arg(long)]
        summary: Option<PathBuf>,
        /// A committed stress report (stress.json) to render the
        /// latency-throughput curve from, when one exists.
        #[arg(long)]
        stress: Option<PathBuf>,
    },
    /// Render the conformance visuals (the capability heat grid + the
    /// per-chapter outcome bars) deterministically FROM the committed party
    /// artifacts — the perf-assets pattern for functional conformance.
    ConformanceAssets {
        /// The artifact root (for the capability matrix).
        #[arg(long)]
        root: PathBuf,
        /// The committed results.json.
        #[arg(long)]
        results: PathBuf,
        /// The committed verdicts.json.
        #[arg(long)]
        verdicts: PathBuf,
        /// Output directory for the SVG files.
        #[arg(long)]
        out: PathBuf,
        /// A suffix appended to the SVG file stems (`-ehrbase` for the
        /// comparison SUT's copies).
        #[arg(long, default_value = "")]
        suffix: String,
    },
    /// Compute the verdicts from a statement + results against an artifact
    /// tree (the pure pipeline) and write the rendered submission documents.
    Verdicts {
        /// The party statement (`statement.json`).
        #[arg(long)]
        statement: PathBuf,
        /// The party results (`results.json`).
        #[arg(long)]
        results: PathBuf,
        /// The artifact root (schedule/, vocab/, registers/).
        #[arg(long)]
        root: PathBuf,
        /// Output directory for the rendered documents + verdicts.json.
        #[arg(long)]
        out: PathBuf,
    },
}

/// Load one JSON party artifact, validating it against its emitted schema
/// before typed parsing.
fn load_party_json<T: serde::de::DeserializeOwned>(
    path: &std::path::Path,
    schema: &serde_json::Value,
    schema_name: &str,
) -> Result<T, String> {
    let text = std::fs::read_to_string(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let value: serde_json::Value =
        serde_json::from_str(&text).map_err(|e| format!("{}: JSON: {e}", path.display()))?;
    let validator = compile_schema(schema, schema_name).map_err(|e| e.to_string())?;
    let violations: Vec<String> = validator
        .iter_errors(&value)
        .map(|e| format!("{}: {e}", e.instance_path()))
        .collect();
    if !violations.is_empty() {
        return Err(format!(
            "{}: schema: {}",
            path.display(),
            violations.join("; ")
        ));
    }
    serde_json::from_value(value).map_err(|e| format!("{}: model: {e}", path.display()))
}

fn main() -> ExitCode {
    match Cli::parse().command {
        Command::EmitSchemas { out } => emit_schemas_command(&out),
        Command::Run {
            root,
            ixit,
            out,
            sut_name,
            sut_version,
            filter,
            statement,
        } => run_command(
            &root,
            &ixit,
            &out,
            &sut_name,
            &sut_version,
            filter.as_deref(),
            statement.as_deref(),
        ),
        Command::Validate {
            root,
            specs,
            write_report,
        } => validate_command(&root, specs.as_deref(), write_report),
        Command::Perf {
            root,
            ixit,
            results,
            class,
            seed_workers,
            hours,
        } => perf_command(&root, &ixit, &results, &class, seed_workers, hours),
        Command::Stress {
            root,
            ixit,
            out,
            corpus_class,
            seed_workers,
            step_secs,
            bisections,
            max_rate,
        } => stress_command(
            &root,
            &ixit,
            &out,
            &corpus_class,
            seed_workers,
            step_secs,
            bisections,
            max_rate,
        ),
        Command::AqlProbe {
            root,
            ixit,
            out,
            corpus_class,
            seed_workers,
            requests,
        } => probe_command(&root, &ixit, &out, &corpus_class, seed_workers, requests),
        Command::StressCompare {
            left,
            left_label,
            right,
            right_label,
            out,
        } => stress_compare_command(&left, &left_label, &right, &right_label, &out),
        Command::PerfAssets {
            root,
            results,
            out,
            summary,
            stress,
        } => perf_assets_command(&root, &results, &out, summary.as_deref(), stress.as_deref()),
        Command::ConformanceAssets {
            root,
            results,
            verdicts,
            out,
            suffix,
        } => conformance_assets_command(&root, &results, &verdicts, &out, &suffix),
        Command::Verdicts {
            statement,
            results,
            root,
            out,
        } => run_verdicts(&statement, &results, &root, &out),
    }
}

fn emit_schemas_command(out: &std::path::Path) -> ExitCode {
    if let Err(e) = std::fs::create_dir_all(out) {
        eprintln!("cannot create {}: {e}", out.display());
        return ExitCode::from(2);
    }
    for (name, schema) in emit_all() {
        let path = out.join(name);
        if let Err(e) = std::fs::write(&path, render(&schema)) {
            eprintln!("cannot write {}: {e}", path.display());
            return ExitCode::from(2);
        }
        println!("wrote {}", path.display());
    }
    ExitCode::SUCCESS
}

fn validate_command(
    root: &std::path::Path,
    specs: Option<&std::path::Path>,
    write_report: bool,
) -> ExitCode {
    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    let findings = validate(&Context {
        set: &loaded.set,
        load_errors: &loaded.errors,
        spec_root: specs,
    });
    for finding in &findings {
        println!("{finding}");
    }
    // Refresh the deterministic wire-surface coverage report ONLY when asked
    // (`--write-report`) and the vendored spec tree is supplied (it feeds the
    // Axis-1 SM-operation enumeration). The report lives beside the committed
    // conformance artifacts (docs/conformance/), derived from the `--specs`
    // path; a write failure is a warning, never a gate failure. Default-off:
    // a `validate` verb that rewrites a committed file on every run surprises
    // read-only and fenced invocations.
    if write_report
        && let Some(specs) = specs
        && let Some(docs) = specs.parent().and_then(std::path::Path::parent)
    {
        let report_path = docs.join("conformance/coverage-report.md");
        let body = render_coverage_report(&loaded.set, Some(specs));
        match report_path
            .parent()
            .map_or(Ok(()), std::fs::create_dir_all)
            .and_then(|()| std::fs::write(&report_path, body))
        {
            Ok(()) => println!("wrote {}", report_path.display()),
            Err(e) => eprintln!("warning: cannot write {}: {e}", report_path.display()),
        }
    }
    println!(
        "{} case(s), {} binding(s), {} party statement(s), {} finding(s)",
        loaded.set.cases.len(),
        loaded.set.bindings.len(),
        loaded.set.parties.len(),
        findings.len()
    );
    if findings.is_empty() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

#[expect(clippy::too_many_lines, reason = "the one-shot orchestration seam")]
fn run_verdicts(
    statement_path: &std::path::Path,
    results_path: &std::path::Path,
    root: &std::path::Path,
    out: &std::path::Path,
) -> ExitCode {
    let statement: Statement =
        match load_party_json(statement_path, &statement_schema(), "statement.schema.json") {
            Ok(s) => s,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        };
    let results: Results =
        match load_party_json(results_path, &results_schema(), "results.schema.json") {
            Ok(r) => r,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        };
    if let Err(errors) = results.check_invariants() {
        for e in &errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }

    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    if !loaded.errors.is_empty() {
        for e in &loaded.errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }
    let Some((_, matrix)) = &loaded.set.matrix else {
        eprintln!("artifact tree carries no capability matrix");
        return ExitCode::from(2);
    };
    let Some((_, register)) = &loaded.set.register else {
        eprintln!("artifact tree carries no ambiguity register");
        return ExitCode::from(2);
    };
    let cases: Vec<_> = loaded.set.cases.iter().map(|(_, c)| c.clone()).collect();
    let perf_cases: Vec<_> = loaded
        .set
        .performance
        .iter()
        .map(|(_, c)| c.clone())
        .collect();

    let report = compute(&statement, &results, &cases, &perf_cases, matrix, register);

    // The outward wire-surface axis (`vocab/wire_surface.yaml`
    // `served_extensions`): rendered into the statement as a declaration of the
    // non-openEHR surface, never an input to any verdict.
    let served_extensions = match &loaded.set.wire_surface {
        Some((_, wire_surface)) => wire_surface.served_extensions.as_slice(),
        None => &[],
    };

    if let Err(e) = std::fs::create_dir_all(out) {
        eprintln!("cannot create {}: {e}", out.display());
        return ExitCode::from(2);
    }
    let artifacts: [(&str, String); 4] = [
        (
            "verdicts.json",
            match serde_json::to_string_pretty(&report) {
                Ok(mut json) => {
                    json.push('\n');
                    json
                }
                Err(e) => {
                    eprintln!("cannot serialize verdicts: {e}");
                    return ExitCode::from(2);
                }
            },
        ),
        (
            "CONFORMANCE_REPORT.md",
            match render_report(&results, &report, &statement) {
                Ok(markdown) => markdown,
                Err(e) => {
                    eprintln!("cannot render the report: {e}");
                    return ExitCode::from(2);
                }
            },
        ),
        (
            "CONFORMANCE_STATEMENT.md",
            render_statement(&statement, &report, served_extensions),
        ),
        (
            "CONFORMANCE_CERTIFICATE.md",
            render_certificate(&statement, &results, &report, matrix),
        ),
    ];
    // The shields.io endpoints, derived here rather than downstream so a
    // published count and the verdict beside it come from one rule.
    let mut artifacts: Vec<(String, String)> = artifacts
        .into_iter()
        .map(|(name, body)| (name.to_owned(), body))
        .collect();
    for named in veredictum::badges::badges(
        &report,
        matrix,
        veredictum::badges::CaseCounts::of(&results),
    ) {
        match serde_json::to_string_pretty(&named.badge) {
            Ok(mut json) => {
                json.push('\n');
                artifacts.push((named.file, json));
            }
            Err(e) => {
                eprintln!("cannot serialize the {} badge: {e}", named.file);
                return ExitCode::from(2);
            }
        }
    }

    for (name, body) in &artifacts {
        let path = out.join(name);
        if let Err(e) = std::fs::write(&path, body) {
            eprintln!("cannot write {}: {e}", path.display());
            return ExitCode::from(2);
        }
        println!("wrote {}", path.display());
    }

    for finding in &report.review {
        println!("static-review: {}", finding.message);
    }
    println!(
        "{} capability verdict(s), {} of {} cases driven, {} review finding(s)",
        report.capabilities.len(),
        report.coverage.driven,
        report.coverage.selected,
        report.review.len(),
    );
    if report.review.is_empty() {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

/// The conformance-asset renderer (`conformance-assets`): the capability
/// heat grid + the per-chapter outcome bars, deterministic SVGs FROM the
/// committed party artifacts (regenerate-and-diff guarded in CI).
fn conformance_assets_command(
    root: &std::path::Path,
    results_path: &std::path::Path,
    verdicts_path: &std::path::Path,
    out: &std::path::Path,
    suffix: &str,
) -> ExitCode {
    // The committed verdicts.json — only the capability evidence list is
    // the render input.
    #[derive(serde::Deserialize)]
    struct VerdictSlice {
        capabilities: Vec<(String, veredictum::verdict::Evidence)>,
    }

    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    let Some((_, matrix)) = &loaded.set.matrix else {
        eprintln!("artifact set has no capability matrix");
        return ExitCode::from(2);
    };
    let results: Results =
        match load_party_json(results_path, &results_schema(), "results.schema.json") {
            Ok(results) => results,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        };
    let verdicts: VerdictSlice = match std::fs::read_to_string(verdicts_path)
        .map_err(|e| format!("cannot read {}: {e}", verdicts_path.display()))
        .and_then(|text| serde_json::from_str(&text).map_err(|e| format!("verdicts: {e}")))
    {
        Ok(verdicts) => verdicts,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    if let Err(e) = std::fs::create_dir_all(out) {
        eprintln!("cannot create {}: {e}", out.display());
        return ExitCode::from(2);
    }
    let sut_label = format!("{} {}", results.sut.name, results.sut.version);
    // An unmapped case id is a taxonomy gap, not a chart to publish: the
    // renderer fails loudly and names the id.
    let chapters = match veredictum::conf_assets::chapter_counts(&results) {
        Ok(chapters) => chapters,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let assets = [
        (
            format!("conformance-heat-grid{suffix}.svg"),
            veredictum::conf_assets::heat_grid_svg(&sut_label, matrix, &verdicts.capabilities),
        ),
        (
            format!("conformance-chapter-bars{suffix}.svg"),
            veredictum::conf_assets::chapter_bars_svg(&sut_label, &chapters),
        ),
    ];
    for (name, body) in &assets {
        let path = out.join(name);
        if let Err(e) = std::fs::write(&path, body) {
            eprintln!("cannot write {}: {e}", path.display());
            return ExitCode::from(2);
        }
        println!("wrote {}", path.display());
    }
    ExitCode::SUCCESS
}

/// The asset renderer (`perf-assets`): deterministic SVGs FROM the committed
/// measurement records (regenerate-and-diff guarded in CI).
#[expect(clippy::too_many_lines, reason = "one-shot orchestration seam")]
fn perf_assets_command(
    root: &std::path::Path,
    results_path: &std::path::Path,
    out: &std::path::Path,
    summary: Option<&std::path::Path>,
    stress: Option<&std::path::Path>,
) -> ExitCode {
    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    if !loaded.errors.is_empty() {
        for e in &loaded.errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }
    let results: Results =
        match load_party_json(results_path, &results_schema(), "results.schema.json") {
            Ok(results) => results,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        };
    if let Err(e) = std::fs::create_dir_all(out) {
        eprintln!("cannot create {}: {e}", out.display());
        return ExitCode::from(2);
    }
    let perf_cases: Vec<_> = loaded
        .set
        .performance
        .iter()
        .map(|(_, c)| c.clone())
        .collect();
    let mut files: Vec<(String, String)> = vec![(
        "perf-class-ladder.svg".to_owned(),
        veredictum::perf_assets::class_ladder_svg(&perf_cases, &results.measurements),
    )];
    if let Some(stress_path) = stress {
        let report: veredictum::stress::StressReport = match std::fs::read_to_string(stress_path)
            .map_err(|e| format!("cannot read {}: {e}", stress_path.display()))
            .and_then(|text| {
                serde_json::from_str(&text).map_err(|e| format!("{}: {e}", stress_path.display()))
            }) {
            Ok(report) => report,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        };
        match veredictum::perf_assets::stress_curve_svg(&report) {
            Ok(svg) => files.push(("perf-stress-curve.svg".to_owned(), svg)),
            Err(e) => {
                eprintln!("stress curve: {e}");
                return ExitCode::from(2);
            }
        }
    }
    for measurement in &results.measurements {
        match veredictum::perf_assets::latency_percentiles_svg(measurement) {
            Ok(svg) => files.push((
                format!("perf-latency-class-{}.svg", measurement.class.token()),
                svg,
            )),
            Err(e) => {
                eprintln!("{}: {e}", measurement.case);
                return ExitCode::from(2);
            }
        }
        // The resource time-series renders only from a record that carries
        // one (sampling is optional by capability; nothing is fabricated).
        if let Some(svg) = veredictum::perf_assets::resources_timeseries_svg(measurement) {
            files.push((
                format!("perf-resources-class-{}.svg", measurement.class.token()),
                svg,
            ));
        }
    }
    if let Some(svg) = veredictum::perf_assets::disk_growth_svg(&results.measurements) {
        files.push(("perf-disk-growth.svg".to_owned(), svg));
    }
    for (name, body) in &files {
        let path = out.join(name);
        if let Err(e) = std::fs::write(&path, body) {
            eprintln!("cannot write {}: {e}", path.display());
            return ExitCode::from(2);
        }
        println!("wrote {}", path.display());
    }
    if let Some(summary_path) = summary {
        let body =
            match veredictum::perf_assets::summary_markdown(&perf_cases, &results.measurements) {
                Ok(body) => body,
                Err(e) => {
                    eprintln!("summary: {e}");
                    return ExitCode::from(2);
                }
            };
        if let Some(parent) = summary_path.parent()
            && let Err(e) = std::fs::create_dir_all(parent)
        {
            eprintln!("cannot create {}: {e}", parent.display());
            return ExitCode::from(2);
        }
        if let Err(e) = std::fs::write(summary_path, body) {
            eprintln!("cannot write {}: {e}", summary_path.display());
            return ExitCode::from(2);
        }
        println!("wrote {}", summary_path.display());
    }
    ExitCode::SUCCESS
}

/// Resolve the blood-pressure OPT the scale corpora commit against.
fn scale_opt_xml(loaded: &veredictum::artifacts::Loaded) -> Result<String, String> {
    let corpus_dir = loaded
        .set
        .corpus_dir
        .as_deref()
        .ok_or_else(|| "artifact set has no corpus directory".to_owned())?;
    let key =
        veredictum::ids::CorpusKey::parse("cnf.opt.blood_pressure").map_err(|e| e.to_string())?;
    let source = loaded
        .set
        .corpus
        .as_ref()
        .and_then(|(_, m)| m.get(&key))
        .and_then(|entry| entry.source.clone())
        .ok_or_else(|| "corpus manifest has no cnf.opt.blood_pressure fixture".to_owned())?;
    std::fs::read_to_string(corpus_dir.join(&source))
        .map_err(|e| format!("cannot read OPT fixture {source}: {e}"))
}

/// The journey context every measured run needs: the catalogue (loaded
/// artifact) and the CKM template pack its stages name.
fn journey_context(
    loaded: &veredictum::artifacts::Loaded,
) -> Result<
    (
        veredictum::perf::JourneyCatalogue,
        veredictum::perf_run::pack::JourneyPack,
    ),
    String,
> {
    let catalogue = loaded
        .set
        .journeys
        .as_ref()
        .map(|(_, catalogue)| catalogue.clone())
        .ok_or_else(|| "artifact set has no vocab/journey_catalogue.yaml".to_owned())?;
    let corpus_dir = loaded
        .set
        .corpus_dir
        .as_deref()
        .ok_or_else(|| "artifact set has no corpus directory".to_owned())?;
    let manifest = loaded
        .set
        .corpus
        .as_ref()
        .map(|(_, manifest)| manifest)
        .ok_or_else(|| "artifact set has no corpus manifest".to_owned())?;
    let pack = veredictum::perf_run::pack::JourneyPack::load(corpus_dir, manifest, &catalogue)?;
    Ok((catalogue, pack))
}

/// The seeding milestones the disk anchors probe at (`perf` passes a
/// probing observer; `stress` observes nothing).
#[derive(Debug, Clone, Copy)]
enum SeedStage {
    BeforeScale,
    AfterScale,
    AfterWard,
}

/// Seed the scale corpus + the standing ward. The workflow ALWAYS seeds a
/// freshly composed, empty SUT and the stack is torn down afterwards —
/// there is no seed reuse (the retired `--skip-seed`/sidecar-index scheme
/// bred stale-state confusion). `stage` observes the seeding milestones
/// (the disk anchors).
fn seed_corpus(
    client: &veredictum::perf_run::client::PerfClient,
    corpus_key: &str,
    opt_xml: &str,
    journey_pack: &veredictum::perf_run::pack::JourneyPack,
    seed_workers: usize,
    progress: &(dyn Fn(String) + Sync),
    stage: &mut dyn FnMut(SeedStage),
) -> Result<veredictum::perf_run::corpus::SeededCorpus, String> {
    use veredictum::perf_run::corpus;
    let (ehrs, versions) = corpus::scale_shape(corpus_key)?;
    stage(SeedStage::BeforeScale);
    let mut seeded = corpus::seed_scale_ladder(
        client,
        corpus_key,
        opt_xml,
        ehrs,
        versions,
        seed_workers,
        progress,
    )
    .map_err(|e| format!("seeding failed: {e}"))?;
    stage(SeedStage::AfterScale);
    corpus::seed_ward(client, &mut seeded, journey_pack, seed_workers, progress)
        .map_err(|e| format!("ward seeding failed: {e}"))?;
    stage(SeedStage::AfterWard);
    Ok(seeded)
}

/// The stress handler: the step-load ladder to the maximum sustainable
/// throughput (exploration only — writes stress.json, never results.json).
#[expect(
    clippy::too_many_arguments,
    clippy::too_many_lines,
    reason = "one-shot orchestration seam"
)]
fn stress_command(
    root: &std::path::Path,
    ixit_path: &std::path::Path,
    out: &std::path::Path,
    corpus_class: &str,
    seed_workers: usize,
    step_secs: u64,
    bisections: u32,
    max_rate: f64,
) -> ExitCode {
    use veredictum::perf::PerfClass;
    use veredictum::perf_run;

    let class = match PerfClass::parse(corpus_class) {
        Ok(class) => class,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    if !loaded.errors.is_empty() {
        for e in &loaded.errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }
    let mut ixit: veredictum::ixit::Ixit = match std::fs::read_to_string(ixit_path)
        .map_err(|e| format!("cannot read {}: {e}", ixit_path.display()))
        .and_then(|text| serde_json::from_str(&text).map_err(|e| format!("ixit: {e}")))
    {
        Ok(ixit) => ixit,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    // File references in the ixit (the SMART lane's signing key) are relative
    // to the ixit document, not to the runner's working directory — the same
    // rebase the `run` command applies (the measured client minted against an
    // unresolved relative path and died at seeding, 2026-07-29 POC run).
    ixit.rebase_paths(ixit_path.parent().unwrap_or(std::path::Path::new(".")));
    let (principals, environment) = match perf_run::window::measured_run_context(&ixit) {
        Ok(context) => context,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let client = principals.primary().clone();
    // The class token is the STANDARDIZED corpus selector (data volume +
    // workload mix); no class floor enters the stress report or chart.
    let Some((_, case)) = loaded
        .set
        .performance
        .iter()
        .find(|(_, c)| c.class == class)
    else {
        eprintln!("no performance case of class {corpus_class} in the catalogue");
        return ExitCode::from(2);
    };
    let opt_xml = match scale_opt_xml(&loaded) {
        Ok(xml) => xml,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let (catalogue, journey_pack) = match journey_context(&loaded) {
        Ok(context) => context,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let progress = |message: String| eprintln!("[stress] {message}");
    let corpus = match seed_corpus(
        &client,
        case.corpus.as_str(),
        &opt_xml,
        &journey_pack,
        seed_workers,
        &progress,
        // The stress instrument records no disk anchors (exploration only).
        &mut |_| {},
    ) {
        Ok(corpus) => corpus,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let options = veredictum::stress::StressOptions {
        step_hold_s: step_secs.max(10),
        bisections,
        max_rate,
        ..veredictum::stress::StressOptions::default()
    };
    let workload = perf_run::schedule::JourneyWorkload {
        catalogue: &catalogue,
        shares: &case.workload.journeys,
        pack: &journey_pack,
        // Stress steps are short — the day curve has no meaning there.
        curve: veredictum::perf::ArrivalCurve::Uniform,
        principals: &principals,
    };
    let report = match veredictum::stress::run_stress(
        &principals,
        &corpus,
        &workload,
        environment,
        ixit.containers.as_ref(),
        &options,
        &progress,
    ) {
        Ok(report) => report,
        Err(e) => {
            eprintln!("stress run failed: {e}");
            return ExitCode::from(2);
        }
    };
    if perf_run::rate_limited_observed() {
        eprintln!("{}", perf_run::rate_limited_refusal("stress"));
        return ExitCode::from(2);
    }
    match serde_json::to_string_pretty(&report) {
        Ok(mut text) => {
            text.push('\n');
            if let Some(parent) = out.parent()
                && let Err(e) = std::fs::create_dir_all(parent)
            {
                eprintln!("cannot create {}: {e}", parent.display());
                return ExitCode::from(2);
            }
            if let Err(e) = std::fs::write(out, text) {
                eprintln!("cannot write {}: {e}", out.display());
                return ExitCode::from(2);
            }
        }
        Err(e) => {
            eprintln!("serialize: {e}");
            return ExitCode::from(2);
        }
    }
    println!("{}", report.remark);
    println!(
        "wrote {} ({} steps, max sustainable {:.1}/s)",
        out.display(),
        report.steps.len(),
        report.max_sustainable_throughput_per_s
    );
    ExitCode::SUCCESS
}

/// The stress-overlay handler (`stress-compare`): render both systems'
/// latency-throughput curves from their committed stress reports.
fn stress_compare_command(
    left: &std::path::Path,
    left_label: &str,
    right: &std::path::Path,
    right_label: &str,
    out: &std::path::Path,
) -> ExitCode {
    let read = |path: &std::path::Path| -> Result<veredictum::stress::StressReport, String> {
        std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read {}: {e}", path.display()))
            .and_then(|text| {
                serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))
            })
    };
    let (left_report, right_report) = match (read(left), read(right)) {
        (Ok(a), Ok(b)) => (a, b),
        (Err(e), _) | (_, Err(e)) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let svg = match veredictum::perf_assets::stress_compare_svg(
        (left_label, &left_report),
        (right_label, &right_report),
    ) {
        Ok(svg) => svg,
        Err(e) => {
            eprintln!("stress compare: {e}");
            return ExitCode::from(2);
        }
    };
    if let Some(parent) = out.parent()
        && let Err(e) = std::fs::create_dir_all(parent)
    {
        eprintln!("cannot create {}: {e}", parent.display());
        return ExitCode::from(2);
    }
    if let Err(e) = std::fs::write(out, svg) {
        eprintln!("cannot write {}: {e}", out.display());
        return ExitCode::from(2);
    }
    println!("wrote {}", out.display());
    ExitCode::SUCCESS
}

/// The AQL-probe handler (`aql-probe`): seed the class corpus fresh, run
/// the probe set, write the report (exploration only — never touches
/// results.json).
#[expect(clippy::too_many_lines, reason = "one-shot orchestration seam")]
fn probe_command(
    root: &std::path::Path,
    ixit_path: &std::path::Path,
    out: &std::path::Path,
    corpus_class: &str,
    seed_workers: usize,
    requests: u32,
) -> ExitCode {
    use veredictum::perf::PerfClass;
    use veredictum::perf_run;

    let class = match PerfClass::parse(corpus_class) {
        Ok(class) => class,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    if !loaded.errors.is_empty() {
        for e in &loaded.errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }
    let mut ixit: veredictum::ixit::Ixit = match std::fs::read_to_string(ixit_path)
        .map_err(|e| format!("cannot read {}: {e}", ixit_path.display()))
        .and_then(|text| serde_json::from_str(&text).map_err(|e| format!("ixit: {e}")))
    {
        Ok(ixit) => ixit,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    // File references in the ixit (the SMART lane's signing key) are relative
    // to the ixit document, not to the runner's working directory — the same
    // rebase the `run` command applies (the measured client minted against an
    // unresolved relative path and died at seeding, 2026-07-29 POC run).
    ixit.rebase_paths(ixit_path.parent().unwrap_or(std::path::Path::new(".")));
    let (principals, environment) = match perf_run::window::measured_run_context(&ixit) {
        Ok(context) => context,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let client = principals.primary().clone();
    let Some((_, case)) = loaded
        .set
        .performance
        .iter()
        .find(|(_, c)| c.class == class)
    else {
        eprintln!("no performance case of class {corpus_class} in the catalogue");
        return ExitCode::from(2);
    };
    let opt_xml = match scale_opt_xml(&loaded) {
        Ok(xml) => xml,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let (_, journey_pack) = match journey_context(&loaded) {
        Ok(context) => context,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let progress = |message: String| eprintln!("[probe] {message}");
    let corpus = match seed_corpus(
        &client,
        case.corpus.as_str(),
        &opt_xml,
        &journey_pack,
        seed_workers,
        &progress,
        // The probe records no disk anchors (exploration only).
        &mut |_| {},
    ) {
        Ok(corpus) => corpus,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let options = veredictum::probe::ProbeOptions { requests };
    let report = match veredictum::probe::run_probe(
        &client,
        &corpus,
        environment,
        ixit.containers.as_ref(),
        &options,
        &progress,
    ) {
        Ok(report) => report,
        Err(e) => {
            eprintln!("probe run failed: {e}");
            return ExitCode::from(2);
        }
    };
    match serde_json::to_string_pretty(&report) {
        Ok(mut text) => {
            text.push('\n');
            if let Some(parent) = out.parent()
                && let Err(e) = std::fs::create_dir_all(parent)
            {
                eprintln!("cannot create {}: {e}", parent.display());
                return ExitCode::from(2);
            }
            if let Err(e) = std::fs::write(out, text) {
                eprintln!("cannot write {}: {e}", out.display());
                return ExitCode::from(2);
            }
        }
        Err(e) => {
            eprintln!("serialize: {e}");
            return ExitCode::from(2);
        }
    }
    println!("wrote {} ({} probes)", out.display(), report.probes.len());
    ExitCode::SUCCESS
}

/// The measured-run handler (`perf`): seed the scale corpus, drive the
/// open-loop workload, merge the measurement record into results.json.
#[expect(clippy::too_many_lines, reason = "one-shot orchestration seam")]
fn perf_command(
    root: &std::path::Path,
    ixit_path: &std::path::Path,
    results_path: &std::path::Path,
    class_token: &str,
    seed_workers: usize,
    hours: u64,
) -> ExitCode {
    use veredictum::perf::PerfClass;
    use veredictum::perf_run;

    // The sustained-window ladder: the case's normative window (1 h) or an
    // officially extended one — never anything shorter.
    if ![1, 2, 4, 6, 8, 12].contains(&hours) {
        eprintln!("--hours must be one of 1 | 2 | 4 | 6 | 8 | 12 (got {hours})");
        return ExitCode::from(2);
    }

    let class = match PerfClass::parse(class_token) {
        Ok(class) => class,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    if !loaded.errors.is_empty() {
        for e in &loaded.errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }
    let mut ixit: veredictum::ixit::Ixit = match std::fs::read_to_string(ixit_path)
        .map_err(|e| format!("cannot read {}: {e}", ixit_path.display()))
        .and_then(|text| serde_json::from_str(&text).map_err(|e| format!("ixit: {e}")))
    {
        Ok(ixit) => ixit,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    // File references in the ixit (the SMART lane's signing key) are relative
    // to the ixit document, not to the runner's working directory — the same
    // rebase the `run` command applies (the measured client minted against an
    // unresolved relative path and died at seeding, 2026-07-29 POC run).
    ixit.rebase_paths(ixit_path.parent().unwrap_or(std::path::Path::new(".")));
    let (principals, environment) = match perf_run::window::measured_run_context(&ixit) {
        Ok(context) => context,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let client = principals.primary().clone();
    let selected: Vec<_> = loaded
        .set
        .performance
        .iter()
        .filter(|(_, c)| c.class == class)
        .collect();
    if selected.is_empty() {
        eprintln!("no performance case of class {class_token} in the catalogue");
        return ExitCode::from(2);
    }
    // The blood-pressure OPT the scale corpus commits against.
    let opt_xml = match scale_opt_xml(&loaded) {
        Ok(xml) => xml,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let (catalogue, journey_pack) = match journey_context(&loaded) {
        Ok(context) => context,
        Err(e) => {
            eprintln!("{e}");
            return ExitCode::from(2);
        }
    };
    let progress = |message: String| eprintln!("[perf] {message}");
    // Resource sampling is optional by capability: no ixit `containers`
    // block → no `resources` record, never a failed run.
    let containers = ixit.containers.clone();
    if containers.is_none() {
        progress("resources: not sampled (ixit declares no `containers` block)".to_owned());
    }

    let mut earned_all = true;
    for (path, case) in selected {
        println!(
            "case {} (class {class_token}) from {}",
            case.id,
            path.display()
        );
        // The disk anchors bracket the seeding milestones; every probe
        // failure degrades to an absent anchor with the reason logged.
        let mut disk = veredictum::perf::DiskAnchors {
            before_scale_seed_bytes: None,
            after_scale_seed_bytes: None,
            after_ward_seed_bytes: None,
            after_window_bytes: None,
            seed_compositions: perf_run::corpus::scale_shape(case.corpus.as_str())
                .ok()
                .and_then(|(ehrs, versions)| u64::try_from(ehrs.saturating_mul(versions)).ok()),
        };
        let probe_volume = |label: &str| -> Option<u64> {
            let db = &containers.as_ref()?.db;
            match perf_run::resources::db_volume_bytes(db) {
                Ok(bytes) => {
                    progress(format!("disk anchor {label}: {bytes} bytes"));
                    Some(bytes)
                }
                Err(e) => {
                    progress(format!("disk anchor {label} unavailable: {e}"));
                    None
                }
            }
        };
        let corpus = match seed_corpus(
            &client,
            case.corpus.as_str(),
            &opt_xml,
            &journey_pack,
            seed_workers,
            &progress,
            &mut |milestone| match milestone {
                SeedStage::BeforeScale => {
                    disk.before_scale_seed_bytes = probe_volume("before scale seed");
                }
                SeedStage::AfterScale => {
                    disk.after_scale_seed_bytes = probe_volume("after scale seed");
                }
                SeedStage::AfterWard => {
                    disk.after_ward_seed_bytes = probe_volume("after preflight + ward seed");
                }
            },
        ) {
            Ok(corpus) => corpus,
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        };
        // Settle the seeding's maintenance debt before the window: a
        // mid-window autovacuum/analyze of the freshly seeded tables would
        // saturate the engine inside the measurement.
        if let Some(c) = &containers {
            progress(
                "settling maintenance before the measured window (vacuumdb --analyze)".to_owned(),
            );
            if let Err(e) = perf_run::resources::settle_maintenance(&c.db) {
                progress(format!("maintenance not settled: {e}"));
            }
        }
        // The case's normative warmup; the sustained window extends by the
        // hours ladder (a longer hold of the same offered load is a stricter
        // demonstration of the same class).
        let warmup_s = case.workload.warmup.0;
        let duration_s = case.workload.duration.0.max(hours.saturating_mul(3600));
        // The sampler brackets the whole window (warmup + sustained + the
        // completion drain) and stops after the dispatcher's last
        // completion lands — drive_case returns only then.
        let sampler = containers
            .as_ref()
            .map(|c| perf_run::resources::ResourceSampler::start(c, warmup_s, duration_s));
        let mut measurement = match perf_run::window::drive_case(
            case,
            &principals,
            &corpus,
            &journey_pack,
            &catalogue,
            environment,
            warmup_s,
            duration_s,
            &progress,
        ) {
            Ok(measurement) => measurement,
            Err(e) => {
                eprintln!("measured run failed: {e}");
                return ExitCode::from(2);
            }
        };
        if let Some(sampler) = sampler {
            let (series, notes) = sampler.stop();
            for note in notes {
                progress(note);
            }
            disk.after_window_bytes = probe_volume("after measured window");
            let sampled_any = series.iter().any(|s| !s.samples.is_empty());
            let anchored_any = disk.before_scale_seed_bytes.is_some()
                || disk.after_scale_seed_bytes.is_some()
                || disk.after_ward_seed_bytes.is_some()
                || disk.after_window_bytes.is_some();
            if sampled_any || anchored_any {
                measurement.resources = Some(veredictum::perf::ResourcesRecord {
                    sample_interval_s: perf_run::resources::SAMPLE_INTERVAL.as_secs(),
                    containers: series,
                    disk: Some(disk),
                });
            } else {
                progress(
                    "resources: not sampled (container runtime unreachable for the whole run)"
                        .to_owned(),
                );
            }
        }
        for op in &measurement.operations {
            println!(
                "  {}: {} requests, {} errors, p50 {:.1}ms p90 {:.1}ms p99 {:.1}ms",
                op.operation,
                op.requests,
                op.errors,
                op.latency_ms_p50,
                op.latency_ms_p90,
                op.latency_ms_p99
            );
        }
        println!("  {}", veredictum::perf::verdict_evidence(&measurement));
        if measurement.verdict != veredictum::perf::ClassVerdict::Earned {
            earned_all = false;
        }
        // A limiter-shaped window is not a measurement of this server, so it
        // never reaches results.json (`crate::perf_run::rate_limited_observed`).
        if perf_run::rate_limited_observed() {
            eprintln!("{}", perf_run::rate_limited_refusal("perf"));
            return ExitCode::from(2);
        }
        // Merge into results.json (replace any prior record for the case).
        let mut results: Results =
            match load_party_json(results_path, &results_schema(), "results.schema.json") {
                Ok(results) => results,
                Err(e) => {
                    eprintln!("{e}");
                    return ExitCode::from(2);
                }
            };
        results.measurements.retain(|m| m.case != measurement.case);
        // A measurement whose case is no longer in the catalogue (a
        // renamed/retired case) is an orphan the verdict review would
        // flag — prune it here, visibly.
        results.measurements.retain(|m| {
            let known = loaded.set.performance.iter().any(|(_, c)| c.id == m.case);
            if !known {
                println!("  pruned orphaned measurement for retired case {}", m.case);
            }
            known
        });
        results.measurements.push(measurement);
        results
            .measurements
            .sort_by(|a, b| a.case.as_str().cmp(b.case.as_str()));
        match serde_json::to_string_pretty(&results) {
            Ok(mut text) => {
                text.push('\n');
                if let Err(e) = std::fs::write(results_path, text) {
                    eprintln!("cannot write {}: {e}", results_path.display());
                    return ExitCode::from(2);
                }
                println!("  measurement merged into {}", results_path.display());
            }
            Err(e) => {
                eprintln!("serialize: {e}");
                return ExitCode::from(2);
            }
        }
    }
    if earned_all {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}

/// The live-run handler: load, execute, emit results.json + summary.
#[expect(clippy::too_many_lines, reason = "the one-shot orchestration seam")]
fn run_command(
    root: &std::path::Path,
    ixit_path: &std::path::Path,
    out: &std::path::Path,
    sut_name: &str,
    sut_version: &str,
    filter: Option<&str>,
    statement_path: Option<&std::path::Path>,
) -> ExitCode {
    let loaded = match load_root(root) {
        Ok(loaded) => loaded,
        Err(e) => {
            eprintln!("runner defect: {e}");
            return ExitCode::from(2);
        }
    };
    if !loaded.errors.is_empty() {
        for e in &loaded.errors {
            eprintln!("{e}");
        }
        return ExitCode::from(2);
    }
    let ixit_text = match std::fs::read_to_string(ixit_path) {
        Ok(text) => text,
        Err(e) => {
            eprintln!("cannot read {}: {e}", ixit_path.display());
            return ExitCode::from(2);
        }
    };
    let mut ixit: veredictum::ixit::Ixit = match serde_json::from_str(&ixit_text) {
        Ok(ixit) => ixit,
        Err(e) => {
            eprintln!("ixit: {e}");
            return ExitCode::from(2);
        }
    };
    // File references in the ixit (the SMART lane's signing key) are relative
    // to the ixit document, not to the runner's working directory.
    ixit.rebase_paths(ixit_path.parent().unwrap_or(std::path::Path::new(".")));
    let mut set = loaded.set;
    if let Some(needle) = filter {
        set.cases.retain(|(_, c)| c.id.as_str().contains(needle));
    }
    let statement: Option<Statement> = match statement_path {
        None => None,
        Some(path) => match std::fs::read_to_string(path)
            .map_err(|e| format!("cannot read {}: {e}", path.display()))
            .and_then(|text| serde_json::from_str(&text).map_err(|e| format!("statement: {e}")))
        {
            Ok(statement) => Some(statement),
            Err(e) => {
                eprintln!("{e}");
                return ExitCode::from(2);
            }
        },
    };
    let report = match veredictum::run::execute(&set, &ixit, statement.as_ref()) {
        Ok(report) => report,
        Err(e) => {
            eprintln!("execution defect: {e}");
            return ExitCode::from(2);
        }
    };
    let outcomes: Vec<veredictum::party::OutcomeRecord> = report
        .records
        .iter()
        .map(veredictum::party::OutcomeRecord::from)
        .collect();
    let (passed, failed, errored, na) = outcomes.iter().fold((0, 0, 0, 0), |acc, o| {
        use veredictum::party::OutcomeStatus;
        match o.status {
            OutcomeStatus::Passed => (acc.0 + 1, acc.1, acc.2, acc.3),
            OutcomeStatus::Failed => (acc.0, acc.1 + 1, acc.2, acc.3),
            OutcomeStatus::Errored => (acc.0, acc.1, acc.2 + 1, acc.3),
            _ => (acc.0, acc.1, acc.2, acc.3 + 1),
        }
    });
    let ixit_digest = {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        ixit_text.hash(&mut hasher);
        format!("{:016x}", hasher.finish())
    };
    // A functional run never re-measures: carry the measurement records of a
    // prior results.json at the same path forward (same SUT name only; a
    // version change gets a loud warning — the §8.10 version-binding rule
    // wants fresh evidence or an unchanged-surface attestation).
    let carried_measurements: Vec<veredictum::perf::Measurement> = {
        let prior_path = out.join("results.json");
        // NOTE: no prior file is ABSENCE (the first run at this path); a file
        // that exists but will not read or parse is a DEFECT — carrying zero
        // measurements past it would silently drop the §8.10 evidence.
        let prior = match std::fs::read_to_string(&prior_path) {
            Ok(text) => match serde_json::from_str::<Results>(&text) {
                Ok(prior) => Some(prior),
                Err(e) => {
                    eprintln!(
                        "runner defect: {} exists but does not parse as results.json ({e}) — \
                         its measurement records cannot be carried forward",
                        prior_path.display()
                    );
                    return ExitCode::from(2);
                }
            },
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                eprintln!(
                    "runner defect: {} is unreadable ({e})",
                    prior_path.display()
                );
                return ExitCode::from(2);
            }
        };
        prior
            .filter(|prior| prior.sut.name == sut_name)
            .map(|prior| {
                if prior.sut.version != sut_version && !prior.measurements.is_empty() {
                    eprintln!(
                        "warning: carrying {} measurement record(s) taken at SUT version {} into a run at {sut_version} — re-measure or attest the surface unchanged",
                        prior.measurements.len(),
                        prior.sut.version
                    );
                }
                prior.measurements
            })
            .unwrap_or_default()
    };
    let results = Results {
        sut: veredictum::party::Sut {
            name: sut_name.to_owned(),
            version: sut_version.to_owned(),
        },
        runner: veredictum::party::Runner {
            name: "veredictum".to_owned(),
            version: env!("CARGO_PKG_VERSION").to_owned(),
            verification_pack_status: veredictum::party::VerificationPackStatus::Passed,
        },
        schedule_release: "cnf-2.0-w2".to_owned(),
        // The recorded technology profile IS the claim the verdict pipeline
        // selects gating records with (`verdict::rollup_results`): a narrow
        // hardcoded list here silently deselects every other format's failed
        // rows — the false-green shape that hid four red canonical-xml rows
        // behind a PASS badge (#288 convergence run, 2026-07-28). The profile
        // therefore comes from the party statement's its-rest claim; with no
        // statement, EVERY format is selected so nothing red can vanish.
        tech_profile: veredictum::party::TechProfile {
            its: veredictum::vocab::ItsName::ItsRest,
            formats: statement
                .as_ref()
                .and_then(|s| {
                    s.tech_profiles
                        .iter()
                        .find(|p| p.its == veredictum::vocab::ItsName::ItsRest)
                })
                .map_or_else(
                    || veredictum::vocab::FormatName::ALL.to_vec(),
                    |p| p.formats.clone(),
                ),
        },
        ixit_digest,
        restapi_specs_version: report.restapi_specs_version.clone(),
        outcomes,
        measurements: carried_measurements,
        ambiguity_dispositions: Vec::new(),
    };
    if let Err(errors) = results.check_invariants() {
        for e in errors {
            eprintln!("results invariant: {e}");
        }
        return ExitCode::from(2);
    }
    if let Err(e) = std::fs::create_dir_all(out) {
        eprintln!("cannot create {}: {e}", out.display());
        return ExitCode::from(2);
    }
    let results_path = out.join("results.json");
    match serde_json::to_string_pretty(&results) {
        Ok(mut text) => {
            text.push('\n');
            if let Err(e) = std::fs::write(&results_path, text) {
                eprintln!("cannot write {}: {e}", results_path.display());
                return ExitCode::from(2);
            }
        }
        Err(e) => {
            eprintln!("serialize: {e}");
            return ExitCode::from(2);
        }
    }
    let exceptions_path = out.join("run-exceptions.json");
    if let Ok(mut text) = serde_json::to_string_pretty(
        &report
            .exceptions
            .iter()
            .map(|(case, e)| serde_json::json!({ "case": case.to_string(), "exception": e }))
            .collect::<Vec<_>>(),
    ) {
        text.push('\n');
        let _write = std::fs::write(&exceptions_path, text);
    }
    println!(
        "{} case-records: {passed} passed / {failed} failed / {errored} errored / {na} n-a; interpreter coverage {:.1}% ({} exceptions); wrote {}",
        report.records.len(),
        report.interpreter_coverage() * 100.0,
        report.exceptions.len(),
        results_path.display()
    );
    if failed == 0 && errored == 0 {
        ExitCode::SUCCESS
    } else {
        ExitCode::from(1)
    }
}