rch-common 1.0.26

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
//! 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,
        },
        // ---------------------------------------------------------------
        // 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,
        },
    ];

    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",
    "redaction_retention_e2e.rs",
    "contract_drift_e2e.rs",
    "feature_flags_rollout_e2e.rs",
    "reliability_doctor_e2e.rs",
    "ux_regression_e2e.rs",
    "smoke.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"));
}