memstead-base 0.12.0

Engine internals for Memstead — store, parser, validators, filesystem-mem engine. Internal library surface consumed by the memstead binaries — pre-1.0, experimental, no API stability promise.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
//! The **tier-1 fidelity report** (bundle plan `05-verify-sync-engine`, group
//! B) — deterministic, engine-rendered, token-budgeted.
//!
//! Verify (group A) records durable findings; this module *renders* a
//! measurement over them plus the live anchor / capability / freshness state.
//! It performs **no LLM call** and **no destination-mem mutation** — it reads
//! the engine, the findings store, the advance store, and the capability
//! matrix, and formats a report. Any repair instruction is the sync brief's job
//! (group C), never this report's.
//!
//! ## What the report states honestly (B1–B5)
//!
//! - **Grain-classed coverage** with tree-anchor fan-out kept on its **own
//!   axis** — a 1-entity/200-file tree anchor shows as one anchor fanning out
//!   over 200 files, never laundered into a blended coverage percentage (B1).
//! - **Anchor-resolution %** over the mem's observed anchors, with `authored`
//!   provenance **excluded** from the coverage/accuracy denominators and shown
//!   as its own bucket (B1).
//! - **Freshness** vs. both `sync_state` tokens (`#synced` / `#verified`). A
//!   detection-less medium (the capability matrix marks it non-change-
//!   detectable) renders `signal: none` → *"freshness unknowable"*; a green
//!   freshness verdict is **structurally unreachable** for such a medium (B2).
//! - **Token-budgeted** in the house envelope shape shared with
//!   [`crate::overview`]: aggregates are hard-required and always ship; heavy
//!   per-artifact lists greedy-fill by priority and, when they do not fit,
//!   drop to `## Hints` with an `estimated_tokens` figure — never rendered
//!   unbounded (B3).
//! - **Coverage semantics** branch: under `curated`, the unaccounted share is
//!   information; under `exhaustive`, unaccounted artifacts (not anchored, not
//!   declared-excluded, no persisted disposition) are findings (B4).
//! - **Denominator provenance** is stated: coverage is relative to the
//!   per-medium enumeration `S(D)` (B5).

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;

use serde::Serialize;

use crate::Engine;
use crate::anchor::{AnchorGrain, AnchorProvenanceClass, AnchorState};
use crate::binding::{Binding, CoverageSemantics, MediumCapabilities, medium_capabilities};
use crate::chunking::estimate_tokens;

use super::advance::read_advance_store;
use super::cursor::{enumerate_source_artifacts, source_moved};
use super::findings::{FindingClass, FindingKey, read_findings_store};
use super::resolve::{ChangeStrategy, ResolvedIngest, ResolvedSource, resolve_change_strategy};

/// Default token budget for the report's heavy content. Mirrors
/// [`crate::overview::DEFAULT_OVERVIEW_BUDGET`] — one house envelope, one
/// default.
pub const DEFAULT_REPORT_BUDGET: usize = 8_000;

/// Heavy-content include keys the renderer recognises, in **greedy-fill
/// priority order**. A key listed in `include` forces its section in past the
/// budget (mirroring the overview envelope); an unlisted key greedy-fills until
/// the budget is exhausted, then surfaces as a hint. An unknown key is ignored
/// with a warning line.
pub const ALLOWED_REPORT_INCLUDE_KEYS: &[&str] =
    &["uncovered_artifacts", "tree_fanout", "superseded_findings"];

// ---------------------------------------------------------------------------
// Structured report — the deterministic, pre-computed data the pure renderer
// formats. Assembling it (`compute_fidelity_report`) reads the engine; the
// renderer (`render_fidelity_report`) is a pure function over this data, so
// every B1–B5 assertion tests against a hand-built value with no IO.
// ---------------------------------------------------------------------------

/// The denominator basis for coverage (B5): coverage is reported relative to
/// the per-medium enumeration `S(D)`, or — when the medium cannot be
/// enumerated — the report says so rather than inventing a denominator.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum DenominatorBasis {
    /// `S(D)` was enumerated: `count` source artifacts in scope (after
    /// `deny_paths`), the coverage denominator.
    Enumerated {
        /// `|S(D)|` — the enumerated source-artifact count.
        count: usize,
    },
    /// The medium is non-enumerable (or its type is not enumerated this cycle):
    /// no `S(D)`, so coverage is reported over anchors only and the denominator
    /// is stated unavailable.
    NonEnumerable {
        /// Why no `S(D)` could be computed.
        reason: String,
    },
}

/// One tree-grain anchor's fan-out over `S(D)` (B1). A tree anchor is one row
/// here whatever its fan-out — the per-file count is an observation, never a
/// per-file coverage credit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TreeFanout {
    /// The entity id carrying the tree anchor.
    pub entity: String,
    /// The tree artifact reference.
    pub artifact: String,
    /// How many `S(D)` files fall under this tree.
    pub fanout: usize,
}

/// Grain-classed coverage over `S(D)` (B1). Tree-anchor fan-out is a **separate
/// axis** — `direct_covered` and `tree_only_covered` are never summed into one
/// blended percentage.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct GrainCoverage {
    /// The denominator basis (B5).
    pub denominator: DenominatorBasis,
    /// `S(D)` files directly covered by a non-tree (file / span) anchor.
    pub direct_covered: usize,
    /// `S(D)` files covered **only** via a tree-grain anchor (the fan-out axis,
    /// kept distinct from `direct_covered`).
    pub tree_only_covered: usize,
    /// `S(D)` files with no anchor at all (the heavy artifact list).
    pub uncovered: Vec<String>,
    /// Per tree anchor, its fan-out over `S(D)` (the heavy detail list).
    pub tree_anchors: Vec<TreeFanout>,
}

/// Anchor composition + resolution tally over the destination mem's anchors
/// (B1). `authored` provenance is pulled into its own bucket and **excluded**
/// from the resolution (coverage/accuracy) tally.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Default)]
pub struct AnchorComposition {
    /// Count per provenance-class wire string across **all** the mem's anchors
    /// (the full transparency breakdown, including `authored`).
    pub by_class: BTreeMap<String, usize>,
    /// Count per grain wire string across all the mem's anchors.
    pub by_grain: BTreeMap<String, usize>,
    /// `authored`-class anchors — the own bucket, excluded from the resolution
    /// denominator below.
    pub authored: usize,
    /// Non-`authored` anchors that carry a resolution state this pass.
    pub observed: usize,
    /// Non-`authored` anchors that resolved clean.
    pub resolves: usize,
    /// Non-`authored` anchors that drifted (stable-medium hash break).
    pub drifted: usize,
    /// Non-`authored` anchors deferred for re-examination (unstable / no hash).
    pub recheck: usize,
    /// Non-`authored` anchors whose artifact is gone.
    pub orphaned: usize,
    /// Non-`authored` anchors that could **not** be observed this pass (state
    /// `None`) — reported honestly, never counted as resolved.
    pub unobserved: usize,
}

/// One facet's capability-matrix row + resolved change signal (B1 capability
/// block; B2 change-detectability; B5 enumeration provenance).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FacetCapability {
    /// The source facet.
    pub facet: String,
    /// The medium type wire string.
    pub medium_type: String,
    /// Whether the medium's scope is enumerable (`S(D)` computable).
    pub enumerable: bool,
    /// Whether the medium provides a change signal.
    pub change_signal: bool,
    /// Whether a base version is retrievable (three-way-merge feasibility).
    pub base_version_retrievable: bool,
    /// The anchor namespace (`path` / `path+commit` / `entity` / `url`).
    pub anchor_namespace: String,
    /// The resolved change-detection signal (`git` / `mtime` / `graph` /
    /// `none`).
    pub signal: String,
}

impl FacetCapability {
    fn from_caps(
        facet: String,
        medium_type: String,
        caps: MediumCapabilities,
        strategy: ChangeStrategy,
    ) -> Self {
        FacetCapability {
            facet,
            medium_type,
            enumerable: caps.enumerable,
            change_signal: caps.change_signal,
            // Effective, not the static ceiling: a base version is retrievable
            // only when the *resolved* strategy actually holds prior content.
            // `mtime` reports that an artifact changed, not its previous bytes,
            // and `none` detects nothing — either degrades prune to
            // conflict-flagging even on a medium whose type-level capability
            // row (e.g. filesystem) advertises base retrievability.
            base_version_retrievable: caps.base_version_retrievable
                && strategy_retrieves_base(strategy),
            anchor_namespace: caps.anchor_namespace.to_string(),
            signal: signal_wire(strategy).to_string(),
        }
    }
}

/// One facet's freshness state vs. both `sync_state` tokens (B1/B2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FacetFreshness {
    /// The source facet.
    pub facet: String,
    /// The resolved change signal (`git` / `mtime` / `graph` / `none`).
    pub signal: String,
    /// The `#synced` baseline token, or `None` when never synced.
    pub synced: Option<String>,
    /// The `#verified` baseline token, or `None` when never verified.
    pub verified: Option<String>,
    /// Whether the medium is change-detectable at all: the capability matrix
    /// marks a change signal **and** a strategy resolved (signal ≠ `none`).
    /// When `false`, freshness is **unknowable** and the renderer is
    /// structurally incapable of printing a green verdict for this facet (B2).
    pub change_detectable: bool,
}

/// The tier-1 fidelity report — fully computed, deterministic data.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FidelityReport {
    /// The canonical binding id `<mem>/<stem>`.
    pub binding: String,
    /// The destination mem.
    pub destination_mem: String,
    /// Whether the destination mem predates its binding — the adopt / onboarding
    /// case (E1). When `true`, the report leads with the expected-0%-anchored
    /// onboarding framing and the concrete backfill path, and the coverage
    /// section frames uncovered artifacts as the backfill worklist rather than
    /// as defects: no failure/error framing and no red verdict is produced
    /// **solely** by pre-binding history.
    pub adopt: bool,
    /// The binding's EFFECTIVE coverage (B4) — declared when the author
    /// wrote the field, otherwise resolved per medium
    /// ([`crate::binding::effective_coverage_semantics`]).
    pub coverage_semantics: CoverageSemantics,
    /// `true` when the binding declared the field; `false` when the
    /// effective value was resolved from the sources' media. The render
    /// marks the resolved case so a reader never mistakes a resolution
    /// for an author's assertion.
    pub coverage_semantics_declared: bool,
    /// Per-facet capability rows (B1 capability block).
    pub capabilities: Vec<FacetCapability>,
    /// Per-facet freshness (B1/B2).
    pub freshness: Vec<FacetFreshness>,
    /// Binding-level: has any change-detectable source moved past its `#synced`
    /// baseline this pass? `None` when no source is change-detectable (nothing
    /// to compare) — never a fabricated `false`.
    pub source_moved_past_synced: Option<bool>,
    /// Grain-classed coverage over `S(D)` (B1/B5).
    pub coverage: GrainCoverage,
    /// Anchor composition + resolution (B1).
    pub anchors: AnchorComposition,
    /// Findings tally by class over the current key.
    pub findings_by_class: BTreeMap<String, usize>,
    /// Tier-3 backlog depth — findings queued for adjudication (B1).
    pub backlog: usize,
    /// Findings recorded under a **prior** `(hash(D), source_head)` key,
    /// segregated as superseded (the heavy detail list is the count's backing).
    pub superseded: Vec<String>,
    /// Persisted dispositions that exclude an otherwise-uncovered artifact from
    /// the exhaustive findings set (B4) — the count (`= disposed_excluded_rationales.len()`).
    pub disposed_excluded: usize,
    /// The durable authored-exclusion ledger consulted under exhaustive coverage
    /// (B4): `(artifact, rationale)` for each uncovered artifact a persisted
    /// disposition marks deliberately excluded. Removed from the findings /
    /// backfill denominator and rendered with its reasoning so the editorial
    /// decision stays visible.
    pub disposed_excluded_rationales: Vec<(String, String)>,
    /// Degradation flags (B1) — typed, human/agent-readable strings.
    pub degradations: Vec<String>,
}

