doctrine 0.12.0

Project tooling CLI
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
// SPDX-License-Identifier: GPL-3.0-only
//! `coverage` — the slice-side coverage store (SL-042 P2, REQ-109).
//!
//! A *coverage entry* is **observed verification evidence** for a requirement:
//! the cited 4-tuple key `(slice, requirement, contributing_change, mode)`, the
//! observed [`CoverageStatus`], the git anchor it was seen at, and (for VH/VA
//! attestations) the date it was attested. Entries live slice-side in
//! `.doctrine/slice/NNN/coverage.toml` as a `[[entry]]` array-of-tables; the
//! reconcile engine (P3/P4) reads them.
//!
//! This module is a **pure leaf** (ADR-001): types + pure folds, no clock / rng /
//! git / disk — all filesystem I/O lives in tests. It owns [`CoverageKey`], the
//! 4-tuple identity/citation key that `rec` aliases as `EvidenceRef` (the cited
//! thing owns its key, not the citer).
//!
//! **Distinct store (NF-001 / ADR-009 §3).** Coverage carries the observed-evidence
//! [`CoverageStatus`], NEVER the authored [`crate::requirement::ReqStatus`]: it does
//! not derive, read, or write authored requirement status. The two stores are
//! separate files — coverage at `.doctrine/slice/NNN/coverage.toml`, authored
//! requirement status in the requirement entity file.

use anyhow::Result;
use serde::{Deserialize, Serialize};

use crate::requirement::{CoverageStatus, ReqStatus};

/// The valid verification modes a coverage entry may cite: by **test** (`VT`), by
/// **agent** (`VA`), or by **human** (`VH`). Membership is validated at the coverage
/// layer (see [`mode_is_valid`]), not by the key's type — `mode` stays a `String`
/// so the `rec` ledger keeps round-tripping arbitrary mode tokens verbatim.
const MODE_VT: &str = "VT";
const MODE_VA: &str = "VA";
const MODE_VH: &str = "VH";
const MODES: &[&str] = &[MODE_VT, MODE_VA, MODE_VH];

/// The stable 4-tuple identity/citation key of a coverage entry (design §5.3 F3):
/// `(slice, requirement, contributing_change, mode)`. Owned here (coverage is the
/// cited thing); `rec` aliases it as `EvidenceRef`. `mode` is a `String`, not an
/// enum — the rec ledger is verbatim and must round-trip arbitrary mode strings;
/// the `∈ {VT,VA,VH}` rule is enforced by [`mode_is_valid`] at this layer.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub(crate) struct CoverageKey {
    pub(crate) slice: String,
    pub(crate) requirement: String,
    pub(crate) contributing_change: String,
    pub(crate) mode: String,
}

/// One coverage entry: the cited [`CoverageKey`] plus its observed payload. The four
/// key fields are `#[serde(flatten)]`ed inline so an `[[entry]]` table reads the
/// key + payload as one flat table. `status` is the **observed-evidence**
/// [`CoverageStatus`] (never authored `ReqStatus` — NF-001). `attested_date` is the
/// VH/VA attestation date; absent (and omitted on render) for plain `VT` evidence.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub(crate) struct CoverageEntry {
    #[serde(flatten)]
    pub(crate) key: CoverageKey,
    pub(crate) status: CoverageStatus,
    pub(crate) git_anchor: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) attested_date: Option<String>,
    /// The repo-relative path set this evidence stands on — the input the
    /// staleness seam ([`crate::git::commits_touching`]) walks `git_anchor..HEAD`
    /// against. Additive (`#[serde(default)]`), so P2 entries without it parse to
    /// an empty set (Unknown-leaning, never falsely Fresh).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) touched_paths: Vec<String>,
    /// The VT-check recipe this entry's evidence is produced from (SL-057): the
    /// alias / literal command, extra args, and the optional output [`Matcher`].
    /// Additive (`#[serde(default)]`, skip-if-none), so pre-SL-057 entries with no
    /// `check` key parse to `None` (the `touched_paths` additive precedent).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) check: Option<VtCheck>,
}

/// The full `coverage.toml` read/written as data: a `[[entry]]` array-of-tables.
/// Defaults to empty so a fresh / absent file parses.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize, Default)]
pub(crate) struct CoverageFile {
    #[serde(default)]
    pub(crate) entry: Vec<CoverageEntry>,
}

/// Collect DISTINCT [`CoverageKey`]s, preserving first-seen order. A key set is a
/// *set* of backing cells — the same 4-tuple key must not be cited twice. The
/// corpus walk can surface a key more than once (a slice tree reachable through
/// both its numeric dir and its slug-alias symlink — ISS-006), so every key-set
/// producer dedupes through HERE: the reconcile writer's `evidence_ref` and the
/// close-gate's residual-evidence set share this one deduper (no parallel twin).
pub(crate) fn distinct_keys(keys: impl Iterator<Item = CoverageKey>) -> Vec<CoverageKey> {
    let mut seen = std::collections::BTreeSet::new();
    let mut out = Vec::new();
    for k in keys {
        let tag = (
            k.slice.clone(),
            k.requirement.clone(),
            k.contributing_change.clone(),
            k.mode.clone(),
        );
        if seen.insert(tag) {
            out.push(k);
        }
    }
    out
}

/// Parse a `coverage.toml` body. Serde auto-unescapes; no hand-templating.
pub(crate) fn parse(s: &str) -> Result<CoverageFile> {
    Ok(toml::from_str(s)?)
}

/// Render a [`CoverageFile`] to its `coverage.toml` body. Serde auto-escapes; no
/// hand-splicing (`crate::tomlfmt::toml_string` exists for the hand-splice case,
/// unneeded here).
pub(crate) fn render(f: &CoverageFile) -> Result<String> {
    Ok(toml::to_string(f)?)
}

/// Whether `mode ∈ {VT, VA, VH}` — the coverage-layer membership rule that the
/// `String`-typed [`CoverageKey::mode`] does not enforce structurally.
pub(crate) fn mode_is_valid(mode: &str) -> bool {
    MODES.contains(&mode)
}

/// The within-file no-clobber fold: if an entry with the same 4-tuple
/// [`CoverageKey`] already exists, REPLACE it in place (latest payload wins);
/// otherwise APPEND. Pure over the in-memory file — no disk.
pub(crate) fn upsert(file: &mut CoverageFile, entry: CoverageEntry) {
    if let Some(existing) = file.entry.iter_mut().find(|e| e.key == entry.key) {
        *existing = entry;
    } else {
        file.entry.push(entry);
    }
}

