rch-common 2.1.21

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

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ===========================================================================
// Coverage matrix types
// ===========================================================================

const COVERAGE_MATRIX_SCHEMA_VERSION: &str = "1.0.0";

/// A single requirement row in the coverage matrix.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct RequirementRow {
    /// Unique identifier for this requirement.
    id: String,
    /// Human-readable description of the requirement.
    description: String,
    /// Reliability domain (e.g., path_deps, convergence, pressure, triage).
    domain: String,
    /// Responsible bead ID.
    bead_id: String,
    /// List of test references (file::test_name_prefix).
    test_refs: Vec<TestRef>,
    /// Expected log/artifact assertions.
    artifact_assertions: Vec<String>,
    /// Whether this row has at least one executable test.
    has_executable_test: bool,
    /// Whether this row has at least one log assertion.
    has_log_assertion: bool,
    /// Explicit gap marker (if no tests exist yet, this should be a backlog item).
    gap: Option<String>,
}

/// Reference to a concrete test.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct TestRef {
    /// Test file (relative to rch-common/tests/).
    file: String,
    /// Test name prefix (matches one or more #[test] functions).
    name_prefix: String,
    /// Test tier: "smoke", "nightly", or "full".
    tier: String,
}

/// Full coverage matrix.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct CoverageMatrix {
    schema_version: String,
    requirements: Vec<RequirementRow>,
    summary: MatrixSummary,
}

/// Summary statistics for the matrix.
#[derive(Debug, Clone, Serialize, Deserialize)]
struct MatrixSummary {
    total_requirements: usize,
    covered_requirements: usize,
    gap_count: usize,
    domains: Vec<String>,
    total_test_refs: usize,
    total_artifact_assertions: usize,
}

// ===========================================================================
// Matrix builder
// ===========================================================================