// ---------------------------------------------------------------------------
// Rollup verdict
// ---------------------------------------------------------------------------

/// The one-word answer a CI gate and a human reader branch on, derived from
/// an assembled [`FidelityReport`] — never measured separately, so it cannot
/// disagree with the figures under it.
///
/// Three values, because there are three honest answers and the third is the
/// one that matters: a measurement can complete without being able to support
/// a green claim. A medium with no change signal cannot observe drift; an
/// empty enumerated scope makes coverage vacuous; a pass that adjudicated no
/// anchor observed nothing. Summarizing any of those as "clean" would be the
/// report asserting more than it measured, so they resolve to
/// [`RollupVerdict::Inconclusive`] with the blindness named.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RollupVerdict {
    /// The pass was substantive on every axis and recorded no findings.
    Clean,
    /// Findings were recorded over the current key.
    Drifted,
    /// The pass completed but cannot support a green claim — see
    /// [`Rollup::because`] and [`Rollup::blind_spots`].
    Inconclusive,
}

impl RollupVerdict {
    /// The stable wire string (`clean` / `drifted` / `inconclusive`).
    pub fn wire(&self) -> &'static str {
        match self {
            RollupVerdict::Clean => "clean",
            RollupVerdict::Drifted => "drifted",
            RollupVerdict::Inconclusive => "inconclusive",
        }
    }
}

/// The rollup block: the verdict, the tally behind it, why it is what it is,
/// and the concrete next actions.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Rollup {
    /// The verdict.
    pub verdict: RollupVerdict,
    /// Total findings over the current key, summed across every class.
    pub findings_total: usize,
    /// One sentence explaining the verdict. Always populated — a verdict
    /// without a reason is a number a reader has to re-derive.
    pub because: String,
    /// Axes this measurement could not speak to, each named concretely.
    /// Empty on a substantive pass. Non-empty forces `Inconclusive` unless
    /// findings were actually recorded (an observed finding is real whatever
    /// else the pass could not see).
    pub blind_spots: Vec<String>,
    /// Top concrete actions, most severe class first. Empty when there is
    /// nothing to act on.
    pub actions: Vec<String>,
}

/// Finding classes in the order a reader should act on them: a wrong
/// projection misleads, drift is stale, an unresolvable anchor is broken
/// bookkeeping, uncovered is unwritten work, and a queued item is not yet
/// adjudicated at all.
const CLASS_SEVERITY: [&str; 5] = [
    "wrong",
    "drifted",
    "unresolvable-anchor",
    "uncovered",
    "queued-for-adjudication",
];

/// The concrete action for one finding class.
fn class_action(class: &str, n: usize, binding: &str) -> String {
    match class {
        "wrong" => format!(
            "{n} entity/entities contradict their source — read them against the source and \
             correct the entity (`memstead projection brief {binding}` lists them)"
        ),
        "drifted" => format!(
            "{n} anchored artifact(s) moved since the entity was written — re-read the source \
             and update the entity, then re-verify to advance the baseline"
        ),
        "unresolvable-anchor" => format!(
            "{n} anchor(s) no longer resolve to anything — repoint them at the artifact's new \
             location or unset them (`memstead_update` `anchors_unset`)"
        ),
        "uncovered" => format!(
            "{n} in-scope source artifact(s) carry no anchor — cover them via \
             `memstead projection brief {binding} --sync`, or record a disposition for the \
             ones deliberately excluded"
        ),
        "queued-for-adjudication" => format!(
            "{n} finding(s) are queued and not yet adjudicated — run \
             `memstead projection verify {binding} --full` to work the backlog down"
        ),
        other => format!("{n} `{other}` finding(s) recorded"),
    }
}

impl FidelityReport {
    /// Derive the [`Rollup`] from this report's own figures.
    ///
    /// Pure and total — same report, same verdict, no engine access. The
    /// derivation is deliberately conservative in one direction only: it will
    /// downgrade a green claim it cannot support, and it will never upgrade a
    /// recorded finding away.
    pub fn rollup(&self) -> Rollup {
        let findings_total: usize = self.findings_by_class.values().sum();

        let mut blind_spots: Vec<String> = Vec::new();
        match &self.coverage.denominator {
            DenominatorBasis::NonEnumerable { reason } => blind_spots.push(format!(
                "the source scope is not enumerable ({reason}) — coverage is reported over \
                 anchors only, so an uncovered artifact cannot be detected"
            )),
            DenominatorBasis::Enumerated { count: 0 } => blind_spots.push(
                "the enumerated source scope is empty (0 artifacts) — every coverage figure \
                 below is vacuous, not clean"
                    .to_string(),
            ),
            DenominatorBasis::Enumerated { .. } => {}
        }
        if self.anchors.observed == 0 {
            blind_spots.push(
                "no anchor carried a resolution state this pass — nothing was adjudicated"
                    .to_string(),
            );
        }
        // A facet is change-blind if EITHER its medium cannot signal change
        // or the binding resolved that medium to no strategy. The two are
        // different: a `codebase` medium reports `change_signal: true` while
        // a binding declaring `change_detection: "none"` resolves it to
        // `ChangeStrategy::None`, which is exactly the freshness row's
        // `change_detectable`. Reading only the capability row let such a
        // binding render CLEAN while the report body two screens down said
        // "freshness unknowable" — the headline disagreeing with its own
        // evidence, which is the one thing this derivation exists to prevent.
        let change_blind: std::collections::BTreeSet<&str> = self
            .freshness
            .iter()
            .filter(|f| !f.change_detectable)
            .map(|f| f.facet.as_str())
            .collect();
        for cap in &self.capabilities {
            if !cap.change_signal {
                blind_spots.push(format!(
                    "facet `{}` ({}) provides no change signal — drift on it cannot be \
                     observed at all",
                    cap.facet, cap.medium_type
                ));
            } else if change_blind.contains(cap.facet.as_str()) {
                blind_spots.push(format!(
                    "facet `{}` ({}) declares change-detection `{}` but this pass could \
                     not read that signal — either the binding asked for none, or the \
                     checkout cannot deliver it (a `git` source with no `.git`: an \
                     archive, a container COPY, a vendored drop). Drift on it cannot \
                     be observed",
                    cap.facet, cap.medium_type, cap.signal
                ));
            }
            // Checked per facet, not only on the binding-level denominator:
            // in a MIXED binding one enumerable facet makes `S(D)` non-empty,
            // so the denominator reads `Enumerated` and the binding-level
            // blind spot above never fires — while the non-enumerable facet's
            // coverage stays unmeasurable. Every medium that is non-enumerable
            // today also lacks a change signal, so this adds no blind spot
            // under the current matrix; it is here so a future
            // non-enumerable-but-change-detectable medium cannot silently
            // render a mixed binding green.
            if !cap.enumerable {
                blind_spots.push(format!(
                    "facet `{}` ({}) is not enumerable — an uncovered artifact under it \
                     cannot be detected, only an anchored one",
                    cap.facet, cap.medium_type
                ));
            }
        }

        let mut actions: Vec<String> = Vec::new();
        for class in CLASS_SEVERITY {
            if let Some(&n) = self.findings_by_class.get(class)
                && n > 0
            {
                actions.push(class_action(class, n, &self.binding));
            }
        }
        // Any class the vocabulary grew past this list still surfaces, after
        // the ranked ones — an unknown class is never silently dropped.
        for (class, &n) in &self.findings_by_class {
            if n > 0 && !CLASS_SEVERITY.contains(&class.as_str()) {
                actions.push(class_action(class, n, &self.binding));
            }
        }

        // The adopt case (E1): a mem that predates its binding is expected to
        // be 0% anchored, so uncovered findings there are the backfill
        // worklist, not drift. A red verdict must never be produced SOLELY by
        // pre-binding history — but the pass is not clean either, so it lands
        // inconclusive with the onboarding reason.
        let only_uncovered = findings_total > 0
            && self
                .findings_by_class
                .iter()
                .all(|(class, &n)| n == 0 || class == "uncovered");

        let (verdict, because) = if self.adopt && only_uncovered {
            (
                RollupVerdict::Inconclusive,
                format!(
                    "this mem predates its binding — the {findings_total} uncovered artifact(s) \
                     are the backfill worklist, not drift"
                ),
            )
        } else if findings_total > 0 {
            let tally = self
                .findings_by_class
                .iter()
                .filter(|(_, n)| **n > 0)
                .map(|(class, n)| format!("{class}: {n}"))
                .collect::<Vec<_>>()
                .join(", ");
            (
                RollupVerdict::Drifted,
                format!("{findings_total} finding(s) recorded over the current key ({tally})"),
            )
        } else if !blind_spots.is_empty() {
            (
                RollupVerdict::Inconclusive,
                format!(
                    "no findings recorded, but the pass could not speak to {} axis/axes — \
                     this is not a clean bill of health",
                    blind_spots.len()
                ),
            )
        } else {
            (
                RollupVerdict::Clean,
                "the pass was substantive on every axis and recorded no findings".to_string(),
            )
        };

        Rollup {
            verdict,
            findings_total,
            because,
            blind_spots,
            actions,
        }
    }
}

// ---------------------------------------------------------------------------
// Rendered output
// ---------------------------------------------------------------------------

/// The rendered report: markdown plus the structured envelope bits (mode,
/// hints) mirroring [`crate::overview::OverviewOutput`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedFidelityReport {
    /// The rendered markdown.
    pub markdown: String,
    /// `"complete"` / `"reduced"` / `"overbudget"` — the same tri-state the
    /// overview envelope uses.
    pub mode: String,
    /// Drill-in hints for heavy sections omitted under the budget:
    /// `(key, estimated_tokens)`.
    pub hints: Vec<(String, usize)>,
    /// The budget actually consumed by hard-required + emitted heavy content.
    pub budget_used: usize,
}

// ---------------------------------------------------------------------------
// Pure renderer
// ---------------------------------------------------------------------------

/// Render `N/D (P%)`, or `N/D (n/a)` when the denominator is zero.
fn ratio(num: usize, den: usize) -> String {
    if den == 0 {
        format!("{num}/{den} (n/a)")
    } else {
        let pct = (num as f64) * 100.0 / (den as f64);
        format!("{num}/{den} ({pct:.1}%)")
    }
}