// ---------------------------------------------------------------------------
// SL-042 P3 — staleness leaf + composite/drift pure folds (REQ-110/111/114).
//
// The purity split (CLAUDE.md pure/imperative; design §5.2): the shell
// (`crate::coverage_scan`) is the ONLY git/disk seam — it resolves each entry's
// `IsStale` and hands the folds in-memory `(CoverageEntry, IsStale)` cells.
// `composite`/`drift` never touch git/disk/clock/rng: staleness arrives already
// resolved, so the verdict is a deterministic function of its inputs.
// ---------------------------------------------------------------------------

/// Whether a coverage cell's evidence is still current relative to its anchor.
/// PRODUCED by the shell (from [`crate::git::commits_touching`]'s `Option<u32>`),
/// CONSUMED by the folds — staleness is never resolved inside a pure fold.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum IsStale {
    /// No commit since the anchor touched the cell's paths (`Some(0)`).
    Fresh,
    /// At least one such commit — evidence may be out of date (`Some(n >= 1)`).
    Stale,
    /// The seam could not decide (`None`): undecidable, treated conservatively.
    Unknown,
}

impl From<Option<u32>> for IsStale {
    /// The seam contract (git §`commits_touching`): `Some(0)` ⇒ Fresh,
    /// `Some(n >= 1)` ⇒ Stale, `None` ⇒ Unknown.
    fn from(count: Option<u32>) -> Self {
        match count {
            Some(0) => IsStale::Fresh,
            Some(_) => IsStale::Stale,
            None => IsStale::Unknown,
        }
    }
}

/// One requirement's fanned-in coverage view: every contributing cell
/// `(CoverageEntry, IsStale)` across slices/changes, sorted by the stable
/// [`CoverageKey`] (DETERMINISTIC — no map-order/clock/rng). v1 surfaces ALL
/// cells with no precedence; it is DERIVED, never persisted.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Composite {
    cells: Vec<(CoverageEntry, IsStale)>,
}

/// Total-order the stable 4-tuple key so [`composite`] is independent of input
/// order (VT-1 determinism). Pure, no allocation beyond the tuple of borrows.
fn key_order(k: &CoverageKey) -> (&str, &str, &str, &str) {
    (
        k.slice.as_str(),
        k.requirement.as_str(),
        k.contributing_change.as_str(),
        k.mode.as_str(),
    )
}

/// Fan one requirement's coverage cells into a deterministic [`Composite`]
/// (design §5.2). Sorts by the stable [`CoverageKey`] so any input permutation
/// yields an identical value. Pure over in-memory input — no disk, no git.
pub(crate) fn composite(entries: &[(CoverageEntry, IsStale)]) -> Composite {
    let mut cells = entries.to_vec();
    cells.sort_by(|a, b| key_order(&a.0.key).cmp(&key_order(&b.0.key)));
    Composite { cells }
}

impl Composite {
    /// No contributing cells at all.
    pub(crate) fn is_empty(&self) -> bool {
        self.cells.is_empty()
    }

    /// Some cell is `Verified` AND [`IsStale::Fresh`] — live, confirming evidence.
    pub(crate) fn any_fresh_verified(&self) -> bool {
        self.cells
            .iter()
            .any(|(e, s)| e.status == CoverageStatus::Verified && *s == IsStale::Fresh)
    }

    /// Some cell ran and contradicted (`Failed`) — the un-acceptable drift source
    /// (SL-179 D1): a check that executed and disagreed. Outranks `Blocked`.
    pub(crate) fn any_failed(&self) -> bool {
        self.cells
            .iter()
            .any(|(e, _)| e.status == CoverageStatus::Failed)
    }

    /// Some cell is `Blocked` — evidence unobtainable (the check could not run).
    /// The acceptable-but-strict drift source (SL-179 D3).
    pub(crate) fn any_blocked(&self) -> bool {
        self.cells
            .iter()
            .any(|(e, _)| e.status == CoverageStatus::Blocked)
    }

    /// Some cell contradicts (`Failed`) or is `Blocked` — an observed problem. The
    /// coarse health summary (the view's `Contradicted` column); the closure gate
    /// reads the sharper [`any_failed`](Self::any_failed) /
    /// [`any_blocked`](Self::any_blocked) split instead.
    pub(crate) fn any_failed_or_blocked(&self) -> bool {
        self.any_failed() || self.any_blocked()
    }

    /// Some cell is `Verified`, [`IsStale::Fresh`], AND cited by mode `VH` — live
    /// confirming **human** evidence (SL-179 D3: the bar that lets an accept-REC
    /// discharge a `Blocked` cell). Consumed by the closure gate
    /// ([`crate::slice`]'s `undischarged_drift`, SL-179 PHASE-03).
    pub(crate) fn has_fresh_vh(&self) -> bool {
        self.cells.iter().any(|(e, s)| {
            e.status == CoverageStatus::Verified && *s == IsStale::Fresh && e.key.mode == MODE_VH
        })
    }

    /// Every cell is still forward-intent (`Planned`/`InProgress`) — nothing yet
    /// claims confirmation or contradiction. Vacuously true on empty; callers
    /// pair it with [`is_empty`](Self::is_empty) where the distinction matters.
    pub(crate) fn only_forward(&self) -> bool {
        self.cells.iter().all(|(e, _)| {
            matches!(
                e.status,
                CoverageStatus::Planned | CoverageStatus::InProgress
            )
        })
    }
}

/// The drift verdict: does authored requirement status cohere with observed
/// coverage? READ-ONLY — it returns NO [`ReqStatus`](crate::requirement::ReqStatus)
/// (NF-001 / ADR-009 §3: no `ReqStatus = f(coverage)` derivation), it only names
/// the relationship for an authoring human to act on.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Verdict {
    /// Authored status and observed evidence agree.
    Coherent,
    /// They disagree — see the [`DivergentReason`].
    Divergent(DivergentReason),
    /// Not enough live evidence to judge (only-stale / mixed / in-force but bare).
    Indeterminate,
}

/// Why a [`Verdict::Divergent`] fired.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DivergentReason {
    /// A check ran and contradicted (`Failed` cell present) — the un-acceptable
    /// drift source (SL-179 D1): no accept-REC discharges it; fix or withdraw.
    ObservedFailure,
    /// Evidence is unobtainable (`Blocked` cell, no live `Failed`) — acceptable
    /// only via a recorded override citing fresh human (VH) evidence (SL-179 D3).
    ObservedBlocked,
    /// Live confirming evidence exists while authored status still trails it
    /// (the accept case — authoring should catch up).
    EvidenceOutrunsAuthored,
}