fn build_coverage_matrix() -> CoverageMatrix {
    let requirements = vec![
        // ---------------------------------------------------------------
        // Domain: Path Dependencies
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-PATH-001".into(),
            description: "Cross-repo Cargo path dependency resolution and transitive closure"
                .into(),
            domain: "path_deps".into(),
            bead_id: "bd-vvmd.2.8".into(),
            test_refs: vec![TestRef {
                file: "cross_repo_path_deps_e2e.rs".into(),
                name_prefix: "e2e_cross_repo_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Planner output includes all transitive path deps".into(),
                "Alias symlinks produce equivalent closure".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-PATH-002".into(),
            description: "Dependency closure planner deterministic ordering".into(),
            domain: "path_deps".into(),
            bead_id: "bd-vvmd.2.7".into(),
            test_refs: vec![TestRef {
                file: "dependency_closure_planner.rs".into(),
                name_prefix: "test_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec!["Planner output is deterministically ordered".into()],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-PATH-003".into(),
            description: "Fail-open semantics when path deps cannot be resolved".into(),
            domain: "path_deps".into(),
            bead_id: "bd-vvmd.2.8".into(),
            test_refs: vec![TestRef {
                file: "cross_repo_path_deps_e2e.rs".into(),
                name_prefix: "e2e_cross_repo_fail_open".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Graceful degradation with diagnostic output when deps are missing".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Command Classification
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-CLASS-001".into(),
            description: "Command classification regression for non-compilation UX".into(),
            domain: "classification".into(),
            bead_id: "bd-vvmd.2.9".into(),
            test_refs: vec![TestRef {
                file: "cross_repo_path_deps_e2e.rs".into(),
                name_prefix: "e2e_cross_repo_classify".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Classification timing under budget".into(),
                "Known commands correctly categorized".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Repo Convergence
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-CONV-001".into(),
            description: "Repo convergence adapter contract and failure taxonomy".into(),
            domain: "convergence".into(),
            bead_id: "bd-vvmd.3.6".into(),
            test_refs: vec![TestRef {
                file: "repo_convergence_e2e.rs".into(),
                name_prefix: "e2e_convergence_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Adapter request/response schema roundtrip valid".into(),
                "Failure taxonomy maps to error codes".into(),
                "Trust and auth policies enforced".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-CONV-002".into(),
            description: "Repo convergence internal unit tests".into(),
            domain: "convergence".into(),
            bead_id: "bd-vvmd.3.8".into(),
            test_refs: vec![TestRef {
                file: "repo_convergence_e2e.rs".into(),
                name_prefix: "e2e_convergence_mock_adapter".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec!["Mock adapter exercises all contract branches".into()],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Storage Pressure
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-DISK-001".into(),
            description: "Disk pressure detection, prevention, and recovery".into(),
            domain: "disk_pressure".into(),
            bead_id: "bd-vvmd.4.6".into(),
            test_refs: vec![TestRef {
                file: "fault_injection_e2e.rs".into(),
                name_prefix: "e2e_fault_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Pressure state transitions logged".into(),
                "Critical threshold triggers build deferral".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Process Triage
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-TRIAGE-001".into(),
            description: "Process triage contract, safe-action policy, escalation ladder".into(),
            domain: "process_triage".into(),
            bead_id: "bd-vvmd.5.6".into(),
            test_refs: vec![TestRef {
                file: "process_triage_e2e.rs".into(),
                name_prefix: "e2e_triage_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Safe-action policy prevents harmful actions on protected processes".into(),
                "Escalation ladder produces monotonically increasing severity".into(),
                "Audit records capture all triage decisions".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Fault Injection
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-FAULT-001".into(),
            description: "Deterministic fault injection for partial failure and recovery".into(),
            domain: "fault_injection".into(),
            bead_id: "bd-vvmd.7.6".into(),
            test_refs: vec![TestRef {
                file: "fault_injection_e2e.rs".into(),
                name_prefix: "e2e_fault_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Network cut, partial sync, timeout, and combined pressure faults exercised".into(),
                "Recovery path validated after each fault".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Schema Contracts
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-SCHEMA-001".into(),
            description: "JSON/log schema contract golden tests for reliability outputs".into(),
            domain: "schema_contract".into(),
            bead_id: "bd-vvmd.6.8".into(),
            test_refs: vec![TestRef {
                file: "schema_contract_e2e.rs".into(),
                name_prefix: "e2e_schema_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "API envelope schema valid".into(),
                "Error payload schema valid".into(),
                "Hook protocol schema valid".into(),
                "Reliability event schema valid".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Concurrency Soak
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-SOAK-001".into(),
            description: "Long-duration concurrency soak with slot churn and pressure transitions"
                .into(),
            domain: "soak_concurrency".into(),
            bead_id: "bd-vvmd.7.9".into(),
            test_refs: vec![TestRef {
                file: "soak_concurrency_e2e.rs".into(),
                name_prefix: "e2e_soak_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "No resource leaks after sustained concurrent operations".into(),
                "Failure hooks execute within timing budget".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Cross-Worker Parity
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-PARITY-001".into(),
            description: "Cross-worker determinism and parity validation".into(),
            domain: "cross_worker_parity".into(),
            bead_id: "bd-vvmd.7.10".into(),
            test_refs: vec![TestRef {
                file: "cross_worker_parity_e2e.rs".into(),
                name_prefix: "e2e_parity_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Exit codes identical across workers for same input".into(),
                "Artifact hashes match across workers".into(),
                "Toolchain differences detected and reported".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Local-vs-Remote Parity
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-LR-001".into(),
            description: "Local-vs-remote execution parity validation".into(),
            domain: "local_remote_parity".into(),
            bead_id: "bd-vvmd.7.11".into(),
            test_refs: vec![TestRef {
                file: "local_remote_parity_e2e.rs".into(),
                name_prefix: "e2e_lr_parity_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Error codes consistent between local and remote".into(),
                "Schema divergence detection works".into(),
                "Classification parity across execution modes".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Deterministic Replay
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-REPLAY-001".into(),
            description: "Scenario bundle capture, replay, and divergence detection".into(),
            domain: "deterministic_replay".into(),
            bead_id: "bd-vvmd.7.12".into(),
            test_refs: vec![TestRef {
                file: "deterministic_replay_e2e.rs".into(),
                name_prefix: "e2e_replay_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Bundle round-trips through capture/replay".into(),
                "Schema version compatibility checked".into(),
                "Divergence detector reports structural diffs".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Performance Budget
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-PERF-001".into(),
            description: "Hard-gated performance budgets for reliability pipeline".into(),
            domain: "performance_budget".into(),
            bead_id: "bd-vvmd.6.6".into(),
            test_refs: vec![TestRef {
                file: "performance_budget_e2e.rs".into(),
                name_prefix: "e2e_perf_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Hook decision latency under 5ms".into(),
                "Catalog lookup under 1ms".into(),
                "Logging overhead under budget".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-PERF-002".into(),
            description:
                "Remediation hot-path performance budgets + regression suite (admit preflight, \
                 incident append/read, output-mode detection, config load, rejection aggregation)"
                    .into(),
            domain: "performance_budget".into(),
            bead_id: "bd-session-history-remediation-ocv9i.16.7".into(),
            test_refs: vec![
                TestRef {
                    file: "remediation_hotpath_budget_e2e.rs".into(),
                    name_prefix: "budget_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "remediation_hotpath_budget_e2e.rs".into(),
                    name_prefix: "remediation_hotpath_budgets_emit_jsonl".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../scripts/e2e_perf_budgets.sh".into(),
                    name_prefix: "e2e_perf_budgets".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "Admit preflight under compilation budget; non-compilation reject under 1ms".into(),
                "Incident append/read measured with record counts and cold/warm cache cases".into(),
                "Output-mode detection on the non-compilation budget".into(),
                "JSONL timing records carry run_id/bead_id/scenario/event/status/\
                 command_fingerprint/duration_ms/budget_ms/p95_ms/p99_ms/detail"
                    .into(),
                "CI cargo-bench gate + waiver mechanism (perf_budget_waivers.json)".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Redaction & Retention
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-REDACT-001".into(),
            description: "Credential/PII redaction and retention policy enforcement".into(),
            domain: "redaction_retention".into(),
            bead_id: "bd-vvmd.6.10".into(),
            test_refs: vec![
                TestRef {
                    file: "redaction_retention_e2e.rs".into(),
                    name_prefix: "e2e_redaction_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "redaction_retention_e2e.rs".into(),
                    name_prefix: "e2e_retention_".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "No raw secrets in output after redaction pass".into(),
                "Retention policies enforce age-based purge".into(),
                "Incident bundle export respects safe-export policy".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Contract Drift
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-DRIFT-001".into(),
            description: "Cross-project helper contract-drift compatibility validation".into(),
            domain: "contract_drift".into(),
            bead_id: "bd-vvmd.6.11".into(),
            test_refs: vec![TestRef {
                file: "contract_drift_e2e.rs".into(),
                name_prefix: "e2e_compat_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Version matrix compatibility checked".into(),
                "Structured mismatch diffs generated".into(),
                "Fallback behavior validated on version mismatch".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Feature Flags & Rollout
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-FLAGS-001".into(),
            description: "Feature flag states, staged rollout, health gates, auto-disable".into(),
            domain: "feature_flags".into(),
            bead_id: "bd-vvmd.6.7".into(),
            test_refs: vec![TestRef {
                file: "feature_flags_rollout_e2e.rs".into(),
                name_prefix: "e2e_flags_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Flag state transitions valid".into(),
                "Canary scoping enforced".into(),
                "Health gate evaluation correct".into(),
                "Auto-disable triggers fire on threshold breach".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Reliability Doctor
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-DOCTOR-001".into(),
            description: "Reliability doctor diagnostics with actionable remediation".into(),
            domain: "reliability_doctor".into(),
            bead_id: "bd-vvmd.6.9".into(),
            test_refs: vec![TestRef {
                file: "reliability_doctor_e2e.rs".into(),
                name_prefix: "e2e_doctor_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "All diagnostic categories covered".into(),
                "Every non-pass diagnostic has remediation command".into(),
                "Dry-run mode flags unsafe operations".into(),
                "Output deterministic across runs".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: UX Quality
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-UX-001".into(),
            description: "Human-facing reliability output quality and golden snapshots".into(),
            domain: "ux_quality".into(),
            bead_id: "bd-1qhj".into(),
            test_refs: vec![TestRef {
                file: "ux_regression_e2e.rs".into(),
                name_prefix: "e2e_ux_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Golden snapshots for all scenario postures".into(),
                "Reason codes present in all non-healthy outputs".into(),
                "Destructive actions carry risk notes".into(),
                "Redaction clean across all scenarios".into(),
                "Cross-worker parity in narrative structure".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Cancellation
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-CANCEL-001".into(),
            description: "Remote build cancellation and deterministic cleanup semantics".into(),
            domain: "cancellation".into(),
            bead_id: "bd-1yt6".into(),
            test_refs: vec![TestRef {
                file: "fault_injection_e2e.rs".into(),
                name_prefix: "e2e_fault_cancel".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Cancellation state machine transitions valid".into(),
                "Cleanup invariants maintained after cancel".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Structured Logging
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-LOG-001".into(),
            description: "Structured reliability test logger and artifact capture".into(),
            domain: "logging".into(),
            bead_id: "bd-vvmd.7.3".into(),
            test_refs: vec![TestRef {
                file: "smoke.rs".into(),
                name_prefix: "smoke_test_logger".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "JSONL log output conforms to schema".into(),
                "Phase events have required fields".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: E2E Harness Foundation
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-HARNESS-001".into(),
            description: "Reusable reliability E2E harness foundation".into(),
            domain: "harness".into(),
            bead_id: "bd-vvmd.7.7".into(),
            test_refs: vec![TestRef {
                file: "smoke.rs".into(),
                name_prefix: "smoke_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "TestHarnessBuilder creates isolated directories".into(),
                "TestLoggerBuilder produces valid JSONL".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: E2E Script Expansion
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-E2E-001".into(),
            description: "Unified E2E scripts for all reliability families".into(),
            domain: "e2e_scripts".into(),
            bead_id: "bd-vvmd.7.2".into(),
            test_refs: vec![TestRef {
                file: "../tests/e2e/unified_reliability_suite.sh".into(),
                name_prefix: "run_family".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Suite produces machine-readable JSONL phase logs".into(),
                "Suite summary JSON has pass/fail/skip counts".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Deferred Proof Replay
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-PROOF-001".into(),
            description: "Deferred proof replay conveyor + state machine: revalidate source \
                          before replay, honor every safety block, never starve interactive \
                          work, and publish queued/blocked/replaying/passed/failed/stale"
                .into(),
            domain: "proof_replay".into(),
            bead_id: "bd-session-history-remediation-ocv9i.5.3".into(),
            test_refs: vec![TestRef {
                file: "proof_replay_conveyor_e2e.rs".into(),
                name_prefix: "e2e_proof_replay_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Recovery after disk pressure: queued under pressure, replays once it clears"
                    .into(),
                "Source changed while queued transitions to stale and is never replayed".into(),
                "Capability still missing stays blocked with reason RCH-I006".into(),
                "Worker eligible after canary rejoin transitions queued -> replaying".into(),
                "Replay never bypasses a safety block; concurrency cap + FIFO fairness \
                 prevent interactive starvation"
                    .into(),
                "Published record carries state token + stable RCH-Innn reason code".into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Hook Daemon-Recovery
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-HOOK-001".into(),
            description: "Hook socket-failure recovery: classify missing/refused/stale socket and \
                          configured-vs-canonical socket-path mismatch, record a durable \
                          structured incident, autostart + retry once, then proceed remotely or \
                          fall back (fail-open) / refuse (proof mode) loudly"
                .into(),
            domain: "hook_recovery".into(),
            bead_id: "bd-session-history-remediation-ocv9i.3.1".into(),
            test_refs: vec![TestRef {
                file: "hook_socket_recovery_incident_e2e.rs".into(),
                name_prefix: "e2e_hook_socket_".into(),
                tier: "smoke".into(),
            }],
            artifact_assertions: vec![
                "Refused/stale/missing socket records DaemonSocketRefused (RCH-I010) with the \
                 socket_failure failure class"
                    .into(),
                "Wrong configured socket records the configured/canonical mismatch with home \
                 paths redacted"
                    .into(),
                "Daemon start success records only the detection incident (no terminal fallback)"
                    .into(),
                "Daemon start failure records LocalFallback (RCH-I011) with fallback allowed"
                    .into(),
                "Proof-mode refusal records ProofRefusal (RCH-I012) fail-closed (no fallback)"
                    .into(),
                "Incidents survive a process restart and carry a stable RCH-Innn reason token"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-OBS-001".into(),
            description: "Prometheus + OpenTelemetry instrumentation for remediation states \
                          (incident, admission/fallback, proof, queue, worker eligibility, \
                          temporary bypass, canary, disk pressure, telemetry freshness, artifact \
                          retrieval, self-healing) with bounded-cardinality labels and redacted, \
                          OTel-compatible span attributes"
                .into(),
            domain: "observability".into(),
            bead_id: "bd-session-history-remediation-ocv9i.14.5".into(),
            test_refs: vec![
                TestRef {
                    // Lives in rch-telemetry/tests/ (the metrics depend on
                    // prometheus/opentelemetry, which rch-common does not pull in).
                    file: "../../rch-telemetry/tests/remediation_metrics_e2e.rs".into(),
                    name_prefix: "remediation_metrics_scrape_traces_and_evidence".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../rch-telemetry/src/remediation.rs".into(),
                    name_prefix: "register_is_idempotent_and_exposes_all_specs".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "Every remediation metric family appears in a Prometheus scrape with bounded labels"
                    .into(),
                "Incident spans carry stable attributes (event_type, reason_code, source, \
                 selected_mode, command_fingerprint, project_id) plus worker/queue/job ids"
                    .into(),
                "No raw command text, home/absolute paths, or secret-shaped values appear in \
                 metric labels or span attributes (path hashed to blake3:, token masked)"
                    .into(),
                "JSONL evidence emitted with run_id, bead_id, scenario, metric_name, labels, \
                 value, status, and detail"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-UX-002".into(),
            description: "Human dashboard TUI + web remediation views: compact status bands \
                          (desired/live fleet, admissibility, proof queue, jobs, disk pressure, \
                          telemetry freshness, recent incidents) each tagged operator-action / \
                          self-healing / normal-fail-open, assembled once by the daemon and \
                          rendered identically by TUI, CLI, and web with no secret leakage"
                .into(),
            domain: "ux_quality".into(),
            bead_id: "bd-session-history-remediation-ocv9i.14.4".into(),
            test_refs: vec![
                TestRef {
                    // Golden + dashboard-data-adapter + no-leak checks for the
                    // pure assembler (rch_common::remediation_view).
                    file: "remediation_view_golden_e2e.rs".into(),
                    name_prefix: "dashboard_states_have_expected_posture".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "remediation_view_golden_e2e.rs".into(),
                    name_prefix: "no_secret_leaks_across_render_modes".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // TUI overlay snapshot tests for the seven mandated states.
                    file: "../../rch/src/tui/widgets.rs".into(),
                    name_prefix: "test_remediation_overlay_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // E2E runner: dump-state view, redaction, CLI envelope, web surface.
                    file: "../../scripts/e2e_remediation_views.sh".into(),
                    name_prefix: "e2e_remediation_views".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "All eight remediation bands render in canonical order on TUI, CLI, and web".into(),
                "Each band and the overall posture is classified operator-action / self-healing / \
                 normal-fail-open and the seven dashboard states map to the expected class"
                    .into(),
                "No hostnames, SSH users, filesystem paths, or secret-shaped values appear in the \
                 serialized view across JSON (pretty/compact) and Debug renderings"
                    .into(),
                "E2E JSONL emitted with run_id, bead_id, scenario, event, status, route_or_view, \
                 reason_code, duration_ms, and detail"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-PLACEMENT-001".into(),
            description: "First-class placement / visibility / strict-remote controls: a canonical \
                          control registry + pure env->PlacementPlan resolver that never silently \
                          drops a knob (RCH_FORCE_REMOTE vs RCH_REQUIRE_REMOTE force-vs-require, \
                          queue-when-busy, wait timeout, visibility, target-dir), and a \
                          requested-worker admissibility evaluator that yields a structured refusal \
                          (reason code + next action) instead of a silent worker swap. Surfaced via \
                          `rch diagnose` (JSON + human) and `rch capabilities`"
                .into(),
            domain: "ux_quality".into(),
            bead_id: "bd-session-history-remediation-ocv9i.13.5".into(),
            test_refs: vec![
                TestRef {
                    // Golden wire-form + schema pin for PlacementPlan and the
                    // requested-worker refusal vocabulary.
                    file: "placement_golden_e2e.rs".into(),
                    name_prefix: "golden_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // Pure resolver + admissibility evaluator unit tests.
                    file: "../src/placement.rs".into(),
                    name_prefix: "evaluate_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // E2E runner: env-control scenarios over `rch diagnose --json`.
                    file: "../../scripts/e2e_placement_controls.sh".into(),
                    name_prefix: "e2e_placement_controls".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "RCH_FORCE_REMOTE resolves to force_remote (fail-open) and RCH_REQUIRE_REMOTE to \
                 require_remote (fail-closed); both-set yields a precedence diagnostic"
                    .into(),
                "Each requested-worker refusal class (unavailable, admin_disabled, \
                 temporarily_bypassed, wrong_platform, missing_runtime, project_excluded, \
                 no_free_slots) maps to a stable RCH-Innn reason code and a next action"
                    .into(),
                "Unrecognized / superseded control values surface a diagnostic rather than being \
                 silently ignored"
                    .into(),
                "E2E JSONL emitted with run_id, bead_id, command, requested_worker, \
                 effective_worker, strict_remote_policy, queue_policy, visibility_mode, status, \
                 reason_code, duration_ms, and detail"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-DISCOVERY-001".into(),
            description: "Agent discovery surfaces for remediation workflows: `rch capabilities \
                          --json` lists reason-code families (RCH-E/R/I, with the small incident \
                          registry enumerated in full) and placement/fallback policies (fail-open, \
                          force-remote, require-remote/proof, queue); `rch robot-docs guide` carries \
                          machine-readable remediation_workflows (admit-before-proof, proof mode, \
                          worker bypass/auto-rejoin, fleet status, force resync, queue \
                          attach/cancel, real-fleet smoke) keyed to real commands; `--help-json` \
                          resolves and is structurally valid for every real nested path; shell \
                          completions include the new remediation commands/flags"
                .into(),
            domain: "ux_quality".into(),
            bead_id: "bd-session-history-remediation-ocv9i.13.4".into(),
            test_refs: vec![
                TestRef {
                    // Contract tests over the built binary: capabilities families/
                    // policies, robot-docs workflows, --help-json schema-check,
                    // stream separation, TOON parity, completions coverage.
                    file: "../../rch/tests/integration/discovery_surfaces.rs".into(),
                    name_prefix: "test_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // E2E runner: drives the discovery commands and emits JSONL
                    // evidence keyed by bead id and command path.
                    file: "../../scripts/e2e_discovery_surfaces.sh".into(),
                    name_prefix: "e2e_discovery_surfaces".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "capabilities.reason_code_families includes RCH-E, RCH-R, and RCH-I; the RCH-I \
                 family enumerates the incident registry including RCH-I011 (local fallback) and \
                 RCH-I012 (proof refusal)"
                    .into(),
                "capabilities.policies includes require_remote (fail-closed, reason_code RCH-I012), \
                 force_remote (fail-open), fail_open, and queue_when_busy, each with next-action \
                 text"
                    .into(),
                "robot-docs guide remediation_workflows covers the seven named workflows with \
                 runnable commands and next-action/observe text; proof_mode references \
                 RCH_REQUIRE_REMOTE and RCH-I012"
                    .into(),
                "--help-json resolves to the correct leaf for every real nested path and rejects \
                 unknown paths; stdout stays pure JSON while diagnostics stay on stderr"
                    .into(),
                "E2E JSONL emitted with run_id, bead_id, command_path, surface, status, and detail"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-CONFIG-ROLLOUT-001".into(),
            description: "Remediation config rollout across install/init/upgrade/doctor surfaces: \
                          old configs without [remediation] deserialize to safe defaults (no \
                          migration step) and partial sections merge per-field; `rch config \
                          validate/lint/doctor` and the top-level `rch doctor` (run by the \
                          installer/easy-mode) report unsafe/out-of-range/contradictory remediation \
                          settings with concrete remediation; `rch config diff` shows changed \
                          remediation knobs and `rch config export --format json` includes the \
                          remediation section with operator paths redacted; `rch init` writes a \
                          documented [remediation] block without overwriting operator choices"
                .into(),
            domain: "ux_quality".into(),
            bead_id: "bd-session-history-remediation-ocv9i.17.2".into(),
            test_refs: vec![
                TestRef {
                    // Merge/upgrade behavior + surface wiring driven against the
                    // built binary via RCH_CONFIG_DIR.
                    file: "../../rch/tests/integration/config_remediation_rollout.rs".into(),
                    name_prefix: "config_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // E2E runner: drives the config surfaces over a crafted config
                    // and emits JSONL evidence keyed by bead id and surface.
                    file: "../../scripts/e2e_config_rollout.sh".into(),
                    name_prefix: "e2e_config_rollout".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "An old config without a [remediation] section deserializes with the whole \
                 section defaulted (RemediationConfig::default()); partial sections merge per-field"
                    .into(),
                "config validate/lint/doctor and the top-level doctor surface \
                 RemediationConfig::validate() findings (LINT-E101/W101, DOC-E100/W100, the \
                 doctor remediation_config check) each with a concrete next step"
                    .into(),
                "config diff shows changed remediation knobs (e.g. \
                 remediation.policy.hook_exec_fail_open) and config export --format json includes \
                 the remediation section with operator home paths redacted to /home/<redacted>/"
                    .into(),
                "Disabling fail-open / proof-fail-closed is accepted without error; an \
                 out-of-range knob (auto_rejoin.check_interval_secs=0) is reported as an error"
                    .into(),
                "E2E JSONL emitted with run_id, bead_id, surface, command, status, and detail"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        RequirementRow {
            id: "REQ-CONFIG-ROLLOUT-002".into(),
            description: "Config rollout E2E logs and golden tests: integration scenarios over temp \
                          config homes AND project configs (default install writes/loads the \
                          [remediation] block; a project .rch/config.toml override is attributed to \
                          the project file via `config show --sources`; invalid config; \
                          upgrade-from-old); golden output proves config-command JSON envelope \
                          stability, TOON parity, and useful remediation text; E2E script emits \
                          self-validated JSONL with run_id, bead_id, scenario, event, status, \
                          reason_code, config_source, path, detail. Unit coverage of the schema/\
                          default helpers and redaction utilities is provided by 17.1 \
                          (remediation_config_golden_e2e.rs / redaction_policy_golden_e2e.rs)"
                .into(),
            domain: "e2e_scripts".into(),
            bead_id: "bd-session-history-remediation-ocv9i.17.3".into(),
            test_refs: vec![
                TestRef {
                    // Adds default-install, project-override, golden-envelope and
                    // TOON-parity tests to the rollout suite.
                    file: "../../rch/tests/integration/config_remediation_rollout.rs".into(),
                    name_prefix: "config_lint_golden".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // E2E runner emitting the bead's required JSONL field set, with
                    // an in-script schema self-validator.
                    file: "../../scripts/e2e_config_rollout_logs.sh".into(),
                    name_prefix: "e2e_config_rollout_logs".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // Schema/default + redaction unit/golden coverage (17.1).
                    file: "remediation_config_golden_e2e.rs".into(),
                    name_prefix: "golden_".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "Integration scenarios cover default install (init writes [remediation], loads \
                 clean), project override (attributed to project: source via config show \
                 --sources), invalid config, and upgrade-from-old"
                    .into(),
                "Golden config-command output proves envelope stability (success/command/\
                 api_version), lowercase LintSeverity, the LINT-W101 code, and actionable \
                 remediation text; config lint --format toon carries the same code and field"
                    .into(),
                "E2E script emits one JSONL record per scenario/event with run_id, bead_id, \
                 scenario, event, status, reason_code, config_source, path, detail and \
                 self-validates the field set"
                    .into(),
                "Schema/default helpers and redaction utilities have unit + golden coverage in \
                 17.1's remediation_config_golden_e2e.rs and redaction_policy_golden_e2e.rs"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Desired-state fleet reconciliation (epic ocv9i.2)
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-FLEET-001".into(),
            description: "Desired-state fleet reconciliation: `rch status --fleet` reports \
                          desired vs live workers (ready / missing-from-fleet / \
                          recovered-not-rejoined / admin-disabled / temporary-bypass / \
                          unreachable / facts-unknown / command-ineligible / unconfigured), \
                          classifies the dominant problem (cloud disappearance, local \
                          overload, disk pressure, missing capability, admin intent, \
                          daemon/config drift), and raises absence alerts for workers absent \
                          beyond the policy threshold — without treating a transient bypass \
                          as a permanent desired-state edit (no-admissible-workers coverage)"
                .into(),
            domain: "fleet_reconciliation".into(),
            bead_id: "bd-session-history-remediation-ocv9i.2".into(),
            test_refs: vec![
                TestRef {
                    // 2.1: desired-state inventory + live eligibility diff (capacity
                    // collapse explanation, empty fleet, stable serialized tokens).
                    file: "../src/fleet_diff.rs".into(),
                    name_prefix: "fleet_diff_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // 2.2: FleetProblemClass + compute_fleet_status + absence alerts +
                    // stable-shape (golden) serialization.
                    file: "../src/fleet_status.rs".into(),
                    name_prefix: "absence_alerts_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // CLI/E2E surface: `rch status --fleet --json` for empty and
                    // all-absent fleets. Deep classification is proven by the unit
                    // tests above; the live binary run is deferred to CI (stale-binary
                    // precedent), so the .sh existence check is skipped by the matrix.
                    file: "../../scripts/e2e_fleet_reconciliation.sh".into(),
                    name_prefix: "e2e_fleet_reconciliation".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "Empty fleet is explained with zero ready/desired (fleet_diff::empty_fleet_is_explained, \
                 fleet_status::empty_fleet_is_healthy_with_no_alerts)"
                    .into(),
                "All-absent / capacity collapse is classified (fleet_diff::fleet_diff_explains_capacity_collapse, \
                 fleet_status::cloud_disappearance_when_hosts_missing)"
                    .into(),
                "Absence alerts respect the threshold and sort longest-absent first \
                 (fleet_status::absence_alerts_respect_threshold_and_sort_longest_first; \
                 ready_worker_never_raises_absence_alert)"
                    .into(),
                "Stable JSON token/shape golden checks (fleet_diff::fleet_diff_serializes_with_stable_tokens, \
                 fleet_status::report_serializes_with_stable_shape)"
                    .into(),
                "rch status --fleet --json emits a well-formed report for empty and all-absent \
                 fleets; E2E JSONL fields: run_id, bead_id, scenario, event, status, reason_code, \
                 problem_class, detail"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: OS/arch-aware fleet update + post-deploy validation
        // (epic ocv9i.7)
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-FLEET-002".into(),
            description: "OS/arch-aware post-deploy validation runs against the EXACT remote \
                          user/path RCH invokes (never root / login-default / bare PATH-resolved \
                          rch-wkr): probes `uname`/`file`/`--version`, a liveness handshake, and a \
                          capabilities/protocol-JSON handshake. A wrong-OS/arch binary \
                          (`Exec format error`) is marked not eligible with reason_code \
                          `os_arch_mismatch`; a version-skewed/corrupt binary that runs but cannot \
                          emit parseable WorkerCapabilities JSON is marked not eligible with \
                          `capabilities_handshake_failed`; any other non-zero exit is \
                          `post_deploy_validation_failed`. Covers the Darwin-controller -> \
                          Linux-worker regression."
                .into(),
            domain: "fleet_update".into(),
            bead_id: "bd-session-history-remediation-ocv9i.7.3".into(),
            test_refs: vec![
                TestRef {
                    // Exact-path command builders (uname/file/--version, health,
                    // capabilities) — all shell-escaped to $HOME.
                    file: "../../rch/src/fleet/executor.rs".into(),
                    name_prefix: "post_deploy_".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // Exact-path / liveness classifier: Exec format error ->
                    // os_arch_mismatch; generic non-zero -> validation failure.
                    file: "../../rch/src/fleet/executor.rs".into(),
                    name_prefix: "classify_post_deploy".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // Capabilities/protocol handshake classifier: unparseable JSON
                    // -> capabilities_handshake_failed; Exec format error ->
                    // os_arch_mismatch; valid JSON (incl. {}) -> eligible.
                    file: "../../rch/src/fleet/executor.rs".into(),
                    name_prefix: "capabilities_handshake_".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "Exact-path probes are shell-escaped to $HOME, never a bare PATH-resolved rch-wkr \
                 (executor::post_deploy_validation_runs_the_exact_quoted_path, \
                 post_deploy_capabilities_command_runs_the_exact_quoted_path, \
                 post_deploy_health_command_runs_the_exact_quoted_path)"
                    .into(),
                "Exec format error (exit 126 or kernel message) -> NotEligible{os_arch_mismatch} on \
                 both the --version and capabilities probes — the Darwin->Linux regression \
                 (executor::classify_post_deploy_marks_exec_format_ineligible, \
                 capabilities_handshake_exec_format_is_os_arch_mismatch)"
                    .into(),
                "Binary that runs but emits unparseable WorkerCapabilities JSON -> \
                 NotEligible{capabilities_handshake_failed}; valid JSON incl. all-defaults {} -> \
                 Eligible (executor::capabilities_handshake_unparseable_json_is_ineligible, \
                 capabilities_handshake_valid_json_is_eligible)"
                    .into(),
                "Generic non-zero exit -> NotEligible{post_deploy_validation_failed} \
                 (executor::classify_post_deploy_generic_failure_and_success, \
                 capabilities_handshake_nonzero_exit_is_generic_failure)"
                    .into(),
                "Structured ineligibility log fields worker/step/reason_code/detail where step is \
                 exact_path_version|health|capabilities_handshake \
                 (executor::verify_installation warn!/info! tracing)"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Release provenance + signature/checksum + deploy audit
        // (epic ocv9i.7, bead .7.4)
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-FLEET-003".into(),
            description: "Release provenance and signature/checksum verification gate fleet binary \
                          deploys BEFORE transfer: target-triple match, expected-checksum match, \
                          and signature validity are checked under a policy. A wrong-triple, \
                          checksum-mismatch, invalid-signature, or (under strict policy) \
                          missing-signature/checksum artifact is REJECTED fail-closed with a stable \
                          provenance_* reason_code; an artifact with no material is allowed only \
                          when policy permits a dev artifact, recording an explicit reason. A \
                          FleetDeployAuditRecord captures run_id, bead_id, worker_id, remote \
                          user/path, artifact/release id, target_triple, previous artifact, \
                          deployed_at/duration_ms, verification_status, rollback_status, \
                          reason_code, trigger, and detail."
                .into(),
            domain: "fleet_update".into(),
            bead_id: "bd-session-history-remediation-ocv9i.7.4".into(),
            test_refs: vec![
                TestRef {
                    // Pure verification verdicts: verified / dev-allowed / rejected.
                    file: "../src/fleet_provenance.rs".into(),
                    name_prefix: "good_signature".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_provenance.rs".into(),
                    name_prefix: "checksum_mismatch".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_provenance.rs".into(),
                    name_prefix: "wrong_target_triple".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_provenance.rs".into(),
                    name_prefix: "dev_artifact".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    // Deploy audit record shape + serde stability.
                    file: "../src/fleet_provenance.rs".into(),
                    name_prefix: "audit_record".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "Target triple is the highest-priority gate: a wrong-triple artifact is rejected \
                 even with a valid signature (fleet_provenance::wrong_target_triple_is_rejected_even_with_valid_signature)"
                    .into(),
                "Checksum mismatch -> Rejected{provenance_checksum_mismatch}; case-insensitive match \
                 -> Verified (fleet_provenance::checksum_mismatch_is_rejected, \
                 checksum_comparison_is_case_insensitive, checksum_only_match_is_verified)"
                    .into(),
                "Signature: invalid -> Rejected{provenance_signature_invalid} under any policy; \
                 missing under STRICT -> Rejected{provenance_signature_missing}; good signature -> \
                 Verified (fleet_provenance::invalid_signature_is_rejected_under_any_policy, \
                 missing_signature_under_strict_policy_is_rejected, good_signature_and_checksum_is_verified)"
                    .into(),
                "Dev artifact with no material -> DevArtifactAllowed{explicit reason} under \
                 dev-friendly policy, but Rejected{provenance_unverifiable} when dev artifacts are \
                 forbidden; require_checksum with nothing to compare -> Rejected{provenance_checksum_missing} \
                 (fleet_provenance::dev_artifact_is_allowed_with_explicit_reason, \
                 dev_artifact_without_allowance_is_unverifiable, require_checksum_without_value_is_rejected)"
                    .into(),
                "FleetDeployAuditRecord carries verification_status/rollback_status/reason_code + \
                 previous_artifact_id and survives a serde roundtrip; verdict serializes with a stable \
                 snake_case status tag; schema component FleetDeployAudit is version-pinned 1.0.0 \
                 (fleet_provenance::audit_record_from_verdict_carries_status_and_reason, \
                 audit_record_serde_roundtrip_is_stable, verdict_is_tagged_with_snake_case_status, \
                 schema_version_is_pinned)"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Real-fleet smoke/soak validation profile (bead .16.6)
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-SMOKE-001".into(),
            description: "Real-fleet smoke/soak validation profile planning + skip/refusal logic: a \
                          bounded profile (daemon reachability, desired-vs-live fleet, exact \
                          user/path capabilities, disk/inode admission, cargo canary, artifact \
                          retrieval, queue attach/cancel, proof-mode refusal) plans WHICH scenarios \
                          run, which SKIP with a stable reason (no real workers, dry-run, \
                          single-worker selection), and which are EXPECTED to fail closed \
                          (proof-mode refusal when remote execution is unavailable). Emits a \
                          structured SmokeProfileEvent JSONL record."
                .into(),
            domain: "smoke_validation".into(),
            bead_id: "bd-session-history-remediation-ocv9i.16.6".into(),
            test_refs: vec![
                TestRef {
                    file: "../src/fleet_smoke_profile.rs".into(),
                    name_prefix: "no_workers".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_smoke_profile.rs".into(),
                    name_prefix: "proof_refusal".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_smoke_profile.rs".into(),
                    name_prefix: "single_worker".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_smoke_profile.rs".into(),
                    name_prefix: "event_serde".into(),
                    tier: "smoke".into(),
                },
                // Consumer: `rch self-test --smoke` builds inputs from config +
                // daemon reachability, runs the foundation planner, and emits the
                // SmokeProfileEvent JSONL trace (single source of truth = the
                // foundation; live per-worker SSH execution is the operator
                // procedure, paired with .7.4's deploy E2E).
                TestRef {
                    file: "../../rch/src/commands/status.rs".into(),
                    name_prefix: "smoke_planned_events".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../rch/src/commands/status.rs".into(),
                    name_prefix: "build_smoke_inputs".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../scripts/e2e_real_fleet_smoke.sh".into(),
                    name_prefix: "e2e".into(),
                    tier: "smoke".into(),
                },
                // Mock-SSH integration for the capabilities scenario executor
                // (composes the 12.2 capability-probe + admissibility foundation).
                TestRef {
                    file: "../../rch/src/fleet/executor.rs".into(),
                    name_prefix: "smoke_capabilities".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../rch/src/fleet/executor.rs".into(),
                    name_prefix: "smoke_disk_inode".into(),
                    tier: "smoke".into(),
                },
                // Build-pipeline scenario verdicts: cargo canary (remote build
                // completed) + artifact retrieval (rsynced back AND hash-matched,
                // with missing-vs-mismatch split) decided from the daemon
                // self-test result; queue attach/cancel decided from the daemon's
                // deterministic not-found refusal of a synthetic build id.
                TestRef {
                    file: "../../rch/src/commands/status.rs".into(),
                    name_prefix: "smoke_canary_verdict".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../rch/src/commands/status.rs".into(),
                    name_prefix: "smoke_artifact_verdict".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../../rch/src/commands/status.rs".into(),
                    name_prefix: "smoke_cancel_verdict".into(),
                    tier: "smoke".into(),
                },
                // The self-test response timeout waits the per-worker build
                // budget (+margin, capped) instead of the 10s default, so the
                // canary client no longer spuriously times out (RCH-E504).
                TestRef {
                    file: "../../rch/src/commands/helpers.rs".into(),
                    name_prefix: "self_test_run".into(),
                    tier: "smoke".into(),
                },
                // Daemon canary robustness the live run surfaced: self-heal a
                // wedged self-test fixture, and resolve cargo off the daemon's
                // minimal PATH.
                TestRef {
                    file: "../../rchd/src/self_test.rs".into(),
                    name_prefix: "self_test_main_rs_health".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/remote_compilation.rs".into(),
                    name_prefix: "resolve_cargo_binary".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "No real workers configured -> every real-fleet scenario Skip{smoke_no_real_workers}; \
                 daemon reachability still runs (fleet_smoke_profile::no_workers_skips_all_real_scenarios_and_marks_overall_skipped)"
                    .into(),
                "Proof-mode refusal is EXPECTED (fail-closed) when remote execution is unavailable, \
                 and Skip{smoke_remote_available} when it is available — asserted even under --dry-run \
                 (fleet_smoke_profile::proof_refusal_skipped_when_remote_available, \
                 dry_run_marks_buildy_scenarios_dry_but_still_asserts_proof_refusal)"
                    .into(),
                "A single --worker selection skips the fleet-wide desired-vs-live scenario \
                 with reason smoke_not_selected while per-worker scenarios still run \
                 (fleet_smoke_profile::single_worker_selection_skips_fleet_wide_scenario)"
                    .into(),
                "Plan covers every scenario once in run order; full fleet executes 7 scenarios; soak \
                 mode is carried into the plan (fleet_smoke_profile::plan_covers_every_scenario_once_in_order, \
                 full_fleet_runs_all_per_worker_scenarios, soak_mode_is_carried_into_the_plan)"
                    .into(),
                "SmokeProfileEvent JSONL carries run_id/bead_id/worker_id/scenario/event/status/reason_code/\
                 command_fingerprint/duration_ms/remote_target_dir/artifact_summary and survives a serde \
                 roundtrip; daemon-only scenarios drop worker_id \
                 (fleet_smoke_profile::event_serde_roundtrip_is_stable, planned_event_carries_fields_and_omits_worker_for_daemon_scenario)"
                    .into(),
                "Consumer `rch self-test --smoke [--dry-run] [--soak]` derives inputs from config + a \
                 daemon /health probe (remote_execution_available = daemon up AND workers configured), \
                 runs plan_smoke_profile, and emits the planned JSONL trace; scripts/e2e_real_fleet_smoke.sh \
                 drives the safe --dry-run --json surface for empty_fleet/all_absent and self-validates \
                 the plan (8 scenarios) + SmokeProfileEvent fields \
                 (status::tests::{build_smoke_inputs_maps_environment_and_flags, smoke_planned_events_cover_every_scenario_with_reasons})"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
        // ---------------------------------------------------------------
        // Domain: Load fairness / storm control
        // ---------------------------------------------------------------
        RequirementRow {
            id: "REQ-LOAD-001".into(),
            description: "Multi-agent load fairness and storm control: a deterministic mock-worker \
                          E2E launches many concurrent build/test/check jobs with varied runtimes, \
                          slot requests, project roots, and proof/fail-open policies, then proves the \
                          scheduler/admission/queue/fallback/observability stay coherent under \
                          contention — fairness/load-spreading, no duplicate remote job ids, no \
                          unbounded local fallback storm, no stuck wrapper without attach/cancel \
                          guidance, and no work to a temporarily-bypassed / admin-disabled / \
                          capability-inadmissible worker. Emits SmokeProfileEvent JSONL (with \
                          local_job_id, remote_job_id, queue_depth, selected_worker, \
                          fallback_decision, detail) and a StormSummary of regression statistics. \
                          Drives the real job_identity + queue_contract primitives."
                .into(),
            domain: "load_fairness".into(),
            bead_id: "bd-session-history-remediation-ocv9i.10.4".into(),
            test_refs: vec![
                // Mock-worker E2E: concurrent swarm upholds all five invariants,
                // load spreads, ids unique, bounded queue, proof fail-closed,
                // ineligible workers idle, cancellation clean, JSONL persisted.
                TestRef {
                    file: "storm_control_e2e.rs".into(),
                    name_prefix: "e2e_storm_".into(),
                    tier: "smoke".into(),
                },
                // Foundation unit tests: simulator + summary + invariant checkers
                // (including non-vacuous detector tests).
                TestRef {
                    file: "../src/storm_control.rs".into(),
                    name_prefix: "healthy_storm_upholds_all_invariants".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/storm_control.rs".into(),
                    name_prefix: "fairness_spreads_load".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/storm_control.rs".into(),
                    name_prefix: "unique_remote_job_ids".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/storm_control.rs".into(),
                    name_prefix: "proof_jobs_refuse".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/storm_control.rs".into(),
                    name_prefix: "ineligible_workers_never_receive_work".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/storm_control.rs".into(),
                    name_prefix: "detector_catches_".into(),
                    tier: "smoke".into(),
                },
                // The load-mode planning surface (ProfileMode::Load +
                // LoadStormControl scenario token + JSONL field setters).
                TestRef {
                    file: "../src/fleet_smoke_profile.rs".into(),
                    name_prefix: "load_mode_is_carried_into_the_plan".into(),
                    tier: "smoke".into(),
                },
                TestRef {
                    file: "../src/fleet_smoke_profile.rs".into(),
                    name_prefix: "load_event_setters_populate_jsonl_fields".into(),
                    tier: "smoke".into(),
                },
                // Shell E2E that runs the deterministic mock-worker storm suite.
                TestRef {
                    file: "../../scripts/e2e_storm_control.sh".into(),
                    name_prefix: "e2e_storm_control".into(),
                    tier: "smoke".into(),
                },
            ],
            artifact_assertions: vec![
                "A 64-job concurrent swarm (varied runtime/slots/roots, mixed proof/force/fail-open) \
                 upholds all five invariants; every wrapper resolves to a definite disposition \
                 (storm_control_e2e::e2e_storm_concurrent_swarm_upholds_all_invariants)"
                    .into(),
                "Load spreads within tolerance across a heterogeneous fleet; no schedulable worker is \
                 starved (storm_control_e2e::e2e_storm_load_spreads_across_the_fleet, check_load_fairness)"
                    .into(),
                "Every admitted job gets a unique remote_job_id; a forged collision is detected \
                 (storm_control::{unique_remote_job_ids_under_storm, detector_catches_duplicate_remote_ids})"
                    .into(),
                "A bounded queue keeps local fallback bounded; an impossibly-tight cap flags the storm, \
                 proving the checker is non-vacuous (storm_control_e2e::e2e_storm_bounded_queue_prevents_fallback_storm)"
                    .into(),
                "Proof (strict-remote) jobs fail closed — they refuse, never fall back to local — with \
                 the proof reason code (storm_control_e2e::e2e_storm_proof_jobs_fail_closed_never_local)"
                    .into(),
                "Temporarily-bypassed / admin-disabled / capability-inadmissible workers are never \
                 selected and stay at 0 utilization; a forged selection is detected \
                 (storm_control_e2e::e2e_storm_ineligible_workers_never_selected, detector_catches_ineligible_selection)"
                    .into(),
                "Cancelled and not-started jobs carry attach/cancel guidance; a started job with no \
                 terminal event is flagged as a stuck wrapper (storm_control::{detector_catches_stuck_wrapper}, \
                 storm_control_e2e::e2e_storm_cancellation_leaves_no_stuck_wrapper)"
                    .into(),
                "StormSummary records total_jobs, remote_successes, local_fallbacks, proof_refusals, \
                 queue_timeouts, cancellations, p95_queue_wait_ms, p95_end_to_end_ms, and per-worker \
                 slot utilization; the SmokeProfileEvent JSONL trace is persisted to an isolated temp \
                 dir with the full field set and no user files touched \
                 (storm_control_e2e::{e2e_storm_records_summary_statistics, e2e_storm_jsonl_log_persisted_with_full_field_set})"
                    .into(),
            ],
            has_executable_test: true,
            has_log_assertion: true,
            gap: None,
        },
    ];

    let total = requirements.len();
    let covered = requirements
        .iter()
        .filter(|r| r.has_executable_test)
        .count();
    let gaps = requirements.iter().filter(|r| r.gap.is_some()).count();
    let total_refs: usize = requirements.iter().map(|r| r.test_refs.len()).sum();
    let total_artifacts: usize = requirements
        .iter()
        .map(|r| r.artifact_assertions.len())
        .sum();

    let mut domains: Vec<String> = requirements.iter().map(|r| r.domain.clone()).collect();
    domains.sort();
    domains.dedup();

    CoverageMatrix {
        schema_version: COVERAGE_MATRIX_SCHEMA_VERSION.into(),
        requirements,
        summary: MatrixSummary {
            total_requirements: total,
            covered_requirements: covered,
            gap_count: gaps,
            domains,
            total_test_refs: total_refs,
            total_artifact_assertions: total_artifacts,
        },
    }
}

// ===========================================================================
// Staleness verification: test file existence
// ===========================================================================

/// Known test files that the matrix references.
const KNOWN_TEST_FILES: &[&str] = &[
    "cross_repo_path_deps_e2e.rs",
    "dependency_closure_planner.rs",
    "repo_convergence_e2e.rs",
    "process_triage_e2e.rs",
    "fault_injection_e2e.rs",
    "schema_contract_e2e.rs",
    "soak_concurrency_e2e.rs",
    "cross_worker_parity_e2e.rs",
    "local_remote_parity_e2e.rs",
    "deterministic_replay_e2e.rs",
    "performance_budget_e2e.rs",
    "remediation_hotpath_budget_e2e.rs",
    "proof_replay_conveyor_e2e.rs",
    "hook_socket_recovery_incident_e2e.rs",
    "redaction_retention_e2e.rs",
    "contract_drift_e2e.rs",
    "feature_flags_rollout_e2e.rs",
    "reliability_doctor_e2e.rs",
    "ux_regression_e2e.rs",
    "smoke.rs",
    "storm_control_e2e.rs",
];

// ===========================================================================
// Tests: schema stability
// ===========================================================================

#[test]
fn e2e_matrix_schema_version() {
    let matrix = build_coverage_matrix();
    assert_eq!(matrix.schema_version, COVERAGE_MATRIX_SCHEMA_VERSION);
}

#[test]
fn e2e_matrix_serialization_roundtrip() {
    let matrix = build_coverage_matrix();
    let json = serde_json::to_string_pretty(&matrix).unwrap();
    let parsed: CoverageMatrix = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.requirements.len(), matrix.requirements.len());
    assert_eq!(
        parsed.summary.total_requirements,
        matrix.summary.total_requirements
    );
}

// ===========================================================================
// Tests: coverage completeness
// ===========================================================================

#[test]
fn e2e_matrix_every_row_has_executable_test() {
    let matrix = build_coverage_matrix();
    for row in &matrix.requirements {
        assert!(
            row.has_executable_test,
            "requirement '{}' ({}) must have at least one executable test",
            row.id, row.description
        );
    }
}

#[test]
fn e2e_matrix_every_row_has_log_assertion() {
    let matrix = build_coverage_matrix();
    for row in &matrix.requirements {
        assert!(
            row.has_log_assertion,
            "requirement '{}' ({}) must have at least one log/assertion artifact",
            row.id, row.description
        );
    }
}

#[test]
fn e2e_matrix_every_row_has_test_ref() {
    let matrix = build_coverage_matrix();
    for row in &matrix.requirements {
        assert!(
            !row.test_refs.is_empty(),
            "requirement '{}' must have at least one test reference",
            row.id
        );
    }
}

#[test]
fn e2e_matrix_every_row_has_artifact_assertion() {
    let matrix = build_coverage_matrix();
    for row in &matrix.requirements {
        assert!(
            !row.artifact_assertions.is_empty(),
            "requirement '{}' must have at least one artifact assertion",
            row.id
        );
    }
}

#[test]
fn e2e_matrix_no_gaps() {
    let matrix = build_coverage_matrix();
    let gaps: Vec<_> = matrix
        .requirements
        .iter()
        .filter(|r| r.gap.is_some())
        .collect();
    assert!(
        gaps.is_empty(),
        "matrix has {} explicit gaps: {:?}",
        gaps.len(),
        gaps.iter().map(|g| &g.id).collect::<Vec<_>>()
    );
}

// ===========================================================================
// Tests: domain coverage
// ===========================================================================

#[test]
fn e2e_matrix_covers_all_required_domains() {
    let matrix = build_coverage_matrix();
    let required_domains = [
        "path_deps",
        "classification",
        "convergence",
        "disk_pressure",
        "process_triage",
        "fault_injection",
        "schema_contract",
        "soak_concurrency",
        "cross_worker_parity",
        "local_remote_parity",
        "deterministic_replay",
        "performance_budget",
        "redaction_retention",
        "contract_drift",
        "feature_flags",
        "reliability_doctor",
        "ux_quality",
        "cancellation",
        "logging",
        "harness",
        "e2e_scripts",
    ];

    for domain in &required_domains {
        let has = matrix.requirements.iter().any(|r| r.domain == *domain);
        assert!(
            has,
            "required domain '{}' must be covered in the matrix",
            domain
        );
    }
}

#[test]
fn e2e_matrix_no_duplicate_requirement_ids() {
    let matrix = build_coverage_matrix();
    let mut seen = HashMap::new();
    for row in &matrix.requirements {
        if let Some(prev) = seen.insert(&row.id, &row.description) {
            panic!(
                "duplicate requirement ID '{}': '{}' vs '{}'",
                row.id, prev, row.description
            );
        }
    }
}

// ===========================================================================
// Tests: test file staleness check
// ===========================================================================

#[test]
fn e2e_matrix_referenced_test_files_exist() {
    let matrix = build_coverage_matrix();
    let test_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests");

    for row in &matrix.requirements {
        for test_ref in &row.test_refs {
            // Skip shell scripts (they live in a different directory)
            if test_ref.file.ends_with(".sh") {
                continue;
            }
            let path = test_dir.join(&test_ref.file);
            assert!(
                path.exists(),
                "test file '{}' referenced by requirement '{}' does not exist at {:?}",
                test_ref.file,
                row.id,
                path
            );
        }
    }
}

#[test]
fn e2e_matrix_known_test_files_exist() {
    let test_dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests");
    for file in KNOWN_TEST_FILES {
        let path = test_dir.join(file);
        assert!(
            path.exists(),
            "known test file '{}' has been removed or renamed. Update the coverage matrix!",
            file
        );
    }
}

// ===========================================================================
// Tests: summary correctness
// ===========================================================================

#[test]
fn e2e_matrix_summary_counts_correct() {
    let matrix = build_coverage_matrix();
    assert_eq!(matrix.summary.total_requirements, matrix.requirements.len());
    assert_eq!(
        matrix.summary.covered_requirements,
        matrix
            .requirements
            .iter()
            .filter(|r| r.has_executable_test)
            .count()
    );
    assert_eq!(
        matrix.summary.gap_count,
        matrix
            .requirements
            .iter()
            .filter(|r| r.gap.is_some())
            .count()
    );
}

#[test]
fn e2e_matrix_summary_test_ref_count_correct() {
    let matrix = build_coverage_matrix();
    let total_refs: usize = matrix.requirements.iter().map(|r| r.test_refs.len()).sum();
    assert_eq!(matrix.summary.total_test_refs, total_refs);
}

#[test]
fn e2e_matrix_summary_artifact_count_correct() {
    let matrix = build_coverage_matrix();
    let total_artifacts: usize = matrix
        .requirements
        .iter()
        .map(|r| r.artifact_assertions.len())
        .sum();
    assert_eq!(matrix.summary.total_artifact_assertions, total_artifacts);
}

// ===========================================================================
// Tests: bead ID validity
// ===========================================================================

#[test]
fn e2e_matrix_all_bead_ids_well_formed() {
    let matrix = build_coverage_matrix();
    for row in &matrix.requirements {
        assert!(
            row.bead_id.starts_with("bd-"),
            "bead_id '{}' in requirement '{}' must start with 'bd-'",
            row.bead_id,
            row.id
        );
    }
}

// ===========================================================================
// Tests: test tier validity
// ===========================================================================

#[test]
fn e2e_matrix_all_test_tiers_valid() {
    let matrix = build_coverage_matrix();
    let valid_tiers = ["smoke", "nightly", "full"];
    for row in &matrix.requirements {
        for test_ref in &row.test_refs {
            assert!(
                valid_tiers.contains(&test_ref.tier.as_str()),
                "test tier '{}' in requirement '{}' must be one of {:?}",
                test_ref.tier,
                row.id,
                valid_tiers
            );
        }
    }
}

// ===========================================================================
// Tests: deterministic output
// ===========================================================================

#[test]
fn e2e_matrix_output_deterministic() {
    let m1 = build_coverage_matrix();
    let m2 = build_coverage_matrix();
    let json1 = serde_json::to_string(&m1).unwrap();
    let json2 = serde_json::to_string(&m2).unwrap();
    assert_eq!(json1, json2, "matrix output must be deterministic");
}

// ===========================================================================
// Tests: logging integration
// ===========================================================================

#[test]
fn e2e_matrix_logging_integration() {
    use rch_common::e2e::logging::{LogLevel, LogSource, TestLoggerBuilder};

    let logger = TestLoggerBuilder::new("coverage_matrix").build();
    let matrix = build_coverage_matrix();

    logger.log(
        LogLevel::Info,
        LogSource::Custom("coverage_matrix".into()),
        format!(
            "Coverage matrix: {} requirements, {} covered, {} gaps, {} domains",
            matrix.summary.total_requirements,
            matrix.summary.covered_requirements,
            matrix.summary.gap_count,
            matrix.summary.domains.len(),
        ),
    );

    let entries = logger.entries();
    assert_eq!(entries.len(), 1);
    assert!(entries[0].message.contains("requirements"));
}