/// Render the hard-required (always-ships) aggregate markdown for a report.
/// This is the content B3's "aggregated counts always ship" rests on — it is
/// concatenated whatever the budget.
fn render_hard_required(report: &FidelityReport) -> String {
    let mut md = String::new();
    md.push_str(&format!("# Fidelity report — `{}`\n\n", report.binding));

    // --- Rollup verdict (opens the report) ---
    // A reader gets the answer before the provenance. Derived from the
    // figures below, never measured separately, so the headline cannot
    // disagree with its own body.
    let rollup = report.rollup();
    md.push_str(&format!(
        "**Verdict: {}** — {}.\n\n",
        rollup.verdict.wire().to_uppercase(),
        rollup.because
    ));
    if !rollup.actions.is_empty() {
        md.push_str("**Do next:**\n\n");
        for action in &rollup.actions {
            md.push_str(&format!("1. {action}\n"));
        }
        md.push('\n');
    }
    if !rollup.blind_spots.is_empty() {
        md.push_str("**This pass could not see:**\n\n");
        for spot in &rollup.blind_spots {
            md.push_str(&format!("- {spot}\n"));
        }
        md.push('\n');
    }

    md.push_str(&format!(
        "- **Destination mem:** `{}`\n- **Coverage semantics:** {}{}\n\n",
        report.destination_mem,
        match report.coverage_semantics {
            CoverageSemantics::Exhaustive => "exhaustive",
            CoverageSemantics::Curated => "curated",
        },
        if report.coverage_semantics_declared {
            ""
        } else {
            " (resolved from the sources' media — not declared)"
        }
    ));

    // --- Adopt / onboarding framing (E1) ---
    // When the mem predates its binding, the report LEADS with onboarding
    // framing: the expected-0%-anchored statement plus the concrete backfill
    // path. REFUSAL: this is never a failure/error framing and the report never
    // produces a red verdict solely from pre-binding history — the coverage
    // section below reframes uncovered artifacts as the backfill worklist.
    if report.adopt {
        md.push_str("## Adopting — first verify\n\n");
        md.push_str(
            "This mem predates its binding: it carries no anchors and has no prior sync \
             baseline, so **0% anchored is expected — this is onboarding, not a failure.** \
             Do not read the coverage numbers below as drift or a red verdict; the uncovered \
             artifacts are the backfill worklist, not defects.\n\n",
        );
        md.push_str(&format!(
            "**Backfill path:** run `memstead projection brief {} --sync` to work through the in-scope \
             source artifacts that carry no entity yet, covering the clearly-new concepts among \
             them through the normal mutation surface. Backfilling is incremental — a partial \
             pass is fine, and the next sync continues where you left off.\n\n",
            report.binding
        ));
    }

    // --- Denominator provenance (B5) ---
    md.push_str("## Denominator provenance\n\n");
    match &report.coverage.denominator {
        DenominatorBasis::Enumerated { count } => md.push_str(&format!(
            "Coverage is reported relative to the per-medium enumeration `S(D)` = **{count}** \
             source artifact(s) in scope (after `deny_paths`).\n\n"
        )),
        DenominatorBasis::NonEnumerable { reason } => md.push_str(&format!(
            "No `S(D)` denominator: {reason}. Coverage is reported over anchors only; the \
             per-medium enumeration is unavailable.\n\n"
        )),
    }

    // --- Capability matrix (B1) ---
    md.push_str("## Capability matrix\n\n");
    if report.capabilities.is_empty() {
        md.push_str("_(no primary sources resolved)_\n\n");
    } else {
        for c in &report.capabilities {
            md.push_str(&format!("### `{}` ({})\n\n", c.facet, c.medium_type));
            md.push_str(&format!(
                "- enumerable: {} | change_signal: {} | base_version_retrievable: {}\n",
                c.enumerable, c.change_signal, c.base_version_retrievable
            ));
            md.push_str(&format!(
                "- anchor_namespace: `{}` | resolved signal: `{}`\n\n",
                c.anchor_namespace, c.signal
            ));
        }
    }

    // --- Freshness (B1/B2) ---
    md.push_str("## Freshness\n\n");
    if report.freshness.is_empty() {
        md.push_str("_(no source facets)_\n\n");
    } else {
        for f in &report.freshness {
            md.push_str(&format!("### `{}`\n\n", f.facet));
            md.push_str(&format!("- signal: `{}`\n", f.signal));
            if !f.change_detectable {
                // B2 REFUSAL: a non-change-detectable medium NEVER prints a
                // green freshness verdict — only "unknowable". This branch is
                // the only place `signal: none` freshness is rendered.
                md.push_str(
                    "- **freshness unknowable** — this medium is not change-detectable \
                     (no change signal); `#synced` / `#verified` cannot be adjudicated as fresh\n",
                );
            } else {
                match &f.synced {
                    Some(t) => md.push_str(&format!("- `#synced`: `{t}`\n")),
                    None => md.push_str("- `#synced`: never synced\n"),
                }
                match &f.verified {
                    Some(t) => md.push_str(&format!("- `#verified`: `{t}`\n")),
                    None => md.push_str("- `#verified`: never verified\n"),
                }
            }
            md.push('\n');
        }
        // Binding-level move verdict — only when something is change-detectable.
        match report.source_moved_past_synced {
            Some(true) => md.push_str(
                "**Source moved past its `#synced` baseline** — the graph is stale for the \
                 moved facet(s); a sync pass is due.\n\n",
            ),
            Some(false) => {
                md.push_str("Every change-detectable source is at its `#synced` baseline.\n\n")
            }
            None => {}
        }
    }

    // --- Coverage (B1, B4) ---
    md.push_str("## Coverage (grain-classed)\n\n");
    let den = match &report.coverage.denominator {
        DenominatorBasis::Enumerated { count } => *count,
        DenominatorBasis::NonEnumerable { .. } => 0,
    };
    md.push_str(&format!(
        "- direct-covered (file / span anchors): {}\n",
        ratio(report.coverage.direct_covered, den)
    ));
    // Tree fan-out is a DISTINCT axis — reported separately, never blended into
    // the direct-covered percentage (B1).
    let tree_files: usize = report.coverage.tree_anchors.iter().map(|t| t.fanout).sum();
    md.push_str(&format!(
        "- tree-anchor fan-out (separate axis): {} tree anchor(s) fanning out over {} file(s); \
         {} file(s) covered ONLY via a tree anchor\n",
        report.coverage.tree_anchors.len(),
        tree_files,
        report.coverage.tree_only_covered
    ));
    md.push_str(&format!(
        "- uncovered (no anchor): {}\n\n",
        report.coverage.uncovered.len()
    ));

    // Coverage-semantics framing (B4). REFUSAL (E1): under adopt, the exhaustive
    // branch must NOT frame the uncovered artifacts as defect findings — they are
    // the expected backfill worklist of a mem that predates its binding, never a
    // red verdict caused solely by pre-binding history.
    match report.coverage_semantics {
        CoverageSemantics::Exhaustive if report.adopt => {
            let backlog = report
                .coverage
                .uncovered
                .len()
                .saturating_sub(report.disposed_excluded);
            md.push_str(&format!(
                "**Exhaustive coverage (onboarding):** {backlog} in-scope artifact(s) carry no \
                 entity yet ({} disposed excluded) — the expected first-sync backfill worklist \
                 for a mem that predates its binding, not defects.\n\n",
                report.disposed_excluded
            ));
        }
        CoverageSemantics::Exhaustive => {
            let findings = report
                .coverage
                .uncovered
                .len()
                .saturating_sub(report.disposed_excluded);
            md.push_str(&format!(
                "**Exhaustive coverage:** {findings} unaccounted artifact(s) — not anchored, not \
                 declared-excluded, no persisted disposition ({} disposed excluded) — are \
                 **findings**.\n\n",
                report.disposed_excluded
            ));
        }
        CoverageSemantics::Curated => {
            md.push_str(&format!(
                "**Curated coverage:** {} unaccounted artifact(s) are **information**, not \
                 defects — a curated binding covers a deliberate slice.\n\n",
                report.coverage.uncovered.len()
            ));
        }
    }

    // Authored exclusion ledger (B4) — surface the reasoning behind each
    // deliberately-excluded artifact so an editorial decision stays visible and
    // auditable, not just subtracted from a denominator.
    if !report.disposed_excluded_rationales.is_empty() {
        md.push_str("**Excluded on purpose (persisted dispositions):**\n");
        for (artifact, rationale) in &report.disposed_excluded_rationales {
            if rationale.is_empty() {
                md.push_str(&format!("- `{artifact}`\n"));
            } else {
                md.push_str(&format!("- `{artifact}` — {rationale}\n"));
            }
        }
        md.push('\n');
    }

    // --- Anchors (B1) ---
    md.push_str("## Anchors\n\n");
    md.push_str(&format!(
        "- by class: {}\n",
        render_counts(&report.anchors.by_class)
    ));
    md.push_str(&format!(
        "- by grain: {}\n",
        render_counts(&report.anchors.by_grain)
    ));
    md.push_str(&format!(
        "- `authored` bucket (excluded from coverage/accuracy denominators): {}\n",
        report.anchors.authored
    ));
    md.push_str(&format!(
        "- resolution (non-`authored`, observed): resolves {}, drifted {}, recheck {}, orphaned {}\n",
        report.anchors.resolves,
        report.anchors.drifted,
        report.anchors.recheck,
        report.anchors.orphaned
    ));
    md.push_str(&format!(
        "- **anchor-resolution %:** {}\n",
        ratio(report.anchors.resolves, report.anchors.observed)
    ));
    md.push_str(&format!(
        "- unobserved this pass (state unavailable, never scored as resolved): {}\n\n",
        report.anchors.unobserved
    ));

    // --- Findings + backlog (B1) ---
    md.push_str("## Findings\n\n");
    md.push_str(&format!(
        "- by class: {}\n",
        render_counts(&report.findings_by_class)
    ));
    md.push_str(&format!(
        "- **tier-3 adjudication backlog:** {}\n",
        report.backlog
    ));
    md.push_str(&format!(
        "- superseded (prior `(hash(D), source_head)` key, segregated): {}\n\n",
        report.superseded.len()
    ));

    // --- Degradations (B1) ---
    md.push_str("## Degradations\n\n");
    if report.degradations.is_empty() {
        md.push_str("_(none)_\n\n");
    } else {
        for d in &report.degradations {
            md.push_str(&format!("- {d}\n"));
        }
        md.push('\n');
    }

    md
}