impl Verdict {
    /// The terse verdict cell text — the SINGLE source of a verdict's display
    /// label (the read's table/JSON render; design §5 D5). Deliberately distinct
    /// from reconcile's `build_prompt` register (two separate registers): this is
    /// a column cell, not an operator prompt. `Divergent` folds in the reason.
    pub(crate) fn label(self) -> String {
        match self {
            Verdict::Coherent => "Coherent".to_owned(),
            Verdict::Indeterminate => "Indeterminate".to_owned(),
            Verdict::Divergent(r) => format!("Divergent: {}", r.label()),
        }
    }
}

impl DivergentReason {
    /// The terse reason token spliced into a `Divergent` verdict label. Borrowed
    /// `&'static str` (no allocation) — [`Verdict::label`] owns the `format!`.
    pub(crate) fn label(self) -> &'static str {
        match self {
            DivergentReason::EvidenceOutrunsAuthored => "evidence-outruns-authored",
            DivergentReason::ObservedFailure => "observed-failure",
            DivergentReason::ObservedBlocked => "observed-blocked",
        }
    }
}

/// The total drift decision tree (design §5.2; every `ReqStatus` × composite-state
/// cell single-valued). Read-only: classifies the authored/observed relationship,
/// never mutates or derives status. Pure — `composite` already carries resolved
/// staleness.
pub(crate) fn drift(authored: ReqStatus, composite: &Composite) -> Verdict {
    use ReqStatus::{Active, Deprecated, InProgress, Pending, Retired, Superseded};

    // Withdrawn statuses assert nothing about live coverage — always coherent.
    if matches!(authored, Retired | Superseded) {
        return Verdict::Coherent;
    }
    // An observed contradiction outranks every in-force reading; a `Failed` cell (a
    // check that ran and disagreed) outranks a `Blocked` one (SL-179 D1 precedence).
    if composite.any_failed() {
        return Verdict::Divergent(DivergentReason::ObservedFailure);
    }
    if composite.any_blocked() {
        return Verdict::Divergent(DivergentReason::ObservedBlocked);
    }
    match authored {
        Pending | InProgress => {
            if composite.any_fresh_verified() {
                Verdict::Divergent(DivergentReason::EvidenceOutrunsAuthored)
            } else if composite.is_empty() || composite.only_forward() {
                Verdict::Coherent
            } else {
                Verdict::Indeterminate
            }
        }
        Active | Deprecated => {
            if composite.is_empty() {
                Verdict::Indeterminate
            } else if composite.any_fresh_verified() {
                Verdict::Coherent
            } else {
                Verdict::Indeterminate
            }
        }
        // Unreachable: the withdrawn set returned Coherent above. Keeping the
        // arm explicit (not `_`) keeps the match total over the 6 variants.
        Retired | Superseded => Verdict::Coherent,
    }
}

// ---------------------------------------------------------------------------
// SL-057 PHASE-01 — pure VT-check model + verdict folds.
//
// A *VT-check* is the recipe a `VT` coverage entry's evidence is produced from:
// an alias (XOR) or a literal `command`, optional `extra_args`, and an optional
// output `Matcher`. This is a PURE leaf (ADR-001): the types + the verdict folds
// below touch NO clock / rng / git / disk / process — running the check and
// reading its output is the shell's job (PHASE-02+). These folds only classify a
// `RunOutcome` the shell hands them, evaluate a matcher over a haystack string,
// and statically validate a `VtCheck`'s shape.
// ---------------------------------------------------------------------------

/// One VT-check recipe (persisted under `[entry.check]`). Either an `alias` into
/// the project base set OR a literal `command` argv — never both (the XOR rule,
/// [`valid`] (a)). `extra_args` are appended to whichever base resolves.
/// `matcher` decides the verdict from the run's output; absent ⇒ exit-code-only.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub(crate) struct VtCheck {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) alias: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) command: Option<Vec<String>>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) extra_args: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) matcher: Option<Matcher>,
}

/// An output matcher: search `source` (defaulting to stdout when absent at the
/// run seam) for `pattern`, as a literal substring (`regex == false`) or a
/// `regex_lite` pattern (`regex == true`). `regex` defaults to `false` on parse.
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub(crate) struct Matcher {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) source: Option<MatchSource>,
    pub(crate) pattern: String,
    #[serde(default)]
    pub(crate) regex: bool,
}

/// Where a [`Matcher`] reads its haystack from.
///
/// **Serde repr (the `coverage.toml` byte surface PHASE-05 goldens pin).** This
/// enum serializes/deserializes as a single TOML **string** scalar (NOT a table),
/// so a [`Matcher`] renders as a clean inline table. The three forms (under
/// `source = …`) are exactly:
///
/// ```toml
/// source = "stdout"
/// source = "stderr"
/// source = "file:.doctrine/spec/tech/*/*.md"
/// ```
///
/// `Stdout ⇄ "stdout"`, `Stderr ⇄ "stderr"`, and `File(glob) ⇄ "file:<glob>"`
/// (literal `file:` prefix, then the glob verbatim). On deserialize, an exact
/// `"stdout"`/`"stderr"` maps to the unit variant, a string starting with `file:`
/// maps to `File(<remainder>)`, and anything else is an unknown-source error. The
/// repr is wired via `#[serde(into / try_from = "String")]` over the [`Display`] /
/// [`TryFrom<String>`] pair below — all three round-trip cleanly (proven by the
/// VT-4 round-trip test). The `File` glob is repo-tree-relative and confined by
/// [`valid`] (c) (no absolute path, no `..` ascent).
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(into = "String", try_from = "String")]
pub(crate) enum MatchSource {
    Stdout,
    Stderr,
    File(String),
}

/// The literal prefix that tags a [`MatchSource::File`] glob in its string repr.
const MATCH_SOURCE_FILE_PREFIX: &str = "file:";

impl std::fmt::Display for MatchSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MatchSource::Stdout => f.write_str("stdout"),
            MatchSource::Stderr => f.write_str("stderr"),
            MatchSource::File(glob) => write!(f, "{MATCH_SOURCE_FILE_PREFIX}{glob}"),
        }
    }
}

impl From<MatchSource> for String {
    fn from(src: MatchSource) -> Self {
        src.to_string()
    }
}

impl TryFrom<String> for MatchSource {
    type Error = String;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        match s.as_str() {
            "stdout" => Ok(MatchSource::Stdout),
            "stderr" => Ok(MatchSource::Stderr),
            other => match other.strip_prefix(MATCH_SOURCE_FILE_PREFIX) {
                Some(glob) => Ok(MatchSource::File(glob.to_owned())),
                None => Err(format!("unknown match source: {other}")),
            },
        }
    }
}

/// The outcome of (attempting to) run a VT-check — produced by the shell, fed to
/// [`derive_status`]. In-memory only (NOT persisted): NO serde derive.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum RunOutcome {
    /// The check could not be obtained/run at all (unresolved alias, spawn
    /// failure, timeout — the F-VII framing). Yields [`CoverageStatus::Blocked`].
    Unobtainable,
    /// The check ran to completion. `exit_ok` is the exit-code verdict; `matched`
    /// is the matcher verdict (`None` ⇒ no matcher present ⇒ exit-code-only).
    Ran {
        exit_ok: bool,
        matched: Option<bool>,
    },
}

/// Classify a [`RunOutcome`] into the observed [`CoverageStatus`] (PURE).
/// `Unobtainable ⇒ Blocked`; a clean exit with no matcher (`matched: None`) or a
/// satisfied matcher (`Some(true)`) ⇒ `Verified`; a non-zero exit OR a failed
/// matcher (`Some(false)`) ⇒ `Failed`. INV-3: `Unobtainable` NEVER yields
/// `Verified`.
pub(crate) fn derive_status(outcome: &RunOutcome) -> CoverageStatus {
    match outcome {
        RunOutcome::Unobtainable => CoverageStatus::Blocked,
        RunOutcome::Ran { exit_ok: false, .. }
        | RunOutcome::Ran {
            exit_ok: true,
            matched: Some(false),
        } => CoverageStatus::Failed,
        RunOutcome::Ran {
            exit_ok: true,
            matched: None | Some(true),
        } => CoverageStatus::Verified,
    }
}

/// Evaluate a matcher pattern over a haystack (PURE). Substring mode
/// (`regex == false`) is `Some(haystack.contains(pattern))` — metacharacters
/// match LITERALLY and the empty pattern is `Some(true)`, NEVER `None`. Regex
/// mode (`regex == true`) compiles under `regex_lite`: a parse error ⇒ `None`,
/// otherwise `Some(re.is_match(haystack))` (the empty pattern matches anything).
pub(crate) fn evaluate_matcher(pattern: &str, regex: bool, haystack: &str) -> Option<bool> {
    if regex {
        match regex_lite::Regex::new(pattern) {
            Ok(re) => Some(re.is_match(haystack)),
            Err(_) => None,
        }
    } else {
        Some(haystack.contains(pattern))
    }
}

/// Why [`valid`] rejected a [`VtCheck`] — one variant per reject reason so callers
/// assert the REASON, not merely `is_err()`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum ValidError {
    /// (a) Both `alias` and `command` are set — they are mutually exclusive.
    AliasCommandConflict,
    /// (b) A non-empty matcher is mandatory unless a literal `command` is set: an
    /// empty-or-absent matcher on an alias, or on the project-default base
    /// (neither alias nor command), is rejected (the D3/A matcher rule).
    MatcherRequired,
    /// (c) A `File` glob escaped the repo tree — an absolute path or a `..` ascent
    /// component (the F-III glob-confinement rule; pure string inspection).
    GlobEscapesTree,
    /// (d) A `regex == true` matcher whose pattern does not parse under
    /// `regex_lite`.
    BadRegex,
}

/// Statically validate a [`VtCheck`]'s shape (PURE, CONFIG-FREE). Enforces the
/// alias/command XOR (a), the mandatory-matcher rule (b), `File`-glob confinement
/// (c), and regex parseability (d). Does NOT resolve the base (does the alias
/// exist? is a default command present?) — that is `verify::resolve`'s job in
/// PHASE-02 (design F-1); this fold never reaches for config.
pub(crate) fn valid(check: &VtCheck) -> Result<(), ValidError> {
    // (a) alias/command XOR.
    if check.alias.is_some() && check.command.is_some() {
        return Err(ValidError::AliasCommandConflict);
    }

    // (b) D3/A: a non-empty matcher is mandatory UNLESS a literal command is set.
    // An empty matcher = matcher is None, or its pattern is "".
    let matcher_empty = match &check.matcher {
        None => true,
        Some(m) => m.pattern.is_empty(),
    };
    if matcher_empty && check.command.is_none() {
        return Err(ValidError::MatcherRequired);
    }

    if let Some(matcher) = &check.matcher {
        // (c) F-III: confine a `File` glob to the repo tree (pure string check).
        if let Some(MatchSource::File(glob)) = &matcher.source {
            let escapes = glob.starts_with('/') || glob.split('/').any(|segment| segment == "..");
            if escapes {
                return Err(ValidError::GlobEscapesTree);
            }
        }
        // (d) regex-mode patterns must parse under regex_lite.
        if matcher.regex && regex_lite::Regex::new(&matcher.pattern).is_err() {
            return Err(ValidError::BadRegex);
        }
    }

    Ok(())
}

#[cfg(test)]
#[expect(
    clippy::unwrap_used,
    reason = "tests: fail-fast unwrap on round-trip/parse is idiomatic"
)]
mod tests {
    use super::*;

    fn key(slice: &str, req: &str, change: &str, mode: &str) -> CoverageKey {
        CoverageKey {
            slice: slice.to_owned(),
            requirement: req.to_owned(),
            contributing_change: change.to_owned(),
            mode: mode.to_owned(),
        }
    }

    fn entry(k: CoverageKey, status: CoverageStatus, attested: Option<&str>) -> CoverageEntry {
        CoverageEntry {
            key: k,
            status,
            git_anchor: "anchor-abc123".to_owned(),
            attested_date: attested.map(str::to_owned),
            touched_paths: Vec::new(),
            check: None,
        }
    }

    /// A synthetic composite cell: one `CoverageEntry` (status varied) paired with
    /// a resolved `IsStale`. Key fields vary so distinct cells stay distinct.
    fn cell(
        slice: &str,
        req: &str,
        change: &str,
        status: CoverageStatus,
        stale: IsStale,
    ) -> (CoverageEntry, IsStale) {
        (entry(key(slice, req, change, "VT"), status, None), stale)
    }

    /// A synthetic cell with an explicit verification `mode` — for the `has_fresh_vh`
    /// predicate, which keys on mode (`VH` vs `VT`/`VA`).
    fn cell_mode(
        slice: &str,
        req: &str,
        change: &str,
        mode: &str,
        status: CoverageStatus,
        stale: IsStale,
    ) -> (CoverageEntry, IsStale) {
        (entry(key(slice, req, change, mode), status, None), stale)
    }

    // --- VT-1: render → parse round-trip preserves every field ---------------