/// Render a `BTreeMap<String, usize>` as `k=v, k=v` (or `(none)`).
fn render_counts(counts: &BTreeMap<String, usize>) -> String {
    if counts.is_empty() {
        return "(none)".to_string();
    }
    counts
        .iter()
        .map(|(k, v)| format!("{k}={v}"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// The three heavy sections, in greedy-fill priority order — each a
/// `(key, markdown)` pair whose markdown is empty when the section has nothing
/// to show (an empty section is emitted free, never hinted).
fn heavy_sections(report: &FidelityReport) -> Vec<(&'static str, String)> {
    let mut out: Vec<(&'static str, String)> = Vec::new();

    // uncovered_artifacts
    let mut s = String::new();
    if !report.coverage.uncovered.is_empty() {
        s.push_str("## Uncovered artifacts\n\n");
        for a in &report.coverage.uncovered {
            s.push_str(&format!("- `{a}`\n"));
        }
        s.push('\n');
    }
    out.push(("uncovered_artifacts", s));

    // tree_fanout
    let mut s = String::new();
    if !report.coverage.tree_anchors.is_empty() {
        s.push_str("## Tree-anchor fan-out (detail)\n\n");
        for t in &report.coverage.tree_anchors {
            s.push_str(&format!(
                "- `{}` → `{}` fans out over {} file(s)\n",
                t.entity, t.artifact, t.fanout
            ));
        }
        s.push('\n');
    }
    out.push(("tree_fanout", s));

    // superseded_findings
    let mut s = String::new();
    if !report.superseded.is_empty() {
        s.push_str("## Superseded findings (detail)\n\n");
        for f in &report.superseded {
            s.push_str(&format!("- {f}\n"));
        }
        s.push('\n');
    }
    out.push(("superseded_findings", s));

    out
}

/// Render the tier-1 fidelity report into markdown, token-budgeted in the house
/// envelope shape (B3). Aggregated counts (the hard-required block) always ship;
/// heavy per-artifact lists greedy-fill by priority and drop to `## Hints` when
/// they do not fit — `include`-listed keys force their section in past the
/// budget, exactly as the overview envelope does.
///
/// - `budget` — the target token budget for **heavy** content (the aggregates
///   ship in addition, so total output exceeds this when the report is large).
/// - `include` — keys forced in regardless of budget; an unknown key adds a
///   warning line, mirroring the overview composer.
pub fn render_fidelity_report(
    report: &FidelityReport,
    budget: usize,
    include: &[String],
) -> RenderedFidelityReport {
    let hard = render_hard_required(report);
    let hard_cost = estimate_tokens(&hard);
    let overbudget = hard_cost > budget;

    let include_set: std::collections::BTreeSet<&str> = include
        .iter()
        .map(String::as_str)
        .filter(|k| ALLOWED_REPORT_INCLUDE_KEYS.contains(k))
        .collect();
    let unknown_includes: Vec<&String> = include
        .iter()
        .filter(|k| !ALLOWED_REPORT_INCLUDE_KEYS.contains(&k.as_str()))
        .collect();

    let sections = heavy_sections(report);
    let mut emitted: Vec<String> = Vec::new();
    let mut hints: Vec<(String, usize)> = Vec::new();
    let mut used = hard_cost;
    let mut remaining = budget.saturating_sub(hard_cost);

    for (key, section_md) in &sections {
        if section_md.is_empty() {
            continue; // nothing to show — never hinted, never charged
        }
        let cost = estimate_tokens(section_md);
        let forced = include_set.contains(key);
        if forced {
            emitted.push(section_md.clone());
            used += cost;
            remaining = remaining.saturating_sub(cost);
        } else if !overbudget && remaining >= cost {
            emitted.push(section_md.clone());
            used += cost;
            remaining -= cost;
        } else {
            hints.push(((*key).to_string(), cost));
        }
    }

    let mode = if overbudget {
        "overbudget"
    } else if hints.is_empty() {
        "complete"
    } else {
        "reduced"
    };

    let mut md = String::new();
    md.push_str("---\n");
    md.push_str(&format!("_report_mode: {mode}\n"));
    md.push_str(&format!("_budget_requested: {budget}\n"));
    md.push_str(&format!("_budget_used: {used}\n"));
    md.push_str("---\n\n");
    md.push_str(&hard);
    for section in &emitted {
        md.push_str(section);
    }

    if !hints.is_empty() {
        md.push_str("## Hints\n\n");
        md.push_str(
            "_(heavy sections omitted under the token budget — re-query with the key)_\n\n",
        );
        for (key, tokens) in &hints {
            md.push_str(&format!("- `{key}` — estimated_tokens: {tokens}\n"));
        }
        md.push('\n');
    }

    if !unknown_includes.is_empty() {
        md.push_str("## Warnings\n\n");
        for k in &unknown_includes {
            md.push_str(&format!(
                "- unknown include key `{k}` — allowed: {}\n",
                ALLOWED_REPORT_INCLUDE_KEYS.join(", ")
            ));
        }
        md.push('\n');
    }

    RenderedFidelityReport {
        markdown: md,
        mode: mode.to_string(),
        hints,
        budget_used: used,
    }
}

// ---------------------------------------------------------------------------
// Assembly — reads the engine, findings store, advance store, capability matrix
// ---------------------------------------------------------------------------

/// Assemble the tier-1 [`FidelityReport`] for a binding (B1–B5). Read-only on
/// the destination mem — it borrows `&Engine` (shared), reads the durable
/// findings store under `key`, the advance store, and the live anchor /
/// enumeration / freshness state. It performs no mutation and no LLM call.
///
/// `key` is the current `(hash(D), source_head)` the verify pass recorded
/// under (from [`super::findings::VerifyOutcome::key`]); the report's findings
/// tally is the store's `current(key)` slice — all open findings under the
/// key's `hash(D)`, regardless of the head each was observed at — and the
/// superseded count is everything under prior binding hashes.
pub fn compute_fidelity_report(
    engine: &Engine,
    workspace_root: &Path,
    binding: &Binding,
    resolved: &ResolvedIngest,
    key: &FindingKey,
) -> FidelityReport {
    let binding_id = resolved.name.clone();
    let dest = resolved.destination_mem.clone();

    // --- Capabilities + freshness, per primary facet ---
    let sync_state = engine
        .mem_config_for(&dest)
        .map(|c| c.sync_state.clone())
        .unwrap_or_default();
    let mut capabilities: Vec<FacetCapability> = Vec::new();
    let mut freshness: Vec<FacetFreshness> = Vec::new();
    let mut any_change_detectable = false;
    for source in &resolved.sources {
        let ResolvedSource::Primary(p) = source else {
            continue;
        };
        let caps = medium_capabilities(p.medium_type);
        let medium_type = serde_json::to_value(p.medium_type)
            .ok()
            .and_then(|v| v.as_str().map(str::to_string))
            .unwrap_or_default();
        let strategy = resolve_change_strategy(p, workspace_root);
        let signal = signal_wire(strategy).to_string();
        // Detectable means THIS PASS could read the signal, not that the
        // binding declared one. A `git` strategy over a tree with no `.git`
        // — a `git archive`, a Docker `COPY`, a vendored drop — declares a
        // signal the checkout cannot deliver: the head resolves empty and no
        // baseline is written. Reporting `change_detectable: true` there let
        // the rollup call such a pass "substantive on every axis" and render
        // CLEAN, which is the worst failure a gate can have. The declaration
        // is not second-guessed (that is the resolver's job); what the run
        // could observe is reported honestly.
        let signal_readable = match strategy {
            ChangeStrategy::Git => {
                super::resolve::find_git_root(&super::resolve::source_base_path(p, workspace_root))
                    .is_some()
            }
            _ => true,
        };
        let change_detectable =
            caps.change_signal && strategy != ChangeStrategy::None && signal_readable;
        any_change_detectable |= change_detectable;

        capabilities.push(FacetCapability::from_caps(
            p.name.clone(),
            medium_type,
            caps,
            strategy,
        ));

        let synced = sync_state
            .get(&format!("{binding_id}/{}#synced", p.name))
            .cloned();
        let verified = sync_state
            .get(&format!("{binding_id}/{}#verified", p.name))
            .cloned();
        freshness.push(FacetFreshness {
            facet: p.name.clone(),
            signal,
            synced,
            verified,
            change_detectable,
        });
    }

    let source_moved_past_synced = if any_change_detectable {
        Some(source_moved(engine, resolved, workspace_root))
    } else {
        None
    };

    // --- S(D) enumeration + grain-classed coverage ---
    let mut s_d: Vec<String> = Vec::new();
    let mut enumerable_facets = 0usize;
    // Facets whose medium the matrix marks enumerable and whose OWN walk came
    // back empty. Tracked per facet, not over the union: in a mixed binding one
    // facet that walks makes `S(D)` non-empty, so a binding-level flag reads
    // "something was enumerated" while the empty facet's coverage stays
    // unmeasured — and the degradation below, which names a facet, could not
    // honestly speak for it. Same reasoning as the per-facet blind spot above.
    let mut empty_enumerable_facets: BTreeSet<String> = BTreeSet::new();
    for source in &resolved.sources {
        if let ResolvedSource::Primary(p) = source {
            let caps = medium_capabilities(p.medium_type);
            if caps.enumerable {
                enumerable_facets += 1;
            }
            let walked =
                enumerate_source_artifacts(engine, p, &resolved.deny_paths, workspace_root);
            if caps.enumerable && walked.is_empty() {
                empty_enumerable_facets.insert(p.name.clone());
            }
            s_d.extend(walked);
        }
    }
    s_d.sort();
    s_d.dedup();

    let denominator = if !s_d.is_empty() {
        DenominatorBasis::Enumerated { count: s_d.len() }
    } else if enumerable_facets == 0 {
        DenominatorBasis::NonEnumerable {
            reason: "the medium type(s) are not enumerable this cycle".to_string(),
        }
    } else {
        // Enumerable per the matrix but the walk yielded nothing — an empty
        // or over-narrow scope. The degradation block below says so out loud;
        // `--full` refuses this case outright rather than measuring it.
        DenominatorBasis::NonEnumerable {
            reason: "no source artifacts enumerated in scope".to_string(),
        }
    };

    let mut direct_covered = 0usize;
    let mut tree_only_covered = 0usize;
    let mut uncovered: Vec<String> = Vec::new();
    let mut tree_fanout: BTreeMap<(String, String), usize> = BTreeMap::new();
    for file in &s_d {
        let refs = engine.anchors_referencing_artifact(file);
        let mine: Vec<&(crate::EntityId, crate::anchor::Anchor)> = refs
            .iter()
            .filter(|(eid, _)| eid.mem() == dest.as_str())
            .collect();
        if mine.is_empty() {
            uncovered.push(file.clone());
            continue;
        }
        let has_non_tree = mine.iter().any(|(_, a)| a.grain != AnchorGrain::Tree);
        if has_non_tree {
            direct_covered += 1;
        } else {
            tree_only_covered += 1;
        }
        // Attribute tree fan-out (separate axis) for every covering tree anchor.
        for (eid, a) in &mine {
            if a.grain == AnchorGrain::Tree {
                *tree_fanout
                    .entry((eid.as_ref().to_string(), a.artifact.clone()))
                    .or_insert(0) += 1;
            }
        }
    }
    let tree_anchors: Vec<TreeFanout> = tree_fanout
        .into_iter()
        .map(|((entity, artifact), fanout)| TreeFanout {
            entity,
            artifact,
            fanout,
        })
        .collect();

    let coverage = GrainCoverage {
        denominator,
        direct_covered,
        tree_only_covered,
        uncovered: uncovered.clone(),
        tree_anchors,
    };

    // --- Anchor composition + resolution over the mem's anchors ---
    let mut anchors = AnchorComposition::default();
    for (_eid, resolved_anchor) in engine.mem_anchors_resolved(&dest) {
        let a = &resolved_anchor.anchor;
        *anchors
            .by_class
            .entry(a.class.as_wire().to_string())
            .or_insert(0) += 1;
        *anchors
            .by_grain
            .entry(a.grain.as_wire().to_string())
            .or_insert(0) += 1;
        if a.class == AnchorProvenanceClass::Authored {
            anchors.authored += 1;
            continue; // own bucket — excluded from the resolution denominator
        }
        match resolved_anchor.state {
            Some(AnchorState::Resolves) => {
                anchors.resolves += 1;
                anchors.observed += 1;
            }
            Some(AnchorState::Drifted) => {
                anchors.drifted += 1;
                anchors.observed += 1;
            }
            Some(AnchorState::Recheck) => {
                anchors.recheck += 1;
                anchors.observed += 1;
            }
            Some(AnchorState::Orphaned) => {
                anchors.orphaned += 1;
                anchors.observed += 1;
            }
            None => anchors.unobserved += 1,
        }
    }

    // --- Findings tally + backlog + superseded, from the durable store ---
    let mut findings_by_class: BTreeMap<String, usize> = BTreeMap::new();
    let mut backlog = 0usize;
    let mut superseded: Vec<String> = Vec::new();
    if let Some((mem, name)) = binding_id.split_once('/')
        && let Ok(Some(store)) = read_findings_store(workspace_root, mem, name)
    {
        for f in store.current(key) {
            *findings_by_class
                .entry(f.class.as_wire().to_string())
                .or_insert(0) += 1;
            if f.class == FindingClass::QueuedForAdjudication {
                backlog += 1;
            }
        }
        for f in store.superseded(key) {
            superseded.push(format!(
                "[{}] {} ({})",
                f.class.as_wire(),
                finding_target_label(&f.target),
                f.facet
            ));
        }
    }

    // --- Durable authored-exclusion ledger (B4) ---
    // The advance store's `exclusions` map survives advance completion (unlike
    // its transient `dispositions`), so an artifact mined-and-deliberately-
    // excluded no longer re-surfaces as `uncovered` on every verify — and keeps
    // its reasoning. Consult it for every uncovered artifact.
    let mut disposed_excluded_rationales: Vec<(String, String)> = Vec::new();
    if let Some((mem, name)) = binding_id.split_once('/')
        && let Ok(Some(state)) = read_advance_store(workspace_root, mem, name)
    {
        let uncovered_set: std::collections::BTreeSet<&str> =
            uncovered.iter().map(String::as_str).collect();
        for (artifact, rationale) in &state.exclusions {
            if uncovered_set.contains(artifact.as_str()) {
                disposed_excluded_rationales.push((artifact.clone(), rationale.clone()));
            }
        }
    }
    let disposed_excluded = disposed_excluded_rationales.len();

    // --- Degradation flags (B1) ---
    let mut degradations: Vec<String> = Vec::new();
    for c in &capabilities {
        if !c.change_signal || c.signal == "none" {
            degradations.push(format!(
                "change-signal-none:`{}` — freshness is unknowable for this facet",
                c.facet
            ));
        }
        if !c.enumerable {
            degradations.push(format!(
                "enumeration-unavailable:`{}` — `S(D)` coverage denominator not computable",
                c.facet
            ));
        } else if empty_enumerable_facets.contains(&c.facet) {
            // The matrix CLAIMS this medium enumerates and the walk produced
            // nothing. That is a capability unavailable in this pass, and the
            // block above only ever spoke for media the matrix already marks
            // non-enumerable — so the honest case rendered `Degradations:
            // (none)` beside a report with no denominator. `--full` refuses
            // this outright; a plain pass measures what it can and must say
            // what it could not.
            degradations.push(format!(
                "enumeration-empty:`{}` — the medium claims enumerability but the walk yielded \
                 no artifacts; coverage is reported over anchors only",
                c.facet
            ));
        }
        if !c.base_version_retrievable {
            degradations.push(format!(
                "base-version-unretrievable:`{}` — prune degrades to conflict-flagging",
                c.facet
            ));
        }
    }
    if anchors.recheck > 0 {
        degradations.push(format!(
            "hash-adjudication-deferred — {} anchor(s) recheck (unstable medium / hash \
             unavailable), not asserted drift",
            anchors.recheck
        ));
    }
    if anchors.unobserved > 0 {
        degradations.push(format!(
            "anchors-unobserved — {} anchor(s) could not be observed this pass",
            anchors.unobserved
        ));
    }

    // Adopt / onboarding signal (E1) — the single canonical predicate shared with
    // the sync brief and the status rollup: a mem with no anchors and no recorded
    // `#synced` baseline predates its binding, so 0% anchored is expected.
    let adopt = super::render::mem_predates_binding(engine, resolved);
    let effective_coverage = crate::binding::effective_coverage_semantics(binding);

    FidelityReport {
        binding: binding_id,
        destination_mem: dest,
        adopt,
        coverage_semantics: effective_coverage.value,
        coverage_semantics_declared: effective_coverage.declared,
        capabilities,
        freshness,
        source_moved_past_synced,
        coverage,
        anchors,
        findings_by_class,
        backlog,
        superseded,
        disposed_excluded,
        disposed_excluded_rationales,
        degradations,
    }
}

/// Whether a resolved change-detection strategy can retrieve a prior base
/// version for a three-way merge (B1). Only git-backed strategies (`git`,
/// `graph`) hold prior content; `mtime` reports *that* an artifact changed but
/// not its previous bytes, and `none` detects nothing — both leave prune with
/// no base leg, so it degrades to conflict-flagging regardless of the medium
/// type's static base-retrievability ceiling. This is why filesystem+mtime —
/// a common non-git dogfood binding — must surface the conflict-flag
/// degradation even though `MediumType::Filesystem` advertises retrievability.
fn strategy_retrieves_base(strategy: ChangeStrategy) -> bool {
    matches!(strategy, ChangeStrategy::Git | ChangeStrategy::Graph)
}

/// The `signal` wire string for a [`ChangeStrategy`] — `none` for detection-less
/// (never a fabricated token, B2).
fn signal_wire(strategy: ChangeStrategy) -> &'static str {
    match strategy {
        ChangeStrategy::None => "none",
        ChangeStrategy::Git => "git",
        ChangeStrategy::Mtime => "mtime",
        ChangeStrategy::Graph => "graph",
    }
}

/// A compact label for a finding target (superseded detail).
fn finding_target_label(target: &super::findings::FindingTarget) -> String {
    match target {
        super::findings::FindingTarget::Anchor { entity, artifact } => {
            format!("{entity}{artifact}")
        }
        super::findings::FindingTarget::Artifact { artifact } => artifact.clone(),
    }
}

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

    // ---- pure-renderer fixtures ------------------------------------------

    fn base_report() -> FidelityReport {
        FidelityReport {
            binding: "engine/graph".to_string(),
            destination_mem: "engine".to_string(),
            adopt: false,
            coverage_semantics: CoverageSemantics::Exhaustive,
            coverage_semantics_declared: true,
            capabilities: vec![FacetCapability {
                facet: "src".to_string(),
                medium_type: "codebase".to_string(),
                enumerable: true,
                change_signal: true,
                base_version_retrievable: true,
                anchor_namespace: "path".to_string(),
                signal: "git".to_string(),
            }],
            freshness: vec![FacetFreshness {
                facet: "src".to_string(),
                signal: "git".to_string(),
                synced: Some("deadbeef".to_string()),
                verified: None,
                change_detectable: true,
            }],
            source_moved_past_synced: Some(false),
            coverage: GrainCoverage {
                denominator: DenominatorBasis::Enumerated { count: 10 },
                direct_covered: 6,
                tree_only_covered: 3,
                uncovered: vec!["src/a.rs".to_string()],
                tree_anchors: vec![TreeFanout {
                    entity: "engine--big".to_string(),
                    artifact: "src/".to_string(),
                    fanout: 3,
                }],
            },
            anchors: AnchorComposition {
                by_class: BTreeMap::from([
                    ("anchored".to_string(), 5),
                    ("authored".to_string(), 2),
                ]),
                by_grain: BTreeMap::from([("file".to_string(), 4), ("tree".to_string(), 1)]),
                authored: 2,
                observed: 5,
                resolves: 4,
                drifted: 0,
                recheck: 1,
                orphaned: 0,
                unobserved: 0,
            },
            findings_by_class: BTreeMap::from([
                ("uncovered".to_string(), 1),
                ("queued-for-adjudication".to_string(), 1),
            ]),
            backlog: 1,
            superseded: Vec::new(),
            disposed_excluded: 0,
            disposed_excluded_rationales: Vec::new(),
            degradations: vec!["hash-adjudication-deferred — 1 anchor(s) recheck".to_string()],
        }
    }

    /// B1 — the report renders every required element deterministically, with
    /// tree fan-out on its own axis, `authored` as its own excluded bucket, and
    /// the backlog depth. Two renders of the same input are byte-identical (no
    /// LLM, no clock).
    #[test]
    fn b1_renders_all_elements_deterministically() {
        let r = base_report();
        let a = render_fidelity_report(&r, 8_000, &[]);
        let b = render_fidelity_report(&r, 8_000, &[]);
        assert_eq!(a.markdown, b.markdown, "deterministic — identical bytes");

        let md = &a.markdown;
        // Grain-classed coverage with tree fan-out SEPARATE, never blended.
        assert!(md.contains("direct-covered (file / span anchors): 6/10"));
        assert!(md.contains(
            "tree-anchor fan-out (separate axis): 1 tree anchor(s) fanning out over 3 file(s)"
        ));
        // The direct % is NOT (6+3)/10 — the tree fan-out is not folded in.
        assert!(
            !md.contains("9/10"),
            "tree fan-out must not blend into direct coverage"
        );
        // anchor-resolution % over non-authored observed.
        assert!(md.contains("anchor-resolution %:** 4/5"));
        // authored is its own excluded bucket.
        assert!(md.contains("`authored` bucket (excluded from coverage/accuracy denominators): 2"));
        // tier-3 backlog depth from the store tally.
        assert!(md.contains("tier-3 adjudication backlog:** 1"));
        // capability-matrix block + degradation flags.
        assert!(md.contains("## Capability matrix"));
        assert!(md.contains("## Degradations"));
        assert!(md.contains("hash-adjudication-deferred"));
        // B5 denominator provenance.
        assert!(md.contains("per-medium enumeration `S(D)` = **10**"));
    }

    /// B2 — a detection-less medium renders `signal: none` → "freshness
    /// unknowable", and NO green freshness verdict appears for it.
    #[test]
    fn b2_detectionless_medium_freshness_unknowable_never_green() {
        let mut r = base_report();
        r.capabilities = vec![FacetCapability {
            facet: "manual".to_string(),
            medium_type: "web".to_string(),
            enumerable: false,
            change_signal: false,
            base_version_retrievable: false,
            anchor_namespace: "url".to_string(),
            signal: "none".to_string(),
        }];
        r.freshness = vec![FacetFreshness {
            facet: "manual".to_string(),
            signal: "none".to_string(),
            // Even if a stale token were somehow present, it must never be
            // rendered as a fresh/green verdict.
            synced: Some("should-never-render-green".to_string()),
            verified: Some("nor-this".to_string()),
            change_detectable: false,
        }];
        r.source_moved_past_synced = None;
        let out = render_fidelity_report(&r, 8_000, &[]);
        let md = &out.markdown;
        assert!(md.contains("signal: `none`"));
        assert!(md.contains("freshness unknowable"));
        // REFUSAL: no fabricated green token, no fresh verdict, no baseline
        // token laundered as fresh.
        assert!(!md.contains("should-never-render-green"));
        assert!(
            !md.contains("`#synced`: `"),
            "no synced token rendered for a non-detectable medium"
        );
        assert!(
            !md.contains("at its `#synced` baseline"),
            "no green 'at baseline' verdict"
        );
    }

    /// B1 — base retrievability is *effective*, keyed on the resolved
    /// change-detection strategy, not the medium type's static ceiling. A
    /// filesystem binding that resolves to `mtime` (no prior content, only a
    /// mod-time signal) has no retrievable base leg, so its facet capability
    /// reports `base_version_retrievable: false` — which is exactly what the
    /// degradation loop keys on to surface the conflict-flag posture. The same
    /// filesystem medium backed by `git` keeps the full never-clobber base leg.
    #[test]
    fn b1_base_retrievability_follows_resolved_strategy_not_medium_ceiling() {
        use crate::pipeline::MediumType;

        // The medium type's static ceiling advertises retrievability…
        assert!(medium_capabilities(MediumType::Filesystem).base_version_retrievable);

        // …but the effective capability derives from the resolved strategy.
        let fs_mtime = FacetCapability::from_caps(
            "prose".to_string(),
            "filesystem".to_string(),
            medium_capabilities(MediumType::Filesystem),
            ChangeStrategy::Mtime,
        );
        assert!(
            !fs_mtime.base_version_retrievable,
            "filesystem+mtime has no retrievable base leg — degrades to conflict-flag"
        );
        assert_eq!(fs_mtime.signal, "mtime");

        let fs_git = FacetCapability::from_caps(
            "prose".to_string(),
            "filesystem".to_string(),
            medium_capabilities(MediumType::Filesystem),
            ChangeStrategy::Git,
        );
        assert!(
            fs_git.base_version_retrievable,
            "filesystem backed by git keeps the never-clobber base leg"
        );

        // A detection-less strategy also has no base leg.
        assert!(!strategy_retrieves_base(ChangeStrategy::None));
        assert!(!strategy_retrieves_base(ChangeStrategy::Mtime));
        assert!(strategy_retrieves_base(ChangeStrategy::Git));
        assert!(strategy_retrieves_base(ChangeStrategy::Graph));

        // The linkage the fix restores: a false effective flag drives the
        // conflict-flag degradation the report renders (mirrors the derivation
        // in compute_fidelity_report's degradation loop).
        let mut r = base_report();
        r.capabilities = vec![fs_mtime.clone()];
        r.degradations = if !fs_mtime.base_version_retrievable {
            vec![format!(
                "base-version-unretrievable:`{}` — prune degrades to conflict-flagging",
                fs_mtime.facet
            )]
        } else {
            Vec::new()
        };
        let md = render_fidelity_report(&r, 8_000, &[]).markdown;
        assert!(
            md.contains("base-version-unretrievable:`prose` — prune degrades to conflict-flagging"),
            "filesystem+mtime surfaces the conflict-flag degradation in the report"
        );
    }

    /// B3 — aggregates always ship at budget 0 (mode overbudget, every heavy
    /// list dropped to hints).
    #[test]
    fn b3_aggregates_always_ship_at_zero_budget() {
        let r = base_report();
        let out = render_fidelity_report(&r, 0, &[]);
        assert_eq!(out.mode, "overbudget");
        let md = &out.markdown;
        // Aggregated counts still ship.
        assert!(md.contains("direct-covered (file / span anchors): 6/10"));
        assert!(md.contains("tier-3 adjudication backlog:** 1"));
        assert!(md.contains("## Capability matrix"));
        // The per-artifact list did NOT render inline; it is a hint.
        assert!(!md.contains("## Uncovered artifacts"));
        assert!(md.contains("## Hints"));
        assert!(out.hints.iter().any(|(k, _)| k == "uncovered_artifacts"));
    }

    /// B3 — a large facet's per-artifact list never renders unbounded under a
    /// small budget: it is dropped to a hint with an estimated_tokens figure.
    /// The complement: `include` forces it in past the budget.
    #[test]
    fn b3_large_facet_list_truncates_then_include_forces() {
        let mut r = base_report();
        // A large uncovered facet — 500 artifacts.
        r.coverage.uncovered = (0..500).map(|i| format!("src/file_{i}.rs")).collect();
        // A budget large enough for the aggregates but not the huge list.
        let hard_cost = estimate_tokens(&render_hard_required(&r));
        let out = render_fidelity_report(&r, hard_cost + 5, &[]);
        assert_eq!(out.mode, "reduced");
        assert!(
            !out.markdown.contains("src/file_499.rs"),
            "big list not rendered unbounded"
        );
        assert!(out.markdown.contains("## Hints"));
        let (_, est) = out
            .hints
            .iter()
            .find(|(k, _)| k == "uncovered_artifacts")
            .expect("uncovered list hinted");
        assert!(*est > 5, "the hint carries a real estimated_tokens figure");

        // Complement: include forces the section in past the budget.
        let forced =
            render_fidelity_report(&r, hard_cost + 5, &["uncovered_artifacts".to_string()]);
        assert!(
            forced.markdown.contains("src/file_499.rs"),
            "include forces the full list"
        );
    }

    /// B4 — exhaustive vs curated framing differs: exhaustive calls unaccounted
    /// artifacts findings; curated calls them information.
    #[test]
    fn b4_curated_vs_exhaustive_framing() {
        let mut exhaustive = base_report();
        exhaustive.coverage_semantics = CoverageSemantics::Exhaustive;
        let ex_md = render_fidelity_report(&exhaustive, 8_000, &[]).markdown;
        assert!(ex_md.contains("Exhaustive coverage:"));
        assert!(ex_md.contains("are **findings**"));

        let mut curated = base_report();
        curated.coverage_semantics = CoverageSemantics::Curated;
        let cur_md = render_fidelity_report(&curated, 8_000, &[]).markdown;
        assert!(cur_md.contains("Curated coverage:"));
        assert!(cur_md.contains("**information**"));
        assert!(
            !cur_md.contains("are **findings**"),
            "curated never frames unaccounted as findings"
        );
    }

    /// B4 — a persisted disposition removes an uncovered artifact from the
    /// exhaustive findings count.
    #[test]
    fn b4_disposition_excludes_from_exhaustive_findings() {
        let mut r = base_report();
        r.coverage_semantics = CoverageSemantics::Exhaustive;
        r.coverage.uncovered = vec!["src/a.rs".to_string(), "src/b.rs".to_string()];
        r.disposed_excluded = 1;
        let md = render_fidelity_report(&r, 8_000, &[]).markdown;
        // 2 uncovered − 1 disposed = 1 finding.
        assert!(md.contains("1 unaccounted artifact(s)"));
        assert!(md.contains("(1 disposed excluded)"));
    }

    /// B4 — the authored-exclusion ledger renders each excluded artifact with
    /// its reasoning, so the editorial decision stays visible (not just counted).
    #[test]
    fn b4_authored_exclusion_rationale_is_rendered() {
        let mut r = base_report();
        r.coverage_semantics = CoverageSemantics::Exhaustive;
        r.coverage.uncovered = vec!["src/gen.rs".to_string()];
        r.disposed_excluded = 1;
        r.disposed_excluded_rationales =
            vec![("src/gen.rs".to_string(), "generated; no entity".to_string())];
        let md = render_fidelity_report(&r, 8_000, &[]).markdown;
        assert!(md.contains("Excluded on purpose (persisted dispositions):"));
        assert!(md.contains("`src/gen.rs` — generated; no entity"));
    }

    /// B5 — the denominator provenance is stated; a non-enumerable medium says
    /// so rather than inventing a denominator.
    #[test]
    fn b5_denominator_provenance_stated() {
        let r = base_report();
        let md = render_fidelity_report(&r, 8_000, &[]).markdown;
        assert!(md.contains("## Denominator provenance"));
        assert!(md.contains("per-medium enumeration `S(D)` = **10**"));

        let mut non = base_report();
        non.coverage.denominator = DenominatorBasis::NonEnumerable {
            reason: "the medium type(s) are not enumerable this cycle".to_string(),
        };
        let md2 = render_fidelity_report(&non, 8_000, &[]).markdown;
        assert!(md2.contains("No `S(D)` denominator"));
        assert!(md2.contains("not enumerable this cycle"));
    }

    /// E1 (report half) — a mem that predates its binding renders the onboarding
    /// framing: the expected-0%-anchored statement plus the concrete backfill
    /// path. REFUSAL: no failure/error framing and no red "are findings" verdict
    /// is produced solely by pre-binding history — the uncovered artifacts are
    /// reframed as the backfill worklist.
    #[test]
    fn e1_adopt_report_renders_onboarding_no_red_verdict() {
        let mut r = base_report();
        r.adopt = true;
        r.coverage_semantics = CoverageSemantics::Exhaustive;
        r.coverage.uncovered = (0..5).map(|i| format!("src/file_{i}.rs")).collect();
        let md = render_fidelity_report(&r, 8_000, &[]).markdown;

        // Onboarding framing leads, with the expected-0% statement …
        assert!(md.contains("## Adopting — first verify"));
        assert!(md.contains("0% anchored is expected — this is onboarding, not a failure."));
        // … and the concrete backfill path.
        assert!(
            md.contains("**Backfill path:** run `memstead projection brief engine/graph --sync`")
        );
        // REFUSAL: the exhaustive branch never frames uncovered as red defect
        // "findings" under adopt — it is the onboarding backfill worklist.
        assert!(
            !md.contains("are **findings**"),
            "pre-binding history must not produce a red findings verdict"
        );
        assert!(md.contains("Exhaustive coverage (onboarding):"));
        assert!(md.contains("backfill worklist"));

        // Complement: without adopt, the same uncovered set IS framed as findings.
        r.adopt = false;
        let md2 = render_fidelity_report(&r, 8_000, &[]).markdown;
        assert!(!md2.contains("## Adopting — first verify"));
        assert!(md2.contains("are **findings**"));
    }

    /// An unknown include key is surfaced as a warning, not silently dropped.
    #[test]
    fn unknown_include_key_warns() {
        let r = base_report();
        let out = render_fidelity_report(&r, 8_000, &["bogus".to_string()]);
        assert!(out.markdown.contains("unknown include key `bogus`"));
    }

    // ---- assembly (impure) end-to-end ------------------------------------

    use crate::anchor::{Anchor, AnchorHashStability, AnchorProvenanceClass, AnchorSidecar};
    use crate::binding::{
        BINDING_VERSION, Binding, BuildMode, BuildOperation, DEFAULT_ADJUDICATION_CAP,
        DEFAULT_FULL_RESYNC_EVERY, Operations, VerifyOperation,
    };
    use crate::ingest::findings::verify_binding;
    use crate::ingest::resolve::resolve_binding_run;
    use crate::pipeline::{IngestTrigger, MediumType, PatternEntry, PatternMode};
    use crate::pipeline_store::{load_pipeline_configs, write_binding};
    use crate::workspace::{
        Mount, MountCapability, MountLifecycle, MountStorage, Workspace, WorkspaceSettings,
    };
    use crate::workspace_store::WorkspaceStoreAdapter;

    /// The assembly reads the engine, findings store, and enumeration end to
    /// end: coverage is classed over `S(D)` with a direct-covered file, a
    /// tree-only file, and an uncovered file; the tree fan-out is on its own
    /// axis; the `authored` anchor is its own excluded bucket; the tier-3
    /// backlog reads from the store the verify pass populated. Read-only on the
    /// mem throughout (`&Engine`).
    #[test]
    fn compute_report_end_to_end() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let mem_dir = root.join("mem");
        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
        std::fs::write(
            mem_dir.join(".memstead").join("config.json"),
            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
        )
        .unwrap();

        std::fs::create_dir_all(root.join(".memstead")).unwrap();
        std::fs::write(
            root.join(".memstead").join("workspace.toml"),
            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
        )
        .unwrap();
        let mount = Mount {
            mem: "engine".to_string(),
            schema: Some("default@1.0.0".parse().unwrap()),
            storage: MountStorage::Folder {
                path: mem_dir.clone(),
            },
            capability: MountCapability::Write,
            lifecycle: MountLifecycle::Eager,
            cross_linkable: false,
            migration_target: None,
        };
        crate::FileWorkspaceStore::new()
            .save_state(
                root,
                &Workspace {
                    mounts: vec![mount],
                    settings: WorkspaceSettings::default(),
                },
            )
            .unwrap();

        let out = std::process::Command::new("git")
            .args(["init", "-q"])
            .current_dir(root)
            .output()
            .unwrap();
        assert!(out.status.success());
        std::fs::create_dir_all(root.join("src").join("sub")).unwrap();
        std::fs::write(root.join("src").join("present.rs"), "fn a() {}\n").unwrap();
        std::fs::write(root.join("src").join("uncovered.rs"), "fn b() {}\n").unwrap();
        std::fs::write(root.join("src").join("sub").join("deep.rs"), "fn c() {}\n").unwrap();

        let mk = |artifact: &str, grain: AnchorGrain, class: AnchorProvenanceClass| Anchor {
            artifact: artifact.to_string(),
            grain,
            class,
            at_version: None,
            hash: class.is_hash_bearing().then(|| "recorded".to_string()),
            hash_stability: AnchorHashStability::Stable,
            derived_from: Vec::new(),
            binding: None,
            source: None,
        };
        let mut sidecar = AnchorSidecar::default();
        sidecar.set(
            "engine--direct",
            vec![mk(
                "src/present.rs",
                AnchorGrain::File,
                AnchorProvenanceClass::Anchored,
            )],
        );
        sidecar.set(
            "engine--tree",
            vec![mk(
                "src/sub/",
                AnchorGrain::Tree,
                AnchorProvenanceClass::Anchored,
            )],
        );
        // An authored anchor — its own excluded bucket, never scored.
        sidecar.set(
            "engine--auth",
            vec![mk(
                "src/present.rs",
                AnchorGrain::File,
                AnchorProvenanceClass::Authored,
            )],
        );
        std::fs::write(
            mem_dir.join(crate::anchor::ANCHOR_SIDECAR_PATH),
            sidecar.to_bytes(),
        )
        .unwrap();

        write_binding(
            root,
            "engine",
            "graph",
            &Binding {
                version: BINDING_VERSION,
                intent: None,
                sources: vec![crate::pipeline::Source {
                    name: "graph".to_string(),
                    medium_type: MediumType::Codebase,
                    pointer: String::new(),
                    change_detection: Some("git".to_string()),
                    scope: vec![PatternEntry {
                        path: "src/**/*.rs".to_string(),
                        mode: PatternMode::Allow,
                    }],
                    engagement: None,
                    preparation: None,
                }],
                reference_mems: Vec::new(),
                destination_mem: "engine".to_string(),
                deny_paths: Vec::new(),
                coverage_semantics: None,
                rules: None,
                prune: None,
                operations: Operations {
                    build: Some(BuildOperation {
                        mode: BuildMode::Discovery,
                        trigger: IngestTrigger::Loop,
                        batch_size: 20,
                        post_actions: None,
                    }),
                    sync: None,
                    verify: Some(VerifyOperation {
                        trigger: IngestTrigger::Manual,
                        batch_size: 20,
                        adjudication_cap: DEFAULT_ADJUDICATION_CAP,
                        full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
                    }),
                },
            },
        )
        .unwrap();

        let engine = Engine::from_workspace_root(root).unwrap();
        let configs = load_pipeline_configs(root).unwrap();
        let binding = &configs.bindings[0].config;
        let resolved = resolve_binding_run("engine/graph", binding).unwrap();

        // Populate the durable findings store (group A) — read-only on the mem.
        let outcome = verify_binding(&engine, root, binding, &resolved).unwrap();

        // Assemble the tier-1 report (group B) under the same key.
        let report = compute_fidelity_report(&engine, root, binding, &resolved, &outcome.key);

        // S(D) = the three .rs files under src/.
        assert_eq!(
            report.coverage.denominator,
            DenominatorBasis::Enumerated { count: 3 }
        );
        // present.rs is directly covered; sub/deep.rs is tree-only; uncovered.rs
        // is uncovered.
        assert_eq!(report.coverage.direct_covered, 1);
        assert_eq!(report.coverage.tree_only_covered, 1);
        assert_eq!(
            report.coverage.uncovered,
            vec!["src/uncovered.rs".to_string()]
        );
        // The tree anchor's fan-out is on its own axis — one anchor over one file.
        assert_eq!(report.coverage.tree_anchors.len(), 1);
        assert_eq!(report.coverage.tree_anchors[0].fanout, 1);
        assert_eq!(report.coverage.tree_anchors[0].artifact, "src/sub/");
        // `authored` is its own excluded bucket, never in the resolution tally.
        assert_eq!(report.anchors.authored, 1);
        assert_eq!(report.anchors.by_class.get("authored"), Some(&1));
        // Two hash-bearing anchors present: the file anchor's recorded hash
        // mismatches the observed prepared form → deterministic drift; the
        // tree anchor has no prepared form without a code map → recheck (honest
        // deferral, never fabricated drift). Observed excludes authored.
        assert_eq!(report.anchors.observed, 2);
        assert_eq!(report.anchors.recheck, 1);
        assert_eq!(report.anchors.drifted, 1);
        // Backlog reads from the store the verify pass populated.
        assert_eq!(report.backlog, outcome.backlog);
        // A degradation flag for the deferred hash adjudication.
        assert!(
            report
                .degradations
                .iter()
                .any(|d| d.contains("hash-adjudication-deferred"))
        );
        // The rendered report is deterministic and carries the S(D) statement.
        let md = render_fidelity_report(&report, 8_000, &[]).markdown;
        assert!(md.contains("per-medium enumeration `S(D)` = **3**"));
        // This mem carries anchors, so it does NOT predate its binding — no
        // onboarding framing (the E1 complement).
        assert!(!report.adopt);
        assert!(!md.contains("## Adopting — first verify"));
    }

    /// E1 (report half) end-to-end — a mem with **no** anchors and no `#synced`
    /// baseline predates its binding: `compute_fidelity_report` sets `adopt` from
    /// the live engine, and the rendered report leads with onboarding framing
    /// with no red findings verdict. Read-only on the mem (`&Engine`).
    #[test]
    fn compute_report_adopt_when_mem_predates_binding() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        let mem_dir = root.join("mem");
        std::fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
        std::fs::write(
            mem_dir.join(".memstead").join("config.json"),
            r#"{"format":1,"schema":"default@1.0.0","version":"1.0.0"}"#,
        )
        .unwrap();
        std::fs::create_dir_all(root.join(".memstead")).unwrap();
        std::fs::write(
            root.join(".memstead").join("workspace.toml"),
            "format = \"memstead-git-branch-2\"\n\n[persistence_adapter]\nname = \"file-two-layer\"\n",
        )
        .unwrap();
        let mount = Mount {
            mem: "engine".to_string(),
            schema: Some("default@1.0.0".parse().unwrap()),
            storage: MountStorage::Folder {
                path: mem_dir.clone(),
            },
            capability: MountCapability::Write,
            lifecycle: MountLifecycle::Eager,
            cross_linkable: false,
            migration_target: None,
        };
        crate::FileWorkspaceStore::new()
            .save_state(
                root,
                &Workspace {
                    mounts: vec![mount],
                    settings: WorkspaceSettings::default(),
                },
            )
            .unwrap();
        let out = std::process::Command::new("git")
            .args(["init", "-q"])
            .current_dir(root)
            .output()
            .unwrap();
        assert!(out.status.success());
        std::fs::create_dir_all(root.join("src")).unwrap();
        // In-scope source with no anchor yet — the backfill worklist.
        std::fs::write(root.join("src").join("a.rs"), "fn a() {}\n").unwrap();
        std::fs::write(root.join("src").join("b.rs"), "fn b() {}\n").unwrap();

        write_binding(
            root,
            "engine",
            "graph",
            &Binding {
                version: BINDING_VERSION,
                intent: None,
                sources: vec![crate::pipeline::Source {
                    name: "graph".to_string(),
                    medium_type: MediumType::Codebase,
                    pointer: String::new(),
                    change_detection: Some("git".to_string()),
                    scope: vec![PatternEntry {
                        path: "src/**/*.rs".to_string(),
                        mode: PatternMode::Allow,
                    }],
                    engagement: None,
                    preparation: None,
                }],
                reference_mems: Vec::new(),
                destination_mem: "engine".to_string(),
                deny_paths: Vec::new(),
                coverage_semantics: None,
                rules: None,
                prune: None,
                operations: Operations {
                    build: Some(BuildOperation {
                        mode: BuildMode::Discovery,
                        trigger: IngestTrigger::Loop,
                        batch_size: 20,
                        post_actions: None,
                    }),
                    sync: None,
                    verify: Some(VerifyOperation {
                        trigger: IngestTrigger::Manual,
                        batch_size: 20,
                        adjudication_cap: DEFAULT_ADJUDICATION_CAP,
                        full_resync_every: DEFAULT_FULL_RESYNC_EVERY,
                    }),
                },
            },
        )
        .unwrap();

        let engine = Engine::from_workspace_root(root).unwrap();
        let configs = load_pipeline_configs(root).unwrap();
        let binding = &configs.bindings[0].config;
        let resolved = resolve_binding_run("engine/graph", binding).unwrap();
        let outcome = verify_binding(&engine, root, binding, &resolved).unwrap();
        let report = compute_fidelity_report(&engine, root, binding, &resolved, &outcome.key);

        // No anchors + no baseline → the mem predates its binding (E1).
        assert!(
            report.adopt,
            "a no-anchor, never-synced mem predates its binding"
        );
        let md = render_fidelity_report(&report, 8_000, &[]).markdown;
        assert!(md.contains("## Adopting — first verify"));
        assert!(md.contains("0% anchored is expected"));
        // REFUSAL: the uncovered source is NOT a red findings verdict here.
        assert!(!md.contains("are **findings**"));
        assert!(md.contains("Exhaustive coverage (onboarding):"));
    }

    /// The report renders the EFFECTIVE coverage and marks the case
    /// where it was resolved from the media rather than declared —
    /// a reader never mistakes a resolution for an author's assertion.
    #[test]
    fn report_marks_resolved_coverage_semantics() {
        let mut resolved = base_report();
        resolved.coverage_semantics = CoverageSemantics::Curated;
        resolved.coverage_semantics_declared = false;
        let md = render_hard_required(&resolved);
        assert!(
            md.contains("curated (resolved from the sources' media — not declared)"),
            "resolved value carries the marker: {md}"
        );

        let declared = base_report(); // declared: true in the fixture
        let md = render_hard_required(&declared);
        assert!(
            md.contains("**Coverage semantics:** exhaustive\n"),
            "declared value renders bare: {md}"
        );
        assert!(
            !md.contains("(resolved from the sources' media"),
            "no resolution marker on a declared value: {md}"
        );
    }
}