    #[test]
    fn round_trip_preserves_attested_present_and_absent() {
        let file = CoverageFile {
            entry: vec![
                // VH evidence with an attestation date.
                entry(
                    key("SL-042", "REQ-109", "SL-042", "VH"),
                    CoverageStatus::Verified,
                    Some("2026-06-12"),
                ),
                // VT evidence with no attestation date.
                entry(
                    key("SL-042", "REQ-108", "SL-041", "VT"),
                    CoverageStatus::Failed,
                    None,
                ),
            ],
        };

        let back = parse(&render(&file).unwrap()).unwrap();
        assert_eq!(
            back, file,
            "mode + status + git_anchor + attested_date preserved"
        );

        // Spell the per-field preservation out so the VT names what it guards.
        let first = back.entry.first().unwrap();
        assert_eq!(first.key.mode, "VH");
        assert_eq!(first.status, CoverageStatus::Verified);
        assert_eq!(first.git_anchor, "anchor-abc123");
        assert_eq!(first.attested_date.as_deref(), Some("2026-06-12"));
        assert!(back.entry.get(1).unwrap().attested_date.is_none());
    }

    #[test]
    fn empty_file_round_trips() {
        let empty = CoverageFile::default();
        assert_eq!(parse(&render(&empty).unwrap()).unwrap(), empty);
    }

    // --- VT-2: the no-clobber upsert fold ------------------------------------

    #[test]
    fn upsert_distinct_keys_appends() {
        let mut file = CoverageFile::default();
        upsert(
            &mut file,
            entry(
                key("SL-042", "REQ-109", "SL-042", "VT"),
                CoverageStatus::Planned,
                None,
            ),
        );
        upsert(
            &mut file,
            entry(
                key("SL-042", "REQ-108", "SL-042", "VT"),
                CoverageStatus::Verified,
                None,
            ),
        );
        assert_eq!(file.entry.len(), 2, "two distinct keys both surface");
    }

    #[test]
    fn upsert_identical_key_replaces_with_latest_payload() {
        let k = key("SL-042", "REQ-109", "SL-042", "VT");
        let mut file = CoverageFile::default();
        upsert(&mut file, entry(k.clone(), CoverageStatus::Planned, None));
        upsert(
            &mut file,
            entry(k.clone(), CoverageStatus::Verified, Some("2026-06-12")),
        );

        assert_eq!(file.entry.len(), 1, "same key replaces, never duplicates");
        let only = file.entry.first().unwrap();
        assert_eq!(only.status, CoverageStatus::Verified, "latest payload wins");
        assert_eq!(only.attested_date.as_deref(), Some("2026-06-12"));
    }

    #[test]
    fn entries_differing_only_in_slice_coexist() {
        // Two slices contributing evidence for the same requirement: distinct keys.
        let mut file = CoverageFile::default();
        upsert(
            &mut file,
            entry(
                key("SL-042", "REQ-109", "SL-042", "VT"),
                CoverageStatus::Verified,
                None,
            ),
        );
        upsert(
            &mut file,
            entry(
                key("SL-099", "REQ-109", "SL-099", "VT"),
                CoverageStatus::Planned,
                None,
            ),
        );
        assert_eq!(
            file.entry.len(),
            2,
            "same requirement across two slices coexists"
        );
    }

    // --- VT-2b: mode membership validator ------------------------------------

    #[test]
    fn mode_membership_is_vt_va_vh_only() {
        assert!(mode_is_valid("VT"));
        assert!(mode_is_valid("VA"));
        assert!(mode_is_valid("VH"));
        assert!(!mode_is_valid("VX"));
        assert!(!mode_is_valid("vt"));
        assert!(!mode_is_valid(""));
    }

    // --- VT-3: distinct-store, structural ------------------------------------

    #[test]
    fn coverage_entry_carries_observed_status_not_authored_reqstatus() {
        // Compile-level fact, spelled as a test: `CoverageEntry::status` is the
        // observed-evidence `CoverageStatus`, NEVER the authored `ReqStatus`
        // (NF-001 / ADR-009 §3). This line only type-checks because the field is
        // `CoverageStatus`; assigning a `ReqStatus` here would not compile.
        let observed: CoverageStatus = entry(
            key("SL-042", "REQ-109", "SL-042", "VT"),
            CoverageStatus::Verified,
            None,
        )
        .status;
        assert_eq!(observed, CoverageStatus::Verified);
    }

    #[test]
    fn coverage_and_requirement_status_live_in_distinct_stores() {
        // Coverage rides the slice tree; authored requirement status lives in the
        // requirement entity file — distinct paths, distinct stores (NF-001).
        let coverage_path = ".doctrine/slice/042/coverage.toml";
        let requirement_path = ".doctrine/requirement/109/requirement-109.toml";
        assert_ne!(coverage_path, requirement_path);
    }

    // --- P3 T1: touched_paths is additive — P2 entries (no field) still parse ---

    #[test]
    fn p2_entry_without_touched_paths_parses_and_defaults_empty() {
        // A coverage.toml authored before P3 carries no `touched_paths` key.
        let body = r#"
[[entry]]
slice = "SL-042"
requirement = "REQ-109"
contributing_change = "SL-042"
mode = "VT"
status = "verified"
git_anchor = "anchor-abc123"
"#;
        let file = parse(body).unwrap();
        let only = file.entry.first().unwrap();
        assert!(only.touched_paths.is_empty(), "absent field defaults empty");
    }

    #[test]
    fn touched_paths_round_trips_when_present() {
        let mut e = entry(
            key("SL-042", "REQ-110", "SL-042", "VT"),
            CoverageStatus::Verified,
            None,
        );
        e.touched_paths = vec!["src/coverage.rs".to_owned(), "src/git.rs".to_owned()];
        let file = CoverageFile { entry: vec![e] };
        let back = parse(&render(&file).unwrap()).unwrap();
        assert_eq!(back, file, "touched_paths survives the round-trip");
    }

    // --- P3 T2: IsStale constructor from the seam's Option<u32> ----------------

    #[test]
    fn is_stale_from_seam_count() {
        assert_eq!(IsStale::from(Some(0)), IsStale::Fresh);
        assert_eq!(IsStale::from(Some(1)), IsStale::Stale);
        assert_eq!(IsStale::from(Some(42)), IsStale::Stale);
        assert_eq!(IsStale::from(None), IsStale::Unknown);
    }

    // --- VT-1 (REQ-110): composite determinism over input order ---------------

    #[test]
    fn composite_is_order_independent() {
        let ordered = vec![
            cell(
                "SL-040",
                "REQ-110",
                "SL-040",
                CoverageStatus::Verified,
                IsStale::Fresh,
            ),
            cell(
                "SL-042",
                "REQ-110",
                "SL-041",
                CoverageStatus::Planned,
                IsStale::Unknown,
            ),
            cell(
                "SL-041",
                "REQ-110",
                "SL-042",
                CoverageStatus::Failed,
                IsStale::Stale,
            ),
        ];
        // A shuffled permutation of the same cells.
        let shuffled = vec![
            ordered.get(2).unwrap().clone(),
            ordered.first().unwrap().clone(),
            ordered.get(1).unwrap().clone(),
        ];
        assert_eq!(
            composite(&ordered),
            composite(&shuffled),
            "the fold is pure over in-memory input — order cannot change the value"
        );
        // Purity: the fold returns a value; it writes nothing (no disk handle in
        // scope to write to — the type signature is the proof).
    }

    // --- VT-2 (REQ-111): the full ReqStatus × composite-state verdict matrix ---

    /// The five canonical composite states the §5.2 tree branches on, each built
    /// from synthetic in-memory cells (no disk).
    fn composites() -> Vec<(&'static str, Composite)> {
        vec![
            ("empty", composite(&[])),
            (
                "fresh-verified",
                composite(&[cell(
                    "SL-042",
                    "REQ-111",
                    "SL-042",
                    CoverageStatus::Verified,
                    IsStale::Fresh,
                )]),
            ),
            (
                "stale-verified",
                composite(&[cell(
                    "SL-042",
                    "REQ-111",
                    "SL-042",
                    CoverageStatus::Verified,
                    IsStale::Stale,
                )]),
            ),
            (
                "failed-or-blocked",
                composite(&[cell(
                    "SL-042",
                    "REQ-111",
                    "SL-042",
                    CoverageStatus::Failed,
                    IsStale::Fresh,
                )]),
            ),
            (
                "forward-only",
                composite(&[
                    cell(
                        "SL-042",
                        "REQ-111",
                        "SL-042",
                        CoverageStatus::Planned,
                        IsStale::Unknown,
                    ),
                    cell(
                        "SL-043",
                        "REQ-111",
                        "SL-043",
                        CoverageStatus::InProgress,
                        IsStale::Stale,
                    ),
                ]),
            ),
        ]
    }

    #[test]
    fn verdict_matrix_matches_the_decision_tree() {
        use DivergentReason::{EvidenceOutrunsAuthored, ObservedFailure};
        use ReqStatus::{Active, Deprecated, InProgress, Pending, Retired, Superseded};
        use Verdict::{Coherent, Divergent, Indeterminate};

        // Expected verdict per (authored, composite-state) — the §5.2 tree.
        // Order of states: empty, fresh-verified, stale-verified,
        // failed-or-blocked (a `Failed` cell ⇒ ObservedFailure post-SL-179),
        // forward-only.
        let expect: Vec<(ReqStatus, [Verdict; 5])> = vec![
            (
                Pending,
                [
                    Coherent,                           // empty
                    Divergent(EvidenceOutrunsAuthored), // fresh-verified
                    Indeterminate,                      // stale-verified
                    Divergent(ObservedFailure),         // failed-or-blocked
                    Coherent,                           // forward-only
                ],
            ),
            (
                InProgress,
                [
                    Coherent,
                    Divergent(EvidenceOutrunsAuthored),
                    Indeterminate,
                    Divergent(ObservedFailure),
                    Coherent,
                ],
            ),
            (
                Active,
                [
                    Indeterminate,              // empty (in-force, bare)
                    Coherent,                   // fresh-verified
                    Indeterminate,              // stale-verified
                    Divergent(ObservedFailure), // failed-or-blocked
                    Indeterminate,              // forward-only (only-stale/mix)
                ],
            ),
            (
                Deprecated,
                [
                    Indeterminate,
                    Coherent,
                    Indeterminate,
                    Divergent(ObservedFailure),
                    Indeterminate,
                ],
            ),
            (Retired, [Coherent, Coherent, Coherent, Coherent, Coherent]),
            (
                Superseded,
                [Coherent, Coherent, Coherent, Coherent, Coherent],
            ),
        ];

        let states = composites();
        for (authored, row) in &expect {
            for (idx, (label, comp)) in states.iter().enumerate() {
                let got = drift(*authored, comp);
                let want = *row.get(idx).unwrap();
                assert_eq!(
                    got, want,
                    "drift({:?}, {label}) expected {want:?}, got {got:?}",
                    authored
                );
            }
        }
    }

    // --- VT-3 (REQ-114/NF-001): drift returns Verdict, not ReqStatus ----------

    #[test]
    fn drift_returns_verdict_not_reqstatus() {
        // Spelled as a test: drift's return type is `Verdict`. This binding only
        // type-checks because drift returns `Verdict` — a `ReqStatus` binding here
        // would not compile (no `ReqStatus = f(coverage)` derivation; NF-001).
        let v: Verdict = drift(ReqStatus::Active, &composite(&[]));
        assert_eq!(v, Verdict::Indeterminate);
        // (The distinct-store path assertion lives in
        // `coverage_and_requirement_status_live_in_distinct_stores` above — reused,
        // not duplicated.)
    }

    // --- composite predicate units (guard the fold's exposed surface) ---------

    #[test]
    fn composite_predicates_read_the_cells() {
        let c = composite(&[
            cell(
                "SL-042",
                "REQ-111",
                "SL-042",
                CoverageStatus::Verified,
                IsStale::Fresh,
            ),
            cell(
                "SL-043",
                "REQ-111",
                "SL-043",
                CoverageStatus::Planned,
                IsStale::Unknown,
            ),
        ]);
        assert!(!c.is_empty());
        assert!(c.any_fresh_verified());
        assert!(!c.any_failed_or_blocked());
        assert!(!c.only_forward(), "a Verified cell is not forward-only");

        let stale_verified = composite(&[cell(
            "SL-042",
            "REQ-111",
            "SL-042",
            CoverageStatus::Verified,
            IsStale::Stale,
        )]);
        assert!(
            !stale_verified.any_fresh_verified(),
            "stale Verified is not fresh-verified"
        );
    }

    // --- VT-1 (SL-179 PHASE-02): the Failed/Blocked split + has_fresh_vh -------

    #[test]
    fn any_failed_and_any_blocked_read_distinct_statuses() {
        let failed = composite(&[cell(
            "SL-042",
            "REQ-111",
            "SL-042",
            CoverageStatus::Failed,
            IsStale::Fresh,
        )]);
        assert!(failed.any_failed(), "a Failed cell reads any_failed");
        assert!(!failed.any_blocked(), "a Failed cell is not blocked");
        assert!(failed.any_failed_or_blocked(), "OR still true");

        let blocked = composite(&[cell(
            "SL-042",
            "REQ-111",
            "SL-042",
            CoverageStatus::Blocked,
            IsStale::Fresh,
        )]);
        assert!(blocked.any_blocked(), "a Blocked cell reads any_blocked");
        assert!(!blocked.any_failed(), "a Blocked cell is not failed");
        assert!(blocked.any_failed_or_blocked(), "OR still true");
    }