#[cfg(test)]
mod rollup_tests {
    use super::*;

    /// A report whose every axis is substantive and whose findings are empty
    /// — the only shape that may verdict `clean`. Each test degrades exactly
    /// one axis from here, so a failure names the axis that moved.
    fn clean_report() -> FidelityReport {
        FidelityReport {
            binding: "engine/graph".to_string(),
            destination_mem: "engine".to_string(),
            adopt: false,
            coverage_semantics: CoverageSemantics::Exhaustive,
            coverage_semantics_declared: true,
            capabilities: vec![FacetCapability {
                facet: "src".to_string(),
                medium_type: "codebase".to_string(),
                enumerable: true,
                change_signal: true,
                base_version_retrievable: true,
                anchor_namespace: "path".to_string(),
                signal: "git".to_string(),
            }],
            freshness: vec![FacetFreshness {
                facet: "src".to_string(),
                signal: "git".to_string(),
                synced: Some("deadbeef".to_string()),
                verified: None,
                change_detectable: true,
            }],
            source_moved_past_synced: Some(false),
            coverage: GrainCoverage {
                denominator: DenominatorBasis::Enumerated { count: 4 },
                direct_covered: 4,
                tree_only_covered: 0,
                uncovered: Vec::new(),
                tree_anchors: Vec::new(),
            },
            anchors: AnchorComposition {
                by_class: BTreeMap::from([("anchored".to_string(), 4)]),
                by_grain: BTreeMap::from([("file".to_string(), 4)]),
                authored: 0,
                observed: 4,
                resolves: 4,
                drifted: 0,
                recheck: 0,
                orphaned: 0,
                unobserved: 0,
            },
            findings_by_class: BTreeMap::new(),
            backlog: 0,
            superseded: Vec::new(),
            disposed_excluded: 0,
            disposed_excluded_rationales: Vec::new(),
            degradations: Vec::new(),
        }
    }