    #[test]
    fn drift_failed_outranks_blocked() {
        // A composite carrying BOTH a Failed and a Blocked cell ⇒ ObservedFailure
        // (Failed outranks Blocked, SL-179 D1 precedence).
        let both = composite(&[
            cell(
                "SL-042",
                "REQ-111",
                "SL-042",
                CoverageStatus::Failed,
                IsStale::Fresh,
            ),
            cell(
                "SL-043",
                "REQ-111",
                "SL-043",
                CoverageStatus::Blocked,
                IsStale::Fresh,
            ),
        ]);
        assert_eq!(
            drift(ReqStatus::Active, &both),
            Verdict::Divergent(DivergentReason::ObservedFailure),
            "Failed outranks Blocked"
        );

        // Blocked-only ⇒ ObservedBlocked.
        let blocked_only = composite(&[cell(
            "SL-042",
            "REQ-111",
            "SL-042",
            CoverageStatus::Blocked,
            IsStale::Fresh,
        )]);
        assert_eq!(
            drift(ReqStatus::Active, &blocked_only),
            Verdict::Divergent(DivergentReason::ObservedBlocked),
            "Blocked-only ⇒ ObservedBlocked"
        );
    }

    #[test]
    fn has_fresh_vh_keys_on_mode_status_and_freshness() {
        // A fresh Verified cell cited by VH ⇒ true.
        let vh = composite(&[cell_mode(
            "SL-042",
            "REQ-111",
            "SL-042",
            "VH",
            CoverageStatus::Verified,
            IsStale::Fresh,
        )]);
        assert!(vh.has_fresh_vh(), "fresh Verified VH ⇒ has_fresh_vh");

        // Same cell cited by VT or VA ⇒ false (not a human attestation).
        for mode in ["VT", "VA"] {
            let non_vh = composite(&[cell_mode(
                "SL-042",
                "REQ-111",
                "SL-042",
                mode,
                CoverageStatus::Verified,
                IsStale::Fresh,
            )]);
            assert!(
                !non_vh.has_fresh_vh(),
                "{mode} Verified is not a human (VH) attestation"
            );
        }

        // A STALE VH Verified cell ⇒ false (not live).
        let stale_vh = composite(&[cell_mode(
            "SL-042",
            "REQ-111",
            "SL-042",
            "VH",
            CoverageStatus::Verified,
            IsStale::Stale,
        )]);
        assert!(!stale_vh.has_fresh_vh(), "stale VH is not live");

        // A fresh VH cell that is NOT Verified (e.g. Failed) ⇒ false.
        let vh_failed = composite(&[cell_mode(
            "SL-042",
            "REQ-111",
            "SL-042",
            "VH",
            CoverageStatus::Failed,
            IsStale::Fresh,
        )]);
        assert!(
            !vh_failed.has_fresh_vh(),
            "a non-Verified VH cell is not confirming"
        );
    }

    // === SL-057 PHASE-01: VT-check model + verdict folds =====================

    /// Build a [`VtCheck`] from the parts a test cares about; the rest default.
    fn vtcheck(
        alias: Option<&str>,
        command: Option<Vec<&str>>,
        matcher: Option<Matcher>,
    ) -> VtCheck {
        VtCheck {
            alias: alias.map(str::to_owned),
            command: command.map(|c| c.into_iter().map(str::to_owned).collect()),
            extra_args: Vec::new(),
            matcher,
        }
    }

    /// A [`Matcher`] over the given source/pattern/regex-flag.
    fn matcher(source: Option<MatchSource>, pattern: &str, regex: bool) -> Matcher {
        Matcher {
            source,
            pattern: pattern.to_owned(),
            regex,
        }
    }

    // --- VT-1: derive_status truth table (INV-3 included) --------------------

    #[test]
    fn derive_status_truth_table() {
        // Unobtainable ⇒ Blocked.
        assert_eq!(
            derive_status(&RunOutcome::Unobtainable),
            CoverageStatus::Blocked
        );
        // Clean exit, no matcher ⇒ Verified (exit-code-only).
        assert_eq!(
            derive_status(&RunOutcome::Ran {
                exit_ok: true,
                matched: None
            }),
            CoverageStatus::Verified
        );
        // Clean exit, matcher satisfied ⇒ Verified.
        assert_eq!(
            derive_status(&RunOutcome::Ran {
                exit_ok: true,
                matched: Some(true)
            }),
            CoverageStatus::Verified
        );
        // Non-zero exit (matcher irrelevant) ⇒ Failed.
        assert_eq!(
            derive_status(&RunOutcome::Ran {
                exit_ok: false,
                matched: None
            }),
            CoverageStatus::Failed
        );
        assert_eq!(
            derive_status(&RunOutcome::Ran {
                exit_ok: false,
                matched: Some(true)
            }),
            CoverageStatus::Failed
        );
        // Clean exit but matcher failed ⇒ Failed.
        assert_eq!(
            derive_status(&RunOutcome::Ran {
                exit_ok: true,
                matched: Some(false)
            }),
            CoverageStatus::Failed
        );
    }

    #[test]
    fn inv3_unobtainable_never_verified() {
        // INV-3: no Unobtainable path yields Verified.
        assert_ne!(
            derive_status(&RunOutcome::Unobtainable),
            CoverageStatus::Verified
        );
    }

    // --- VT-2: evaluate_matcher (substring + regex) --------------------------

    #[test]
    fn evaluate_matcher_substring_literal_and_metachars() {
        // Plain substring match / miss.
        assert_eq!(evaluate_matcher("ok", false, "all ok here"), Some(true));
        assert_eq!(evaluate_matcher("nope", false, "all ok here"), Some(false));
        // Metacharacters match LITERALLY in substring mode: `a.c` does NOT match
        // "abc" (the `.` is a literal dot) but DOES match "a.c".
        assert_eq!(evaluate_matcher("a.c", false, "abc"), Some(false));
        assert_eq!(evaluate_matcher("a.c", false, "xx a.c yy"), Some(true));
        // Empty pattern ⇒ Some(true), never None.
        assert_eq!(evaluate_matcher("", false, "anything"), Some(true));
        assert_eq!(evaluate_matcher("", false, ""), Some(true));
    }

    #[test]
    fn evaluate_matcher_regex_mode() {
        // Regex match / miss.
        assert_eq!(evaluate_matcher("a.c", true, "abc"), Some(true));
        assert_eq!(evaluate_matcher("a.c", true, "axyzc"), Some(false));
        // Unparseable regex ⇒ None.
        assert_eq!(evaluate_matcher("(", true, "anything"), None);
        // Empty pattern ⇒ Some(true) under regex_lite too.
        assert_eq!(evaluate_matcher("", true, "anything"), Some(true));
    }