    /// A substantive pass with nothing recorded is the only way to green.
    #[test]
    fn clean_requires_a_substantive_pass_and_no_findings() {
        let mut r = clean_report();
        assert_eq!(r.rollup().verdict, RollupVerdict::Clean);
        assert!(r.rollup().blind_spots.is_empty());
        assert!(r.rollup().actions.is_empty());

        r.findings_by_class.insert("drifted".to_string(), 2);
        let roll = r.rollup();
        assert_eq!(roll.verdict, RollupVerdict::Drifted);
        assert_eq!(roll.findings_total, 2);
        assert!(
            roll.actions[0].contains("moved since the entity was written"),
            "the top action is the concrete next step: {:?}",
            roll.actions
        );
    }

    /// Criterion 4's complement: a vacuous measurement is never summarized as
    /// clean. The graph medium's `0/0` case reports `enumerable: true` and
    /// enumerates nothing, which is exactly how a "0 findings" run could look
    /// green while having observed no source at all.
    #[test]
    fn a_vacuous_zero_over_zero_is_inconclusive_not_clean() {
        let mut r = clean_report();
        r.coverage.denominator = DenominatorBasis::Enumerated { count: 0 };
        let roll = r.rollup();
        assert_eq!(
            roll.verdict,
            RollupVerdict::Inconclusive,
            "0/0 is not a clean bill of health"
        );
        assert!(
            roll.blind_spots.iter().any(|s| s.contains("vacuous")),
            "the blindness is named, not implied: {:?}",
            roll.blind_spots
        );
    }

    /// A facet that cannot be enumerated blocks green on its own, even when
    /// a sibling facet makes the binding-level denominator `Enumerated`. The
    /// mixed-binding case is exactly where a per-binding check would miss it.
    #[test]
    fn a_non_enumerable_facet_blocks_green_even_in_a_mixed_binding() {
        let mut r = clean_report();
        r.capabilities.push(FacetCapability {
            facet: "site".to_string(),
            medium_type: "web".to_string(),
            enumerable: false,
            // Deliberately TRUE: isolates the enumerability axis from the
            // change-signal one, so this test fails if only the latter is
            // checked.
            change_signal: true,
            base_version_retrievable: false,
            anchor_namespace: "url".to_string(),
            signal: "none".to_string(),
        });
        // The enumerable sibling keeps the denominator populated.
        assert!(matches!(
            r.coverage.denominator,
            DenominatorBasis::Enumerated { count } if count > 0
        ));
        let roll = r.rollup();
        assert_eq!(
            roll.verdict,
            RollupVerdict::Inconclusive,
            "one enumerable facet must not launder a non-enumerable one: {roll:?}"
        );
        assert!(
            roll.blind_spots
                .iter()
                .any(|s| s.contains("not enumerable")),
            "{:?}",
            roll.blind_spots
        );
    }