    // --- VT-3: valid reject matrix (assert the SPECIFIC variant) -------------

    #[test]
    fn valid_rejects_alias_command_conflict() {
        let check = vtcheck(
            Some("test"),
            Some(vec!["cargo", "test"]),
            Some(matcher(None, "ok", false)),
        );
        assert_eq!(valid(&check), Err(ValidError::AliasCommandConflict));
    }

    #[test]
    fn valid_rejects_empty_matcher_on_alias() {
        // Absent matcher on an alias ⇒ MatcherRequired.
        assert_eq!(
            valid(&vtcheck(Some("test"), None, None)),
            Err(ValidError::MatcherRequired)
        );
        // Empty-pattern matcher on an alias ⇒ MatcherRequired.
        assert_eq!(
            valid(&vtcheck(Some("test"), None, Some(matcher(None, "", false)))),
            Err(ValidError::MatcherRequired)
        );
    }

    #[test]
    fn valid_rejects_empty_matcher_on_default_base() {
        // Neither alias nor command (project-default base): absent matcher rejected.
        assert_eq!(
            valid(&vtcheck(None, None, None)),
            Err(ValidError::MatcherRequired)
        );
    }

    #[test]
    fn valid_accepts_empty_matcher_with_literal_command() {
        // An empty/absent matcher is legal ONLY alongside a literal command.
        assert_eq!(valid(&vtcheck(None, Some(vec!["true"]), None)), Ok(()));
        assert_eq!(
            valid(&vtcheck(
                None,
                Some(vec!["true"]),
                Some(matcher(None, "", false))
            )),
            Ok(())
        );
    }

    #[test]
    fn valid_rejects_absolute_file_glob() {
        let check = vtcheck(
            Some("test"),
            None,
            Some(matcher(
                Some(MatchSource::File("/etc/x".to_owned())),
                "ok",
                false,
            )),
        );
        assert_eq!(valid(&check), Err(ValidError::GlobEscapesTree));
    }

    #[test]
    fn valid_rejects_ascending_file_glob() {
        let check = vtcheck(
            Some("test"),
            None,
            Some(matcher(
                Some(MatchSource::File("../x".to_owned())),
                "ok",
                false,
            )),
        );
        assert_eq!(valid(&check), Err(ValidError::GlobEscapesTree));
        // A `..` nested deeper in the path is caught too.
        let nested = vtcheck(
            Some("test"),
            None,
            Some(matcher(
                Some(MatchSource::File(".doctrine/spec/tech/../../x".to_owned())),
                "ok",
                false,
            )),
        );
        assert_eq!(valid(&nested), Err(ValidError::GlobEscapesTree));
    }

    #[test]
    fn valid_rejects_unparseable_regex() {
        let check = vtcheck(Some("test"), None, Some(matcher(None, "(", true)));
        assert_eq!(valid(&check), Err(ValidError::BadRegex));
    }

    #[test]
    fn valid_accepts_wellformed_alias_with_matcher() {
        let check = vtcheck(
            Some("test"),
            None,
            Some(matcher(Some(MatchSource::Stdout), "ok", false)),
        );
        assert_eq!(valid(&check), Ok(()));
        // A relative File glob with no ascent is fine.
        let file_ok = vtcheck(
            Some("test"),
            None,
            Some(matcher(
                Some(MatchSource::File(".doctrine/spec/tech/*/*.md".to_owned())),
                "ok",
                false,
            )),
        );
        assert_eq!(valid(&file_ok), Ok(()));
    }

    // --- VT-4: MatchSource serde repr round-trips all three variants ---------

    #[test]
    fn match_source_serde_repr_all_three_variants() {
        // Render each variant inside a full entry and assert the exact byte form,
        // then parse it back — this pins the PHASE-05 golden surface.
        for (src, token) in [
            (MatchSource::Stdout, "\"stdout\""),
            (MatchSource::Stderr, "\"stderr\""),
            (
                MatchSource::File(".doctrine/spec/tech/*/*.md".to_owned()),
                "\"file:.doctrine/spec/tech/*/*.md\"",
            ),
        ] {
            let m = matcher(Some(src.clone()), "ok", false);
            let rendered = toml::to_string(&m).unwrap();
            assert!(
                rendered.contains(&format!("source = {token}")),
                "expected `source = {token}` in:\n{rendered}"
            );
            let back: Matcher = toml::from_str(&rendered).unwrap();
            assert_eq!(back.source, Some(src), "MatchSource round-trips");
        }
    }

    #[test]
    fn vtcheck_full_round_trip_through_entry() {
        // A full VtCheck (alias + extra_args + File matcher) survives the
        // CoverageEntry render → parse round-trip.
        let mut e = entry(
            key("SL-057", "REQ-200", "SL-057", "VT"),
            CoverageStatus::Verified,
            None,
        );
        e.check = Some(VtCheck {
            alias: Some("test".to_owned()),
            command: None,
            extra_args: vec!["--quiet".to_owned()],
            matcher: Some(matcher(
                Some(MatchSource::File(
                    ".doctrine/spec/tech/003/spec-003.md".to_owned(),
                )),
                "PASS",
                true,
            )),
        });
        let file = CoverageFile { entry: vec![e] };
        let back = parse(&render(&file).unwrap()).unwrap();
        assert_eq!(back, file, "the full VtCheck round-trips byte-clean");
    }

    #[test]
    fn vtcheck_command_variant_round_trips() {
        // The `command` (literal argv) + Stderr-source variant also round-trips.
        let mut e = entry(
            key("SL-057", "REQ-201", "SL-057", "VT"),
            CoverageStatus::Verified,
            None,
        );
        e.check = Some(vtcheck(
            None,
            Some(vec!["cargo", "test"]),
            Some(matcher(Some(MatchSource::Stderr), "ok", false)),
        ));
        let file = CoverageFile { entry: vec![e] };
        let back = parse(&render(&file).unwrap()).unwrap();
        assert_eq!(back, file);
    }

    #[test]
    fn pre_sl057_entry_without_check_parses_to_none() {
        // A pre-SL-057 [[entry]] body carries no `check` key — it must still parse,
        // with `check == None` (the additive-field precedent).
        let body = r#"
[[entry]]
slice = "SL-042"
requirement = "REQ-109"
contributing_change = "SL-042"
mode = "VT"
status = "verified"
git_anchor = "anchor-abc123"
"#;
        let file = parse(body).unwrap();
        assert!(
            file.entry.first().unwrap().check.is_none(),
            "absent check defaults None"
        );
    }
}