    /// A binding that declares `change_detection: "none"` over a medium that
    /// COULD signal change is change-blind all the same. The capability row
    /// still reads `change_signal: true` — only the resolved signal and the
    /// freshness row know — so a rollup reading capabilities alone renders
    /// this green while its own body prints "freshness unknowable".
    #[test]
    fn a_resolved_signal_of_none_blocks_green_even_when_the_medium_could_signal() {
        let mut r = clean_report();
        // Exactly the shape `change_detection: "none"` over a codebase
        // produces: the MEDIUM can signal, the BINDING declined to.
        r.capabilities[0].change_signal = true;
        r.capabilities[0].signal = "none".to_string();
        r.freshness[0].change_detectable = false;
        r.freshness[0].signal = "none".to_string();
        let roll = r.rollup();
        assert_eq!(
            roll.verdict,
            RollupVerdict::Inconclusive,
            "a change-blind binding is not a clean bill of health: {roll:?}"
        );
        assert!(
            roll.blind_spots
                .iter()
                .any(|s| s.contains("could not read that signal")),
            "the blind spot names the unreadable signal: {:?}",
            roll.blind_spots
        );
    }

    /// A medium with no change signal cannot observe drift, so it cannot
    /// support a green verdict on that axis — the capability row decides,
    /// not the finding count.
    #[test]
    fn a_facet_without_a_change_signal_blocks_green() {
        let mut r = clean_report();
        r.capabilities[0].change_signal = false;
        let roll = r.rollup();
        assert_eq!(roll.verdict, RollupVerdict::Inconclusive);
        assert!(
            roll.blind_spots
                .iter()
                .any(|s| s.contains("no change signal")),
            "{:?}",
            roll.blind_spots
        );
    }

    /// A non-enumerable scope means an uncovered artifact is undetectable —
    /// silence there is absence of evidence, not evidence of absence.
    #[test]
    fn a_non_enumerable_scope_blocks_green() {
        let mut r = clean_report();
        r.coverage.denominator = DenominatorBasis::NonEnumerable {
            reason: "web medium".to_string(),
        };
        assert_eq!(r.rollup().verdict, RollupVerdict::Inconclusive);
    }

    /// A pass that adjudicated nothing observed nothing.
    #[test]
    fn zero_observed_anchors_blocks_green() {
        let mut r = clean_report();
        r.anchors.observed = 0;
        r.anchors.resolves = 0;
        assert_eq!(r.rollup().verdict, RollupVerdict::Inconclusive);
    }

    /// E1: a mem that predates its binding is expected to be 0% anchored, so
    /// uncovered findings there are the backfill worklist. No red verdict may
    /// be produced SOLELY by pre-binding history — but it is not clean either.
    #[test]
    fn adopt_with_only_uncovered_is_never_red() {
        let mut r = clean_report();
        r.adopt = true;
        r.findings_by_class.insert("uncovered".to_string(), 12);
        let roll = r.rollup();
        assert_eq!(
            roll.verdict,
            RollupVerdict::Inconclusive,
            "onboarding is neither drift nor a clean bill: {roll:?}"
        );
        assert!(
            roll.because.contains("backfill worklist"),
            "the reason states the onboarding framing: {}",
            roll.because
        );

        // Real drift on an adopting mem is still drift — the E1 framing
        // covers pre-binding history, not everything that follows it.
        r.findings_by_class.insert("drifted".to_string(), 1);
        assert_eq!(r.rollup().verdict, RollupVerdict::Drifted);
    }

    /// An observed finding outranks a blind spot: the pass could not see
    /// everything, but what it did see is real.
    #[test]
    fn findings_outrank_blind_spots() {
        let mut r = clean_report();
        r.capabilities[0].change_signal = false;
        r.findings_by_class.insert("wrong".to_string(), 1);
        let roll = r.rollup();
        assert_eq!(roll.verdict, RollupVerdict::Drifted);
        assert!(
            !roll.blind_spots.is_empty(),
            "the blindness is still reported alongside the verdict"
        );
    }

    /// Actions are ordered by what a reader should fix first, and a class the
    /// vocabulary grows past the ranked list is never silently dropped.
    #[test]
    fn actions_are_severity_ordered_and_never_drop_a_class() {
        let mut r = clean_report();
        r.findings_by_class.insert("uncovered".to_string(), 3);
        r.findings_by_class.insert("wrong".to_string(), 1);
        r.findings_by_class
            .insert("some-future-class".to_string(), 2);
        let roll = r.rollup();
        assert!(
            roll.actions[0].contains("contradict their source"),
            "{roll:?}"
        );
        assert_eq!(roll.actions.len(), 3, "{roll:?}");
        assert!(
            roll.actions.iter().any(|a| a.contains("some-future-class")),
            "an unranked class still surfaces: {roll:?}"
        );
    }

    /// The wire vocabulary is closed and stable — consumers branch on it.
    #[test]
    fn verdict_wire_strings_are_stable() {
        assert_eq!(RollupVerdict::Clean.wire(), "clean");
        assert_eq!(RollupVerdict::Drifted.wire(), "drifted");
        assert_eq!(RollupVerdict::Inconclusive.wire(), "inconclusive");
        let json = serde_json::to_string(&RollupVerdict::Inconclusive).unwrap();
        assert_eq!(json, "\"inconclusive\"");
    }
}