headwater-check 0.4.0

Generates the rules from the taxonomy, runs them, computes coverage against the census, and keys each instance on what it read and on the clock it was handed
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
// SPDX-License-Identifier: Apache-2.0
//! Scope: what one check may read, carried by the type it receives.
//!
//! [Spec 12](../../../../docs/spec/12-check-layer.md#scope--the-declaration-everything-else-rests-on)
//! states what the declaration buys: "the view exposes *only* what the scope
//! declared. A `Document`-scoped check physically cannot read a sibling." It
//! states the cost of the alternative too. A scope that nothing enforces "would
//! silently corrupt every cache key derived from it", so spec 12 lists scope
//! enforcement as a
//! [correctness root](../../../../docs/spec/12-check-layer.md#the-correctness-roots).
//!
//! # The declaration is a type, and this module is where that holds
//!
//! [Spec 12](../../../../docs/spec/12-check-layer.md#the-declaration-is-a-type-not-a-returned-value)
//! rules out a `scope()` method: "a scope that a check *returns* is a second
//! fact beside the argument it receives. Nothing connects them, so a check can
//! declare `Document` and still be handed a view that reads the corpus."
//!
//! One trait per scope removes the second fact. Three properties of this module
//! enforce it:
//!
//! 1. **A view has private fields, and only this module builds one.** A check
//!    cannot widen the view it was handed, and it cannot construct a wider one.
//! 2. **[`Scope`] has private fields and no public constructor.** A check
//!    cannot mint a scope. The engine derives the reported scope from the
//!    trait, in [`document_scope`], [`edge_scope`], [`neighbourhood_scope`] and
//!    [`corpus_scope`], and each one reads only its own trait.
//! 3. **The view owns the read set, and the check never does.** An instance
//!    records what the view carried, so a check cannot under-report what it
//!    read. Spec 12 uses that set for two things: the cache key, and the read
//!    set that keeps a verdict honest under merge. Each read carries the census
//!    digest of the file. A key over a path alone would survive every edit to
//!    the document it names.
//!
//! # What a check still declares, and what it cannot
//!
//! The grain comes from the trait. `NEEDS_BODY`, `NEEDS_PHASE_A` and
//! `NEEDS_CLOCK` stay declarations, because each states an input the check
//! needs and none of them claims a grain. One rule enforces all three: a view
//! returns nothing to a check that did not declare the input.
//!
//! `NEEDS_PHASE_A` is the third of them and the newest.
//! [`headwater_graph::Trouble`] is what the graph build could not make of one
//! document, and a rule that reports a phase-A defect has to read it. It
//! arrives **on the view**, restricted to the one document the instance is
//! over, rather than on the check. A check that held the whole report could
//! look a sibling's path up as easily as its own, and that is the widening this
//! module makes impossible.
//!
//! `VERSION` is the other declaration, and it is the one component of a cache
//! key that no input supplies. It says which edition of a rule reached a
//! verdict, so a change to what a rule decides invalidates the entries the
//! earlier edition wrote. Nothing derives it: two editions of a rule read the
//! same documents and the same lock, and they differ only in code. So an author
//! raises it by hand.
//!
//! `tests/editions.rs` catches an author who forgets, where a recorded corpus
//! shows it. `fixtures/editions.ledger` holds, for each rule over each
//! recorded corpus it reaches, its `VERSION`, a fingerprint of the corpus and
//! a digest of what the cache would store for every verdict it reaches there.
//! A digest that moves while `VERSION` and the corpus stay fails, and
//! `HEADWATER_BLESS` does not re-record it. An edit to a corpus is re-recorded
//! by bless. The ledger cannot see four things: a change that no recorded
//! corpus exercises, a rule with no instance on any of them (the test lists
//! each one with the reason), a rule change in the same commit as an edit to
//! its corpus, and a change visible only against a warm cache that an older
//! binary wrote. The last is the digest over the compiled rule that
//! [13 — Open obligations](../../../../docs/spec/13-open-obligations.md)
//! still carries.
//!
//! # The clock is one declaration with two uses, and that is the point
//!
//! `NEEDS_CLOCK` decides two things through one value of [`Scope`]. It decides
//! whether a view carries [`crate::Context::now`], and whether the cache key
//! carries the same date. The two cannot drift, because the instantiation
//! functions below bind the clock once and hand that binding to the view and to
//! [`crate::cache`].
//!
//! That answers the hole spec 13 recorded against the key. A check that reads
//! the clock and does not key on it serves yesterday's verdict today. The
//! `--no-cache` differential cannot see it, because both sides of that
//! comparison hold one value of the clock.
//!
//! # The prior version is the second declaration of that shape
//!
//! `NEEDS_PRIOR` decides the same two things through one value of [`Scope`].
//! [`prior_for`] is the second half of [`clock_for`]: one call per
//! instantiation, and its result goes to the view and to the cache key. A run
//! where the prior version differs therefore keys differently, and a cached
//! verdict cannot survive a change to the version it was about.
//!
//! Spec 12 makes the prior version available **only in change-scoped
//! evaluation**, and that is where the two declarations part. A run with no
//! change cannot hand one over. It does not pass the instance either. The
//! engine creates every instance of such a check and reports it as skipped,
//! with the reason [`CHANGE_SCOPED_ONLY`], because a check that quietly
//! contributes nothing in the mode a repository actually runs is the silent
//! pass
//! [spec 4](../../../../docs/spec/04-assurance-model.md#no-silent-passes-every-document-is-accounted-for)
//! exists to prevent.
//!
//! The view carries the front matter of the same document at an earlier state,
//! so no scope widens. A document-scoped check still reads one document and
//! still cannot reach a sibling.
//!
//! # Where the instance set comes from
//!
//! A check is a template, and the engine instantiates it per target. The
//! generation step reads the taxonomy alone. It asks `instantiates` about a
//! kind or a relation name and never about a document, so a check cannot choose
//! its own targets out of the corpus. That is the same failure as a returned
//! scope, one level up.
//!
//! Order is the census's for a document check and for a neighbourhood check,
//! and the graph's edge order for an edge check. All three are path order, so a
//! run reports its instances in one order and `fixtures/check.report` records
//! it.

use crate::cache::Cache;
use crate::change::{Departed, Prior};
use crate::context::{Context, Date};
use crate::instance::{Input, Instance, Outcome};
use headwater_census::census::{Census, Outcome as Classification};
use headwater_census::resolve::Step;
use headwater_doc::Body;
use headwater_graph::{Direction, Edge, Graph, Target, Trouble};
use headwater_yaml::{Mapping, Span};

/// A typed row that carries no document. Unreachable, and recorded rather than
/// dropped: an instance that vanishes is a document that coverage calls
/// unchecked for a reason nobody can read.
const NO_DOCUMENT: &str = "the row carries no document to read";

/// The unit one instance is created over.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Grain {
    /// One document: its front matter, and its body when the check asks.
    Document,
    /// One relation instance and both endpoints.
    Edge,
    /// One document and the documents one relation away from it.
    ///
    /// [Spec 12](../../../../docs/spec/12-check-layer.md#what-this-leaves-open)
    /// leaves the depth open and suspects the grain is unnecessary: "if no real
    /// check needs depth > 1, the correct move is to cut it and to keep `Edge`
    /// as the only relational scope". The depth is fixed at 1 here for that
    /// reason, and the sentence is answered rather than dodged in
    /// [`crate::participation`]: an `Edge` instance exists per edge, and a
    /// participation expectation is about an edge that nobody declared.
    Neighbourhood { depth: u8 },
    /// Everything. Spec 12 calls these the barriers.
    Corpus,
    /// The resolved taxonomy, and no document at all.
    ///
    /// [Spec 12](../../../../docs/spec/12-check-layer.md#scope--the-declaration-everything-else-rests-on) draws
    /// every scope over the corpus, and it names five. A rule that reads the
    /// taxonomy rather than the corpus fits none of them, and
    /// [`crate::register`] holds two: an obligation that carries no disposition
    /// and a control whose mechanism this engine does not implement are both
    /// defects of the taxonomy, and neither has a document to point at.
    ///
    /// The grain is here rather than folded into [`Grain::Corpus`] because the
    /// two read different things. A corpus-grained rule reads every row of the
    /// census, and its verdict moves when a document moves. A taxonomy-grained
    /// one reads the lock, and its verdict moves when the lock moves. To call
    /// the second one corpus-grained would put a document in a read set that no
    /// document was ever read for.
    /// [13 — Open obligations](../../../../docs/spec/13-open-obligations.md)
    /// carries what that costs spec 12's list.
    Taxonomy,
}

impl Grain {
    /// The word a report prints.
    pub fn name(self) -> &'static str {
        match self {
            Grain::Document => "document",
            Grain::Edge => "edge",
            Grain::Neighbourhood { .. } => "neighbourhood",
            Grain::Corpus => "corpus",
            Grain::Taxonomy => "taxonomy",
        }
    }

    /// Whether an instance of this grain is **routed** to the documents it
    /// reads, which is the question [`crate::coverage`] asks of it.
    ///
    /// [Spec 4](../../../../docs/spec/04-assurance-model.md#no-silent-passes-every-document-is-accounted-for)
    /// states OB-COV-2 as "every classified document is routed to at least one
    /// check", and routing is the generation step: a template, a declaration,
    /// and one instance per target. The three grains above route, and their
    /// targets are documents or the edges between them. The two below do not.
    /// A corpus-grained instance exists once and its target is the corpus, so
    /// it is nobody's routing however many documents it reads.
    ///
    /// The distinction is here because the alternative deletes a rule. A
    /// corpus-scoped instance reads every document, so a coverage report that
    /// counted reading would call every document checked, and
    /// `coverage.document_unchecked` could never fire again. One rule would
    /// then declare the whole corpus covered, which is the silent pass the
    /// census exists to prevent.
    pub fn routes(self) -> bool {
        match self {
            Grain::Document | Grain::Edge | Grain::Neighbourhood { .. } => true,
            Grain::Corpus | Grain::Taxonomy => false,
        }
    }
}

/// What one check instance may read.
///
/// The fields are private and no public constructor exists, so no check
/// outside this crate can build one. That is the point: a `Scope` is derived
/// from the trait a check implements, and it is never a second fact beside it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scope {
    grain: Grain,
    needs_body: bool,
    needs_phase_a: bool,
    needs_clock: bool,
    needs_prior: bool,
    needs_claims: bool,
    needs_observations: bool,
}

impl Scope {
    pub(crate) const fn document(
        needs_body: bool,
        needs_phase_a: bool,
        needs_clock: bool,
        needs_prior: bool,
    ) -> Self {
        Scope {
            grain: Grain::Document,
            needs_body,
            needs_phase_a,
            needs_clock,
            needs_prior,
            needs_claims: false,
            needs_observations: false,
        }
    }

    pub(crate) const fn edge(needs_clock: bool, needs_observations: bool) -> Self {
        Scope {
            grain: Grain::Edge,
            needs_body: false,
            needs_phase_a: false,
            needs_clock,
            needs_prior: false,
            needs_claims: false,
            needs_observations,
        }
    }

    pub(crate) const fn neighbourhood(needs_clock: bool) -> Self {
        Scope {
            grain: Grain::Neighbourhood { depth: 1 },
            needs_body: false,
            needs_phase_a: false,
            needs_clock,
            needs_prior: false,
            needs_claims: false,
            needs_observations: false,
        }
    }

    pub(crate) const fn corpus(needs_phase_a: bool, needs_prior: bool, needs_claims: bool) -> Self {
        Scope {
            grain: Grain::Corpus,
            needs_body: false,
            needs_phase_a,
            needs_clock: false,
            needs_prior,
            needs_claims,
            needs_observations: false,
        }
    }

    pub(crate) const fn taxonomy() -> Self {
        Scope {
            grain: Grain::Taxonomy,
            needs_body: false,
            needs_phase_a: false,
            needs_clock: false,
            needs_prior: false,
            needs_claims: false,
            needs_observations: false,
        }
    }

    pub fn grain(&self) -> Grain {
        self.grain
    }

    pub fn needs_body(&self) -> bool {
        self.needs_body
    }

    /// Whether an instance of this scope receives what phase A could not make
    /// of its document. It joins the cache key on the same terms the body does
    /// not need to: a report about one document is a function of that
    /// document's bytes, which the read set already carries, and the flag is in
    /// the key because it changes what the instance read.
    pub fn needs_phase_a(&self) -> bool {
        self.needs_phase_a
    }

    /// Whether an instance of this scope receives the injected clock, and so
    /// whether its cache key carries one. One fact, both uses.
    pub fn needs_clock(&self) -> bool {
        self.needs_clock
    }

    /// Whether an instance of this scope receives the version of its document
    /// that stood before the change, and so whether its cache key carries the
    /// hash of that version. One fact, both uses, as the clock is.
    ///
    /// It is also what makes an instance of this scope skip in a full-corpus
    /// run, because that is the run that has no change to take one from.
    pub fn needs_prior(&self) -> bool {
        self.needs_prior
    }

    /// Whether an instance of this scope receives the identifier claim store,
    /// and so whether its cache key carries the flag and its read set carries
    /// the store's digest. One fact, both uses, as the clock is.
    ///
    /// The store is not a document and it lives outside the corpus root, so it
    /// reaches an instance through this flag and through nothing else. A flag
    /// that changed what an instance read and did not reach the key is the
    /// correctness bug
    /// [spec 12](../../../../docs/spec/12-check-layer.md#determinism-concretely)
    /// names.
    pub fn needs_claims(&self) -> bool {
        self.needs_claims
    }

    /// Whether an instance of this scope receives the committed observation
    /// snapshot, and so whether its cache key carries the flag and its read
    /// set carries the snapshot's digest. One fact, both uses, as the clock
    /// is.
    ///
    /// The snapshot is not one of the edge's two endpoints, so neither
    /// endpoint's digest moves when only the snapshot changes: it reaches an
    /// instance through this flag and through nothing else, on
    /// [`Scope::needs_claims`]'s own terms. A flag that changed what an
    /// instance read and did not reach the key is the correctness bug
    /// [spec 12](../../../../docs/spec/12-check-layer.md#determinism-concretely)
    /// names, and it is the bug [#937](https://github.com/headwater-ai/headwater/issues/937)
    /// found live: a rule reading [`crate::observation::Observations`]
    /// straight from its own struct field, with no input in its read set to
    /// show for it, is cached against a key that cannot see an edit to the
    /// file it just read.
    pub fn needs_observations(&self) -> bool {
        self.needs_observations
    }

    /// The scope as one line of a report, in spec 12's own words for the
    /// grain. A reader who counts the barriers reads them here.
    pub fn render(&self) -> String {
        let carries = match (self.grain, self.needs_body) {
            (Grain::Document, false) => "one document and its front matter",
            (Grain::Document, true) => "one document, its front matter and its body",
            (Grain::Edge, _) => "one relation instance and both endpoints",
            (Grain::Neighbourhood { .. }, _) => {
                "one document and the documents one relation away from it"
            }
            (Grain::Corpus, _) => "every row of the census",
            (Grain::Taxonomy, _) => "the resolved taxonomy, and no document",
        };
        // Phase A's report, where the rule declared it. A reader who counts the
        // barriers has to see that this instance read one more thing than front
        // matter, and the two grains that declare it read two different sets:
        // one document's news at document grain, and the identity of every
        // document at corpus grain.
        let phase_a = match (self.needs_phase_a, self.grain) {
            (false, _) => "",
            (true, Grain::Corpus) => {
                ", and what phase A could not make of each document's identity"
            }
            (true, _) => ", and what phase A could not make of it",
        };
        // The clock is named because it is an input like any other, and because
        // spec 12 puts it in the cache key. A reader who asks why a warm run
        // re-evaluated one rule and not another reads the answer here.
        let clock = match self.needs_clock {
            true => ", and the injected clock",
            false => "",
        };
        // The other temporal input, named on the same terms. A reader who asks
        // why every instance of one rule skipped over a whole corpus reads the
        // answer here: this scope is available only in change-scoped evaluation.
        // The two grains that declare it read two different things, and one
        // sentence for both would tell a reader of a corpus-scoped rule that it
        // was handed one document.
        let prior = match (self.needs_prior, self.grain) {
            (false, _) => "",
            (true, Grain::Corpus) => {
                ", and the version of each path the change named that no row of this corpus holds"
            }
            (true, _) => ", and the version of it that stood before the change",
        };
        // The one input of this engine that is not a document and not an
        // injected value. A reader who asks how a rule reaches a directory
        // beside the corpus root reads the answer here.
        let claims = match self.needs_claims {
            true => ", and the identifier claim store",
            false => "",
        };
        // The other input outside the corpus, named on [`Scope::needs_claims`]'s
        // own terms: a reader who asks how a rule reaches the committed
        // observation snapshot beside its two endpoints reads the answer here.
        let observations = match self.needs_observations {
            true => ", and the committed observation snapshot",
            false => "",
        };
        // Spec 12 calls the corpus-scoped checks the barriers, and the word is
        // last so that it reads as a statement about the scope rather than
        // about the inputs listed before it.
        let barrier = match self.grain {
            Grain::Corpus => ", and it is a barrier",
            _ => "",
        };
        format!(
            "{} scope, {carries}{phase_a}{clock}{prior}{claims}{observations}{barrier}",
            self.grain.name()
        )
    }
}

/// The emitter targets a check exports to, and the empty set is the common
/// value.
///
/// [Spec 12](../../../../docs/spec/12-check-layer.md#exportable_as-is-a-set-with-a-partition-rule)
/// states the bar a name in this set has to clear: the emitted constraint
/// catches exactly what the native check catches, in both directions. A
/// construct that misses a document the check reports is a partial
/// translation, and a construct that rejects a document the check accepts is
/// worse, because a loss set cannot record it. A differential test is what
/// permits a value here, and `engine/crates/generate/tests/differential.rs`
/// is that test.
///
/// The declaration sits on the check rather than in a table beside it, for the
/// reason the scope does. A second list of rules is a list that drifts.
pub type ExportTargets = &'static [&'static str];

/// A check over one document.
pub trait DocumentCheck {
    const RULE: &'static str;
    /// Which edition of this rule reached a verdict. See the module comment:
    /// it keys the cache, and raising it is what invalidates every entry an
    /// earlier edition wrote. Raise it whenever `tests/editions.rs` reports
    /// that this rule's verdicts moved, then re-record with `HEADWATER_BLESS=1`.
    const VERSION: u32;
    /// The emitter targets this check exports to. See [`ExportTargets`]. The
    /// default is the empty set, because most checks reach nothing a schema
    /// language can say, and a default of "unexported" cannot claim coverage
    /// by accident.
    const EXPORTABLE_AS: ExportTargets = &[];
    /// Whether the view carries the body. A check that does not declare it
    /// receives nothing from [`DocumentView::body`], so the declaration is the
    /// access rather than a note beside it.
    const NEEDS_BODY: bool = false;
    /// Whether the view carries what phase A could not make of this document,
    /// on the same terms: a check that does not declare it receives nothing
    /// from [`DocumentView::phase_a`].
    ///
    /// It is what a rule that routes a structural finding needs, and it is
    /// deliberately not a handle on the graph. The view carries the report for
    /// the one document the instance is over and no other, so a rule that
    /// reports a phase-A defect still cannot read a sibling.
    const NEEDS_PHASE_A: bool = false;
    /// Whether the view carries the injected clock, on the same terms and with
    /// one more consequence: it joins the cache key.
    const NEEDS_CLOCK: bool = false;
    /// Whether the view carries the version of this document that stood before
    /// the change, on the clock's terms and with one more consequence again:
    /// spec 12 makes the input available only in change-scoped evaluation, so
    /// every instance of this check in a full-corpus run is reported as skipped.
    ///
    /// It is the input transition legality needs. One value of a facet cannot
    /// say how it was reached, so a rule about a movement reads the state the
    /// document moved from.
    const NEEDS_PRIOR: bool = false;

    /// The generation step: whether this template has an instance over a
    /// document of this kind. It reads the taxonomy and never the corpus.
    fn instantiates(&self, kind: &str) -> bool {
        let _ = kind;
        true
    }

    /// The second half of the generation step: whether this template has an
    /// instance over the document at this corpus-relative path. It reads the
    /// taxonomy and the path the census walked, and never the document.
    ///
    /// A rule whose population is a declared list of paths rather than a set
    /// of kinds selects here, so a document off the list has no instance
    /// rather than an instance that passes unread (#1051). The default selects
    /// every path.
    fn selects(&self, path: &str) -> bool {
        let _ = path;
        true
    }

    fn evaluate(&self, view: &DocumentView<'_>) -> Outcome;
}

/// What one edge-scoped instance is created over.
///
/// Both members are one relation instance, which is the grain
/// [spec 12](../../../../docs/spec/12-check-layer.md#scope--the-declaration-everything-else-rests-on) fixes for
/// this trait. They differ over what counts as one, and the difference is
/// whether the target resolved.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EdgeUnit {
    /// The pair that
    /// [Q4](../../../../docs/spec/09-decisions.md#q4--relation-storage)
    /// identifies: a source identifier, a relation, and a target document. Two
    /// reciprocal halves are one instance of it, and an edge whose target is
    /// not a document is no instance at all, because there is no second
    /// endpoint to read.
    Pair,
    /// One entry of one `relations:` block, whatever its target became.
    ///
    /// A rule about the target *string* has to reach an entry whose string
    /// bound to nothing, and a pair cannot carry one. A target that no document
    /// answers to has no far end, so nothing at that end can have written the
    /// other half. Two halves of one bound pair are two instances here, and
    /// correctly so: they are two strings, written by two authors, in two
    /// files, and each one is right or wrong on its own.
    Entry,
}

/// A check over one relation instance and both of its endpoints.
pub trait EdgeCheck {
    const RULE: &'static str;
    /// As [`DocumentCheck::VERSION`].
    const VERSION: u32;
    /// As [`DocumentCheck::EXPORTABLE_AS`].
    const EXPORTABLE_AS: ExportTargets = &[];
    /// As [`DocumentCheck::NEEDS_CLOCK`].
    const NEEDS_CLOCK: bool = false;
    /// As [`CorpusCheck::NEEDS_CLAIMS`], for the committed observation
    /// snapshot rather than the claim store: a rule that reads
    /// [`crate::observation::Observations`] declares it here, so the
    /// snapshot's digest joins this rule's own per-instance read set and its
    /// cache key, on [`Scope::needs_observations`]'s terms. A rule that reads
    /// the snapshot without setting this is cached against a key that never
    /// moves when the file it read does.
    const NEEDS_OBSERVATIONS: bool = false;
    /// What one instance of this check covers. See [`EdgeUnit`].
    ///
    /// The trait declares it, and the runner does not pass it. The reason is
    /// the reason the grain is a trait: a unit the caller chose is a second
    /// fact beside the check, and nothing holds the two together.
    ///
    /// It stays off [`Scope`] because it selects which instances exist. A
    /// scope states what one instance may read, and that is also the whole of
    /// what a cache key covers.
    const UNIT: EdgeUnit = EdgeUnit::Pair;

    /// The generation step, as [`DocumentCheck::instantiates`], over the name
    /// of the relation an edge declares.
    fn instantiates(&self, relation: &str) -> bool {
        let _ = relation;
        true
    }

    fn evaluate(&self, view: &EdgeView<'_>) -> Outcome;
}

/// A check over the whole corpus: spec 12's barrier.
///
/// There is no `instantiates`, and the absence is the grain. Every other trait
/// here generates one instance per target out of a declaration, and this one
/// has a single target that no declaration selects. So the count of the
/// barriers is the count of the corpus-scoped rules, which is the number
/// [spec 12](../../../../docs/spec/12-check-layer.md#scope--the-declaration-everything-else-rests-on)
/// asks a reader to be able to read rather than discover under load.
///
/// A rule belongs here when its subject is a relation between two documents
/// that no edge connects. Two documents that claim one identifier are the
/// case: nothing links them, so [`Grain::Neighbourhood`] does not reach them,
/// and a document-scoped instance reads one of the two, so its key survives
/// every edit to the other one.
pub trait CorpusCheck {
    const RULE: &'static str;
    /// As [`DocumentCheck::VERSION`].
    const VERSION: u32;
    /// As [`DocumentCheck::EXPORTABLE_AS`].
    const EXPORTABLE_AS: ExportTargets = &[];
    /// Whether the view carries what phase A could not make of the identity of
    /// any document, on [`DocumentCheck::NEEDS_PHASE_A`]'s terms.
    ///
    /// The document-grained flag hands a rule the report about its own file and
    /// nothing else, which is what keeps that grain honest. There is no such
    /// restriction to make here: this scope reads the corpus, so the report it
    /// receives is the corpus-wide one.
    const NEEDS_PHASE_A: bool = false;

    /// Whether the view carries the paths the change named that no row of this
    /// corpus holds, and the version of each one.
    ///
    /// [`DocumentCheck::NEEDS_PRIOR`] hands one document the version of
    /// itself, which no rule about a document that left can use: there is no
    /// row to instantiate over, so there is no such instance. This flag is the
    /// corpus-grained half of the same input, and it carries the same
    /// consequence — an instance of a rule that declares it skips in a run that
    /// names no change, because that run has no change to take one from.
    const NEEDS_PRIOR: bool = false;

    /// Whether the view carries the identifier claim store.
    ///
    /// The store is at `.headwater/ids`, beside the corpus and not inside it,
    /// so no census row covers it and no read set would carry it by accident.
    /// A rule that declares this receives [`headwater_check::claim::Claims`]
    /// and one more [`Input`] in its read set, whose digest is over the store's
    /// canonical listing. See [`crate::claim`].
    ///
    /// It carries none of [`CorpusCheck::NEEDS_PRIOR`]'s consequence. An absent
    /// store is an empty store rather than a missing input, so an instance that
    /// declares this runs in every run, which is what the drift it reports
    /// requires: a rule that skipped in a plain `headwater check` would be
    /// dormant in exactly the run that reads this corpus end to end.
    const NEEDS_CLAIMS: bool = false;

    /// Whether the view carries every prose link the build bound, with what
    /// each one resolved to.
    ///
    /// It joins no cache key and it has no [`Scope`] flag, and that is the one
    /// thing about it worth stating. The four inputs above are each injected
    /// into a view from outside the read set — a report the graph made, a
    /// version out of a change, a clock the caller fixed, a store beside the
    /// corpus — so a key that did not name them would omit an input. The links
    /// are not that. They are a *reading of* the documents this instance
    /// already reads, derived by the build from those same bytes, so the read
    /// set names them already and a key component here would hash the same
    /// bytes twice and cold-start every cache of every adopting corpus for a
    /// fact no verdict depends on. [`crate::link_path`] carries the one case
    /// where that reasoning does not reach, which is a link whose target is
    /// not a document of this corpus.
    const NEEDS_LINKS: bool = false;

    /// Whether the view carries the heading anchors of every document of this
    /// corpus, by path.
    ///
    /// It joins no cache key, and the argument is [`CorpusCheck::NEEDS_LINKS`]'s
    /// exactly: the anchors are a *reading of* the documents this instance
    /// already reads, derived from the same bytes the read set names, so a key
    /// component here would hash those bytes twice and cold-start every cache
    /// of every adopting corpus for a fact no verdict depends on.
    ///
    /// It is declared rather than taken silently, because a rule that reads an
    /// input it never named is what these declarations exist to stop, and a
    /// reader of this trait should see every input a rule takes without reading
    /// its body. See [`crate::fragment`].
    const NEEDS_ANCHORS: bool = false;

    /// Whether the view carries every edge of the graph and every generated
    /// document of the census.
    ///
    /// It joins no cache key, on [`CorpusCheck::NEEDS_LINKS`]'s terms. The
    /// edges are a reading of the documents this instance already reads, and
    /// a generated document is a row that carries a document, so it is in the
    /// read set already. The one rule that declares this reads the edges
    /// `headwater generate` reads, onto the documents it writes. See
    /// [`crate::state_set_twice`].
    const NEEDS_GRAPH: bool = false;

    /// Whether the view carries the marked files the projection plan claims no
    /// output for, as [`Context::orphaned`] holds them.
    ///
    /// It joins the cache key, and it is the one corpus input here that does
    /// so outside the read set. `headwater generate` computes the set from the
    /// lock and the tree, and this crate cannot repeat that computation, so
    /// the caller injects it. A key without it would keep a cached "fired"
    /// verdict through the change that turned the page into an orphan. It is
    /// not an [`Input`], because a read set lists paths a later
    /// `headwater gate` reads back from disk, and this set is not a file. So
    /// it goes into the key on the terms of an anchor target: as the
    /// `resolution` line that [`crate::cache`] writes for something outside
    /// the corpus told this run. See [`crate::state_set_twice`].
    const NEEDS_ORPHANED: bool = false;

    fn evaluate(&self, view: &CorpusView<'_>) -> Outcome;
}

/// A check over one document and the documents one relation away from it.
pub trait NeighbourhoodCheck {
    const RULE: &'static str;
    /// As [`DocumentCheck::VERSION`].
    const VERSION: u32;
    /// As [`DocumentCheck::EXPORTABLE_AS`].
    const EXPORTABLE_AS: ExportTargets = &[];
    /// As [`DocumentCheck::NEEDS_CLOCK`].
    const NEEDS_CLOCK: bool = false;

    /// The generation step, as [`DocumentCheck::instantiates`], over the kind
    /// of the document at the centre.
    fn instantiates(&self, kind: &str) -> bool {
        let _ = kind;
        true
    }

    fn evaluate(&self, view: &NeighbourhoodView<'_>) -> Outcome;
}

/// The scope of a document-scoped check, derived from its trait.
pub fn document_scope<C: DocumentCheck>() -> Scope {
    Scope::document(
        C::NEEDS_BODY,
        C::NEEDS_PHASE_A,
        C::NEEDS_CLOCK,
        C::NEEDS_PRIOR,
    )
}

/// The scope of an edge-scoped check, derived from its trait.
pub fn edge_scope<C: EdgeCheck>() -> Scope {
    Scope::edge(C::NEEDS_CLOCK, C::NEEDS_OBSERVATIONS)
}

/// The scope of a neighbourhood-scoped check, derived from its trait.
pub fn neighbourhood_scope<C: NeighbourhoodCheck>() -> Scope {
    Scope::neighbourhood(C::NEEDS_CLOCK)
}

/// The scope of a corpus-scoped check, derived from its trait.
pub fn corpus_scope<C: CorpusCheck>() -> Scope {
    Scope::corpus(C::NEEDS_PHASE_A, C::NEEDS_PRIOR, C::NEEDS_CLAIMS)
}

/// The edition of a document-scoped check, derived from its trait.
///
/// A report reads this the way it reads the scope, and for the same reason:
/// [`crate::ReadSet`] publishes the version of every rule that ran, and a
/// version written beside a rule rather than read off it is a second fact that
/// nothing holds to the first.
pub fn document_version<C: DocumentCheck>() -> u32 {
    C::VERSION
}

/// The edition of an edge-scoped check, derived from its trait.
pub fn edge_version<C: EdgeCheck>() -> u32 {
    C::VERSION
}

/// The edition of a neighbourhood-scoped check, derived from its trait.
pub fn neighbourhood_version<C: NeighbourhoodCheck>() -> u32 {
    C::VERSION
}

/// The edition of a corpus-scoped check, derived from its trait.
pub fn corpus_version<C: CorpusCheck>() -> u32 {
    C::VERSION
}

/// The export targets of a document-scoped check, derived from its trait.
pub fn document_exports<C: DocumentCheck>() -> ExportTargets {
    C::EXPORTABLE_AS
}

/// The export targets of an edge-scoped check, derived from its trait.
pub fn edge_exports<C: EdgeCheck>() -> ExportTargets {
    C::EXPORTABLE_AS
}

/// The export targets of a neighbourhood-scoped check, derived from its trait.
pub fn neighbourhood_exports<C: NeighbourhoodCheck>() -> ExportTargets {
    C::EXPORTABLE_AS
}

/// The export targets of a corpus-scoped check, derived from its trait.
pub fn corpus_exports<C: CorpusCheck>() -> ExportTargets {
    C::EXPORTABLE_AS
}

/// The clock a check of this scope receives, and nothing for one that did not
/// declare it.
///
/// One function, called once per instantiation, and its result goes to the view
/// and to the cache key. That is what makes the two incapable of disagreeing.
fn clock_for(scope: Scope, ctx: &Context) -> Option<Date> {
    match scope.needs_clock() {
        true => Some(ctx.now()),
        false => None,
    }
}

/// The prior version of one document, for a scope that declared the input.
///
/// [`clock_for`]'s second half, and the same rule: called once per instance, and
/// the value it returns goes to the view and to the cache key.
///
/// Three answers rather than two, because a run that cannot supply the input is
/// not the same as an input a document has no value for.
enum PriorFor<'a> {
    /// A scope that did not declare the input. The view carries nothing.
    NotDeclared,
    /// The version this instance is held against.
    Bound(Prior<'a>),
    /// No verdict is possible, and the text is the reason a report prints. The
    /// run has no change, or the caller named a version this engine could not
    /// read.
    Skip(String),
}

/// The reason spec 12 fixes for an instance of a prior-reading check in a run
/// that carries no change.
///
/// The words are the specification's own, and a reader who greps a report for
/// them lands on the sentence that rules them.
pub const CHANGE_SCOPED_ONLY: &str = "change-scoped-only";

fn prior_for<'a>(scope: Scope, ctx: &'a Context, path: &str) -> PriorFor<'a> {
    if !scope.needs_prior() {
        return PriorFor::NotDeclared;
    }
    let Some(change) = ctx.change() else {
        return PriorFor::Skip(format!(
            "{CHANGE_SCOPED_ONLY}: the prior version is available only in change-scoped \
             evaluation, and this run carries no change"
        ));
    };
    match change.prior_of(path) {
        Ok(prior) => PriorFor::Bound(prior),
        Err(why) => PriorFor::Skip(why.to_string()),
    }
}

/// One document, and nothing else.
///
/// There is no accessor for a second document, for the taxonomy, or for the
/// graph. That absence is the enforcement: a check that wants a sibling has to
/// implement a wider trait, and the runner then keys its cache accordingly.
pub struct DocumentView<'a> {
    path: &'a str,
    digest: Option<&'a str>,
    kind: &'a str,
    placed_on: Option<&'a str>,
    facets: &'a Mapping,
    body: Option<&'a Body>,
    phase_a: Option<Trouble<'a>>,
    clock: Option<Date>,
    prior: Option<Prior<'a>>,
    /// The language regime that lists this path outside the corpus root, and
    /// nothing for a census row. See [`over_outside_root`].
    regime: Option<&'a str>,
}

impl<'a> DocumentView<'a> {
    /// Relative to the repository root, with `/` separators.
    pub fn path(&self) -> &'a str {
        self.path
    }

    /// The kind the census resolved for this document.
    ///
    /// The empty string for a path outside the corpus root, which no kind
    /// binds. No kind has that name, so no `instantiates` accepts it.
    pub fn kind(&self) -> &'a str {
        self.kind
    }

    /// The language regime that lists this path outside the corpus root, and
    /// nothing for a document under it. A check that reads it looks its
    /// binding up by this name rather than by [`DocumentView::kind`].
    pub fn outside_regime(&self) -> Option<&'a str> {
        self.regime
    }

    /// The shelf whose placement carried the kind, and nothing when a
    /// discriminator in front matter carried it instead. Read back from the
    /// derivation the census recorded, so it cannot disagree with the kind.
    pub fn placed_on(&self) -> Option<&'a str> {
        self.placed_on
    }

    /// The front matter, as the author declared it.
    pub fn facets(&self) -> &'a Mapping {
        self.facets
    }

    /// The body, and only for a check that declared `NEEDS_BODY`.
    pub fn body(&self) -> Option<&'a Body> {
        self.body
    }

    /// What phase A could not make of **this** document, and only for a check
    /// that declared `NEEDS_PHASE_A`.
    ///
    /// It is the graph build's own answer rather than a second reading of the
    /// same front matter. See [`headwater_graph::Trouble`] for why a check that
    /// re-derived it would be a second definition of one defect.
    pub fn phase_a(&self) -> Option<&Trouble<'a>> {
        self.phase_a.as_ref()
    }

    /// The injected date, and only for a check that declared `NEEDS_CLOCK`.
    pub fn now(&self) -> Option<Date> {
        self.clock
    }

    /// The version of this document that stood before the change, and only for
    /// a check that declared `NEEDS_PRIOR`.
    ///
    /// A check that declared it is never handed `None`: an instance with no
    /// prior version to bind is skipped before a view exists. The option is the
    /// declaration, on the same terms as [`DocumentView::body`].
    pub fn prior(&self) -> Option<Prior<'a>> {
        self.prior
    }

    /// What this view lets a check read: one document, and the hash of it.
    pub fn reads(&self) -> Vec<Input> {
        vec![Input::new(self.path, self.digest)]
    }
}

/// One relation instance, both endpoints, and the halves that declared it.
///
/// A pair is one target however many documents wrote it, which is
/// [Q4](../../../../docs/spec/09-decisions.md#q4--relation-storage)'s identity
/// for an edge: the source identifier, the relation name, and the normalized
/// target. Position in a list is not part of it.
pub struct EdgeView<'a> {
    relation: &'a str,
    declared: Option<&'a Edge>,
    inverse: Option<&'a Edge>,
    /// The two ends in the direction the relation declares, source first, and
    /// nothing for an instance whose far end is not a document. See
    /// [`EdgeView::ends`].
    ends: Option<(EdgeEnd<'a>, EdgeEnd<'a>)>,
    /// The front matter of the document that declared the half this instance
    /// is keyed on. See [`EdgeView::declarer_facets`].
    declarer: Option<&'a Mapping>,
    clock: Option<Date>,
    reads: Vec<Input>,
    resolution: String,
}

/// One end of a relation instance, in the direction the relation declares.
///
/// [Spec 12](../../../../docs/spec/12-check-layer.md#scope--the-declaration-everything-else-rests-on)
/// fixes an edge-scoped instance at "one relation instance **and both
/// endpoints**", and the front matter here is that clause read literally. It is
/// not the depth-1 boundary that [`Neighbour`] holds: a neighbourhood has as
/// many neighbours as the corpus wrote, so a front matter on each one would
/// make that grain a corpus view, while an edge has exactly two ends and the
/// read set already hashes both of them.
#[derive(Clone, Copy, Debug)]
pub struct EdgeEnd<'a> {
    pub id: &'a str,
    pub path: &'a str,
    pub kind: &'a str,
    facets: Option<&'a Mapping>,
    generated: bool,
    digest: Option<&'a str>,
}

impl<'a> EdgeEnd<'a> {
    /// The front matter of the document at this end, as its author wrote it.
    ///
    /// Nothing where the census carries no parsed document for the path, which
    /// is an absence rather than empty front matter: a rule that read the two
    /// as one would report a document nobody could open as one that declared
    /// nothing.
    pub fn facets(&self) -> Option<&'a Mapping> {
        self.facets
    }

    /// Whether this engine wrote the file at this end.
    ///
    /// The census's answer, carried here rather than re-derived: the marker has
    /// one predicate, `headwater_mark::carries_marker`, and the census is the
    /// one caller of it over a corpus. A rule that opened the marker key itself
    /// would be a second reading of which files this engine wrote, and the two
    /// could then disagree about one file.
    ///
    /// It rides beside [`EdgeEnd::facets`] because the two answer one question
    /// together. Spec 3 gives a generated document a warrant the engine derives
    /// and no declared one, so a rule holding the front matter alone reads an
    /// absence where there is an answer. [`headwater_doc::warrant_of`] is what
    /// takes the pair.
    pub fn generated(&self) -> bool {
        self.generated
    }

    /// The census's own digest of the bytes at this end, and nothing where
    /// the census read none.
    ///
    /// The same digest [`Digests::input`] carries into the read set, so a
    /// rule that compares it against a value recorded elsewhere — a
    /// committed observation snapshot, for [`crate::verification`] — is
    /// comparing against the exact bytes this run's read set already keys
    /// on, rather than opening the file a second time.
    pub fn digest(&self) -> Option<&'a str> {
        self.digest
    }
}

impl<'a> EdgeView<'a> {
    /// Build the view over the halves of one pair. It returns nothing when no
    /// half carries a direction, which is what an empty group produces. It
    /// returns rather than panics for the reason a check never panics: one bad
    /// group must not silence the rest of the corpus.
    ///
    /// The digests come from the census, because the walk that read a document
    /// is what recorded its digest. An edge carries no bytes of its own. It is
    /// declared inside the front matter of one of its endpoints, so hashing
    /// both endpoints covers the relation name, the target and every instance
    /// attribute on it.
    fn over(
        halves: &[&'a Edge],
        census: &'a Census,
        digests: &Digests,
        clock: Option<Date>,
    ) -> Option<Self> {
        let declared = halves
            .iter()
            .copied()
            .find(|edge| edge.direction == Direction::AsDeclared);
        let inverse = halves
            .iter()
            .copied()
            .find(|edge| edge.direction == Direction::Inverse);

        // The read set names the declaring end first, and the declared
        // direction wins when both ends wrote their half. So one pair reads
        // the same two documents in the same order whatever the verdict is.
        let anchor = declared.or(inverse)?;
        let mut reads = vec![digests.input(&anchor.source.path)];
        if let Target::Document { path, .. } = &anchor.target {
            // A self-edge is one file at both ends, and one instance counts
            // once against one document however many times it names it.
            if !reads.iter().any(|input| &input.path == path) {
                reads.push(digests.input(path));
            }
        }

        // The two ends, normalized once. An author may write either half, so
        // the document that declared the entry sits at the source end or at the
        // target end depending on the direction the graph resolved. Doing it
        // here rather than in each rule is what stops two rules from disagreeing
        // about which end of one edge is which.
        let ends = match &anchor.target {
            Target::Document { id, path, kind } => {
                let (writer_facets, writer_generated, writer_digest) =
                    read_at(census, &anchor.source.path);
                let writer = EdgeEnd {
                    id: &anchor.source.id,
                    path: &anchor.source.path,
                    kind: &anchor.source.kind,
                    facets: writer_facets,
                    generated: writer_generated,
                    digest: writer_digest,
                };
                let (other_facets, other_generated, other_digest) = read_at(census, path);
                let other = EdgeEnd {
                    id,
                    path,
                    kind,
                    facets: other_facets,
                    generated: other_generated,
                    digest: other_digest,
                };
                Some(match anchor.direction {
                    Direction::AsDeclared => (writer, other),
                    Direction::Inverse => (other, writer),
                })
            }
            _ => None,
        };

        Some(EdgeView {
            relation: anchor.declared.as_str(),
            declared,
            inverse,
            ends,
            declarer: read_at(census, &anchor.source.path).0,
            clock,
            reads,
            resolution: anchor.target.resolution(),
        })
    }

    /// What the target of this edge bound to, for the cache key and for
    /// nothing else.
    ///
    /// It is taken from the same half the read set is taken from, so one
    /// instance names one binding however many documents wrote a half of it.
    /// At [`EdgeUnit::Pair`] both halves are documents by construction, and
    /// both are in the read set above. At [`EdgeUnit::Entry`] the half is the
    /// entry, and this is the only component of the key that names what its
    /// target string reached.
    fn resolution(&self) -> &str {
        &self.resolution
    }

    /// The relation this pair declares, after a name resolved to its type.
    pub fn relation(&self) -> &'a str {
        self.relation
    }

    /// The half written from the source end, when a document wrote it.
    pub fn declared_half(&self) -> Option<&'a Edge> {
        self.declared
    }

    /// The half written from the target end, when a document wrote it.
    pub fn inverse_half(&self) -> Option<&'a Edge> {
        self.inverse
    }

    /// The two ends of this relation instance, source first, in the direction
    /// the relation declares.
    ///
    /// Nothing when the far end is not a document: an anchor, a withheld target
    /// and an unbound one are all a relation with one endpoint, and there is no
    /// second document to read. At [`EdgeUnit::Pair`] that never happens, and at
    /// [`EdgeUnit::Entry`] it is most of what the unit exists to reach.
    pub fn ends(&self) -> Option<(EdgeEnd<'a>, EdgeEnd<'a>)> {
        self.ends
    }

    /// The front matter of the document that declared this instance's half,
    /// whatever the far end is.
    ///
    /// [`EdgeView::ends`] is nothing for an anchor target, because there is
    /// no second document. The declaring document is still there, it is
    /// already the first member of [`EdgeView::reads`], and a rule about an
    /// anchor edge can need what its author stated about it: whether it was
    /// verified today is what [`crate::suspect`] reads before it offers a fix
    /// that records a verification. Nothing where the census carries no parsed
    /// document for the path.
    pub fn declarer_facets(&self) -> Option<&'a Mapping> {
        self.declarer
    }

    /// The injected date, and only for a check that declared `NEEDS_CLOCK`.
    pub fn now(&self) -> Option<Date> {
        self.clock
    }

    /// Both endpoints: spec 12 fixes an edge-scoped read set at "one relation
    /// instance **and both endpoints**", and coverage counts the instance
    /// against each of them.
    pub fn reads(&self) -> &[Input] {
        &self.reads
    }
}

/// Which end of a declared relation a document sits at.
///
/// An author may write either half, so the name in front matter does not say
/// this. The direction the graph resolved does.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
    Source,
    Target,
}

/// One document one relation away, and the relation that reaches it.
#[derive(Clone, Copy, Debug)]
pub struct Neighbour<'a> {
    /// The relation type, after a name resolved to it. Never the name an author
    /// wrote, because the two halves of one pair write two different names.
    pub relation: &'a str,
    /// Which end of that relation the document at the centre sits at.
    pub end: End,
    pub path: &'a str,
    pub kind: &'a str,
    pub id: &'a str,
    /// The entry that declared this edge, wherever it was written.
    pub span: Span,
}

/// One document, and the documents one relation away from it.
///
/// The centre is a full document view. A neighbour is an identity and a kind
/// and nothing more: no front matter, no body. That is the depth-1 boundary,
/// and it is what stops this grain from becoming a corpus view with extra
/// steps.
pub struct NeighbourhoodView<'a> {
    path: &'a str,
    kind: &'a str,
    facets: &'a Mapping,
    neighbours: Vec<Neighbour<'a>>,
    clock: Option<Date>,
    reads: Vec<Input>,
}

impl<'a> NeighbourhoodView<'a> {
    pub fn path(&self) -> &'a str {
        self.path
    }

    pub fn kind(&self) -> &'a str {
        self.kind
    }

    /// The front matter of the document at the centre, as its author wrote it.
    pub fn facets(&self) -> &'a Mapping {
        self.facets
    }

    /// Every document one relation away, without repeats, in the graph's edge
    /// order.
    pub fn neighbours(&self) -> &[Neighbour<'a>] {
        &self.neighbours
    }

    /// The injected date, and only for a check that declared `NEEDS_CLOCK`.
    pub fn now(&self) -> Option<Date> {
        self.clock
    }

    /// The centre and every neighbour. A neighbour's kind is a fact its own
    /// front matter decided, so an edit to that file changes what this instance
    /// decided and has to invalidate it.
    pub fn reads(&self) -> &[Input] {
        &self.reads
    }
}

/// The corpus, as the one rule that reads it needs it.
///
/// The read set is every census row that **carries a document**, and that set
/// is the derivation rather than a choice. `Index::build` opens no file: it
/// reads the identifier facet of each row that carries a document, and a row
/// that carries none contributed nothing and could not have. A row the walk
/// never read has no digest either, and an input with no digest is one
/// [`crate::cache`] refuses to key at all, so a read set that held every row
/// would leave this instance permanently unkeyed and the barrier permanently
/// re-evaluated.
///
/// Every transition into and out of that set moves the key. A file that gains
/// front matter gains a row with a document. One that loses it leaves the set.
/// A new file arrives as a new input. An exclusion pattern is in the lock, and
/// the lock digest is a component of every key. So there is no edit to this
/// corpus that changes what this rule decides and leaves its key where it was.
pub struct CorpusView<'a> {
    identity: Option<&'a [headwater_graph::index::Reported]>,
    departed: &'a [Departed<'a>],
    claims: Option<&'a crate::claim::Claims>,
    links: Option<&'a [headwater_graph::links::Link]>,
    anchors: Option<&'a crate::fragment::Anchors>,
    edges: Option<&'a [Edge]>,
    generated: Option<Vec<Generated<'a>>>,
    orphaned: Option<&'a std::collections::BTreeSet<String>>,
    reads: Vec<Input>,
}

/// One document the census classified as generated and resolved a kind for,
/// which is a document `headwater generate` writes the facets of.
#[derive(Clone, Copy, Debug)]
pub struct Generated<'a> {
    pub path: &'a str,
    /// The identifier the index read off it. A generated file that declares
    /// none is not here, because an edge names a document by its identifier.
    pub id: &'a str,
    pub kind: &'a str,
    /// Its front matter, as the last run of the emitter wrote it.
    pub facets: &'a Mapping,
}

impl<'a> CorpusView<'a> {
    /// Every edge of the graph, and only for a check that declared
    /// `NEEDS_GRAPH`.
    pub fn edges(&self) -> Option<&'a [Edge]> {
        self.edges
    }

    /// Every generated document with a kind, in census order, and only for a
    /// check that declared `NEEDS_GRAPH`.
    pub fn generated(&self) -> Option<&[Generated<'a>]> {
        self.generated.as_deref()
    }

    /// The marked files no output of the projection plan claims, and only for
    /// a check that declared `NEEDS_ORPHANED`.
    pub fn orphaned(&self) -> Option<&'a std::collections::BTreeSet<String>> {
        self.orphaned
    }

    /// What the identifier index could not make of any document, and only for
    /// a check that declared `NEEDS_PHASE_A`.
    ///
    /// It is the build's own answer rather than a second reading of the same
    /// front matter, which is [`DocumentView::phase_a`]'s reason and one more
    /// besides. Whether two documents claim one identifier is a judgment over
    /// both shelves of the index in one order, and a rule that re-derived it
    /// from the corpus would be a second definition of the defect that decides
    /// which of the two the graph already bound every edge to.
    pub fn identity(&self) -> Option<&'a [headwater_graph::index::Reported]> {
        self.identity
    }

    /// What the change named that no row of this corpus holds, and only for a
    /// check that declared `NEEDS_PRIOR`.
    ///
    /// Empty is a real answer for a run whose change named no such path. A run
    /// that has no change at all never reaches a view: the runner skips the
    /// instance with the reason, the way it does for a document-scoped rule
    /// that declared the same input.
    pub fn departed(&self) -> &[Departed<'a>] {
        self.departed
    }

    /// The identifier claim store, and only for a check that declared
    /// `NEEDS_CLAIMS`.
    ///
    /// An empty store and no store are two different answers, and the option is
    /// the difference: a run whose scope did not admit the store receives
    /// `None`, and a repository that has minted nothing receives an empty
    /// [`crate::claim::Claims`]. The first is a rule reading what it did not
    /// declare and the second is a fact about a corpus.
    pub fn claims(&self) -> Option<&'a crate::claim::Claims> {
        self.claims
    }

    /// Every prose link the build bound and what each one resolved to, and only
    /// for a check that declared `NEEDS_LINKS`.
    ///
    /// It is the build's own set rather than a second reading of the same
    /// bodies, on [`CorpusView::identity`]'s terms: what counts as a prose
    /// link, which ones are somebody else's quotation, and what a destination
    /// normalizes to are all decisions [`headwater_graph::links`] already made,
    /// and the report already prints the answer.
    ///
    /// `None` is a run whose scope did not admit them, and an empty slice is a
    /// corpus that writes no prose link at all. See [`crate::link_path`].
    pub fn links(&self) -> Option<&'a [headwater_graph::links::Link]> {
        self.links
    }

    /// The heading anchors of every document of this corpus, and only for a
    /// check that declared `NEEDS_ANCHORS`.
    ///
    /// `None` is a run whose scope did not admit them. A corpus that writes no
    /// heading at all is an index that answers `false` for every fragment,
    /// which is a different thing and a real verdict.
    pub fn anchors(&self) -> Option<&'a crate::fragment::Anchors> {
        self.anchors
    }

    /// Every document this view was built over. See the type comment for why
    /// the set is the rows that carry a document rather than every row.
    pub fn reads(&self) -> &[Input] {
        &self.reads
    }

    /// A view carrying nothing but the links, for the tests of the one rule
    /// that reads them. It is `cfg(test)` so that no shipped path can build a
    /// view whose read set does not come from a census.
    #[cfg(test)]
    pub(crate) fn only_links(links: Option<&'a [headwater_graph::links::Link]>) -> Self {
        CorpusView {
            identity: None,
            departed: &[],
            claims: None,
            links,
            anchors: None,
            edges: None,
            generated: None,
            orphaned: None,
            reads: Vec::new(),
        }
    }

    /// A view carrying nothing but the claim store, for the tests of the rule
    /// that reads it alone. `cfg(test)` on [`CorpusView::only_links`]'s terms.
    #[cfg(test)]
    pub(crate) fn only_claims(claims: Option<&'a crate::claim::Claims>) -> Self {
        CorpusView {
            identity: None,
            departed: &[],
            claims,
            links: None,
            anchors: None,
            edges: None,
            generated: None,
            orphaned: None,
            reads: Vec::new(),
        }
    }

    /// A view carrying the links and the anchors, for the tests of the rule
    /// that reads both. `cfg(test)` on [`CorpusView::only_links`]'s terms.
    #[cfg(test)]
    pub(crate) fn only_links_and_anchors(
        links: Option<&'a [headwater_graph::links::Link]>,
        anchors: Option<&'a crate::fragment::Anchors>,
    ) -> Self {
        CorpusView {
            identity: None,
            departed: &[],
            claims: None,
            links,
            anchors,
            edges: None,
            generated: None,
            orphaned: None,
            reads: Vec::new(),
        }
    }
}

/// The digest of each document the census read, by path.
///
/// An edge-scoped view is built from the graph, and a digest is a fact the
/// census holds. This is the one lookup between them, so that no phase invents
/// a hash for a file the walk never read.
pub struct Digests {
    /// In the census's own order, which is path order, so a lookup is a binary
    /// search and never a scan of the corpus per edge.
    by_path: Vec<(String, Option<String>)>,
}

impl Digests {
    pub fn of(census: &Census) -> Self {
        Digests {
            by_path: census
                .rows
                .iter()
                .map(|row| (row.path.clone(), row.digest.clone()))
                .collect(),
        }
    }

    /// One input. A path the census never walked carries no digest, so nothing
    /// over it is keyed, which is the same answer as a file that was not read.
    pub fn input(&self, path: &str) -> Input {
        let digest = self
            .by_path
            .binary_search_by(|(known, _)| known.as_str().cmp(path))
            .ok()
            .and_then(|index| self.by_path[index].1.as_deref());
        Input::new(path, digest)
    }
}

/// What the census holds for one path: the front matter it parsed, whether
/// this engine wrote the file, and the digest of the bytes it read there.
///
/// Nothing for the front matter where the census parsed none, which is an
/// absence rather than empty front matter. `false` for the marker where the
/// census walked no such path at all, because a path outside the census is a
/// path this engine has no record of writing. Nothing for the digest on the
/// same terms: a path the walk never reached carries no bytes to hash.
///
/// The census is the one reader of the corpus, and this is the second lookup
/// into it from an edge-scoped view. [`Digests`] is the first, and it binary
/// searches the same list; the difference is that this one borrows out of the
/// census rather than copying, so it takes the census by reference at the point
/// of use instead of being built once.
///
/// One lookup returns all three facts rather than three functions searching
/// the same list, and the tuple is what [`EdgeEnd`] carries.
fn read_at<'a>(census: &'a Census, path: &str) -> (Option<&'a Mapping>, bool, Option<&'a str>) {
    let Ok(index) = census
        .rows
        .binary_search_by(|row| row.path.as_str().cmp(path))
    else {
        return (None, false, None);
    };
    let row = &census.rows[index];
    (
        row.document.as_ref().map(|document| &document.facets),
        matches!(row.outcome, Classification::Generated { .. }),
        row.digest.as_deref(),
    )
}

/// Instantiate a document-scoped check over a census.
///
/// One instance per typed document the check generates over. An untyped row
/// has no kind and so no document instance, and the census already reports it
/// with its own outcome.
///
/// The graph is here for one reason. A check that declared `NEEDS_PHASE_A`
/// receives what the build could not make of *its* document. A row the census
/// classified as generated is not a typed row, so no instance is created over
/// one and no phase-A report about one reaches a rule. That is spec 6's
/// exemption holding at this grain, and not a second decision here: the
/// content of a generated file is a function of its emitter, and
/// `generate --check` holds it.
pub fn over_documents<C: DocumentCheck>(
    check: &C,
    census: &Census,
    graph: &Graph,
    ctx: &Context,
    cache: &mut Cache,
) -> Vec<Instance> {
    let scope = document_scope::<C>();
    // Bound once. The same value reaches the view and the key, which is what
    // makes a clock-reading check impossible to leave out of its own key.
    let clock = clock_for(scope, ctx);
    let mut instances = Vec::new();
    for row in &census.rows {
        let Classification::Typed { kind, derivation } = &row.outcome else {
            continue;
        };
        if !check.instantiates(kind) || !check.selects(&row.path) {
            continue;
        }
        // Bound once, before anything else about this row is read. A run with
        // no change reaches this arm for every instance of the rule, so the
        // skipped count of a full-corpus run is the instance count exactly, and
        // a reader can hold the two numbers against each other.
        let prior = match prior_for(scope, ctx, &row.path) {
            PriorFor::NotDeclared => None,
            PriorFor::Bound(prior) => Some(prior),
            PriorFor::Skip(why) => {
                cache.undecided();
                instances.push(Instance::skipped(
                    C::RULE,
                    Grain::Document,
                    vec![Input::new(&row.path, row.digest.as_deref())],
                    &why,
                ));
                continue;
            }
        };
        let Some(document) = &row.document else {
            cache.undecided();
            instances.push(Instance::skipped(
                C::RULE,
                Grain::Document,
                vec![Input::new(&row.path, row.digest.as_deref())],
                NO_DOCUMENT,
            ));
            continue;
        };

        let view = DocumentView {
            path: &row.path,
            digest: row.digest.as_deref(),
            kind,
            placed_on: derivation.steps.iter().find_map(|step| match step {
                Step::PlacementCarriesTheKind { shelf, .. } => Some(shelf.as_str()),
                _ => None,
            }),
            facets: &document.facets,
            body: match C::NEEDS_BODY {
                true => Some(&document.body),
                false => None,
            },
            // Built per row and only where the trait asked for it, so a rule
            // that did not declare the input pays nothing and receives nothing.
            phase_a: match C::NEEDS_PHASE_A {
                true => Some(graph.about(&row.path)),
                false => None,
            },
            clock,
            prior,
            regime: None,
        };
        // The target of a document-scoped instance is the document, so the
        // path is its identity as well as its one input.
        let reads = view.reads();
        // No resolution: a document-scoped instance reads one document, and a
        // document is a corpus path that the read set above already names.
        // The prior version is the same binding the view holds, which is what
        // stops a cached verdict from surviving a change to the version it was
        // about.
        let outcome = cache.outcome(
            C::RULE,
            C::VERSION,
            scope,
            &row.path,
            &reads,
            clock,
            prior,
            None,
            || check.evaluate(&view),
        );
        instances.push(Instance::of(C::RULE, Grain::Document, reads, outcome));
    }
    instances
}

/// A document-scoped check that also reads a path outside the corpus root
/// that a language regime lists.
///
/// [HW-DR-0084](../../../../docs/decisions/0084-a-language-rule-reaches-front-door-prose-outside-the-corpus-root-and-no-other-rule-does.md)
/// clause 5 gives three rules such a path and no other rule. The trait is the
/// enforcement: [`over_outside_root`] takes only a check that implements it,
/// and only the three language rules do, so no registration can hand an
/// outside path to a fourth rule by calling the wrong runner.
pub trait OutsideCheck: DocumentCheck {
    /// The generation step for an outside path: whether this template binds
    /// the regime that lists it. It reads the taxonomy and never the file.
    fn binds_regime(&self, regime: &str) -> bool;
}

/// Instantiate a check over the paths outside the corpus root that a language
/// regime lists.
///
/// One instance per listed path whose regime the check binds. The view carries
/// the regime rather than a kind, and it carries no phase-A report, no clock
/// and no prior version: none of the three rules declares any of them, and a
/// path that is not a node has no phase-A report to carry. A check that
/// declared one would read `None` where it expects a value, so the runner
/// refuses the pairing at compile time with the assertion below.
///
/// The census holds these paths outside its rows, so they never reach
/// [`over_documents`] and never join the coverage denominator.
pub fn over_outside_root<C: OutsideCheck>(
    check: &C,
    census: &Census,
    cache: &mut Cache,
) -> Vec<Instance> {
    const {
        assert!(
            !C::NEEDS_PHASE_A && !C::NEEDS_CLOCK && !C::NEEDS_PRIOR,
            "an outside path carries no phase-A report, clock or prior version"
        );
    }
    let scope = document_scope::<C>();
    let mut instances = Vec::new();
    for row in &census.outside.rows {
        if !check.binds_regime(&row.regime) {
            continue;
        }
        let Some(document) = &row.document else {
            cache.undecided();
            instances.push(Instance::skipped(
                C::RULE,
                Grain::Document,
                vec![Input::new(&row.path, row.digest.as_deref())],
                row.unread.as_deref().unwrap_or(NO_DOCUMENT),
            ));
            continue;
        };
        let view = DocumentView {
            path: &row.path,
            digest: row.digest.as_deref(),
            kind: "",
            placed_on: None,
            // Front-door prose usually declares no facets, and the census
            // gives such a file an empty mapping. A file that does declare
            // some is read as written, and the scent facet reaches the rules
            // exactly as it does for a document under the root.
            facets: &document.facets,
            body: match C::NEEDS_BODY {
                true => Some(&document.body),
                false => None,
            },
            phase_a: None,
            clock: None,
            prior: None,
            regime: Some(&row.regime),
        };
        let reads = view.reads();
        let outcome = cache.outcome(
            C::RULE,
            C::VERSION,
            scope,
            &row.path,
            &reads,
            None,
            None,
            None,
            || check.evaluate(&view),
        );
        instances.push(Instance::of(C::RULE, Grain::Document, reads, outcome));
    }
    instances
}

/// Instantiate an edge-scoped check over a graph.
///
/// The unit comes off the trait, and it decides what one instance covers.
/// [`EdgeUnit::Pair`] groups the two reciprocal halves of one Q4 triple and
/// reaches no edge whose target is not a document, because `declared_triple`
/// returns nothing for one. [`EdgeUnit::Entry`] takes every declared edge as
/// written, which is the only unit that reaches a target that bound to
/// nothing.
///
/// One function rather than two, because the grouping is the only difference
/// and everything after it — the view, the read set, the key, the cache — has
/// to be the same for both. Two functions is where the two would drift.
///
/// `observations` is handed to every caller on [`over_corpus`]'s own terms for
/// `claims`: a check that does not set [`EdgeCheck::NEEDS_OBSERVATIONS`] pays
/// nothing for it and never sees it in its read set, and one that does gets
/// the snapshot's digest folded into its own per-instance key rather than only
/// into the run's top-level read set, which is where [#937](https://github.com/headwater-ai/headwater/issues/937)
/// found it missing.
pub fn over_edges<C: EdgeCheck>(
    check: &C,
    census: &Census,
    graph: &Graph,
    digests: &Digests,
    observations: &crate::observation::Observations,
    ctx: &Context,
    cache: &mut Cache,
) -> Vec<Instance> {
    let scope = edge_scope::<C>();
    let clock = clock_for(scope, ctx);
    // The edges arrive in path order, so the groups come out in a stable order
    // with no sort here.
    let mut pairs: Vec<(String, Vec<&Edge>)> = Vec::new();
    for edge in &graph.edges {
        let Some(key) = (match C::UNIT {
            EdgeUnit::Pair => edge
                .declared_triple()
                .and_then(
                    |(source, relation, target)| match check.instantiates(&relation) {
                        true => Some(format!("{source}\u{1f}{relation}\u{1f}{target}")),
                        false => None,
                    },
                ),
            // The authored triple, which the graph already holds to be unique
            // inside one document: a repeated one is `Problem::RepeatedTriple`
            // and declares no second edge. The name is the one an author wrote
            // rather than the relation it resolves to, because two halves of
            // one pair are two entries at this unit and they carry two names.
            EdgeUnit::Entry => match check.instantiates(&edge.declared) {
                true => {
                    let (source, name, target) = edge.triple();
                    Some(format!("{source}\u{1f}{name}\u{1f}{target}"))
                }
                false => None,
            },
        }) else {
            continue;
        };
        match pairs.iter_mut().find(|(known, _)| known == &key) {
            Some((_, halves)) => halves.push(edge),
            None => pairs.push((key, vec![edge])),
        }
    }

    let mut instances = Vec::with_capacity(pairs.len());
    for (triple, halves) in &pairs {
        let Some(view) = EdgeView::over(halves, census, digests, clock) else {
            continue;
        };
        // The triple is the identity Q4 gives an edge, and it is what tells
        // two instances apart that read the same two documents. One pair of
        // documents can carry two relations, and their read sets are equal.
        let mut reads = view.reads().to_vec();
        // The one input outside the two endpoints, added only where the check
        // declared it, on [`Scope::needs_claims`]'s own terms: an absent
        // snapshot adds nothing (it is not an input this run read), an
        // unreadable one adds the path with no digest (which `Cache::key`
        // refuses to key on, so the instance is evaluated fresh every run
        // until the file is readable again), and a read one adds its digest,
        // so an edit to `.headwater/observations.yml` is an edit this
        // instance's own key can see.
        if C::NEEDS_OBSERVATIONS {
            if let Some(digest) = observations.read_set_digest() {
                reads.push(Input::new(crate::observation::PATH, digest));
            }
        }
        // The one scope that reaches a resolver. See [`crate::cache`]: the
        // identity of an anchor edge is the same string on both sides of the
        // change that falsifies its verdict, so the binding is named in the key
        // beside it.
        let outcome = cache.outcome(
            C::RULE,
            C::VERSION,
            scope,
            triple,
            &reads,
            clock,
            // No prior version. Only `DocumentCheck` declares the input, for
            // the reason spec 12 gives it: a change names documents, and an
            // edge is not one.
            None,
            Some(view.resolution()),
            || check.evaluate(&view),
        );
        instances.push(Instance::of(C::RULE, Grain::Edge, reads, outcome));
    }
    instances
}

/// Instantiate a neighbourhood-scoped check over a census and a graph.
///
/// One instance per typed document the check generates over, as at document
/// grain. What differs is the view and so the read set: the centre, plus every
/// document one relation away from it.
pub fn over_neighbourhoods<C: NeighbourhoodCheck>(
    check: &C,
    census: &Census,
    graph: &Graph,
    digests: &Digests,
    ctx: &Context,
    cache: &mut Cache,
) -> Vec<Instance> {
    let scope = neighbourhood_scope::<C>();
    let clock = clock_for(scope, ctx);
    let adjacency = Adjacency::of(graph);

    let mut instances = Vec::new();
    for row in &census.rows {
        let Classification::Typed { kind, .. } = &row.outcome else {
            continue;
        };
        if !check.instantiates(kind) {
            continue;
        }
        let Some(document) = &row.document else {
            cache.undecided();
            instances.push(Instance::skipped(
                C::RULE,
                Grain::Neighbourhood { depth: 1 },
                vec![Input::new(&row.path, row.digest.as_deref())],
                NO_DOCUMENT,
            ));
            continue;
        };

        let neighbours = adjacency.of_path(&row.path);
        let mut reads = vec![Input::new(&row.path, row.digest.as_deref())];
        for neighbour in &neighbours {
            // A bound-anchor neighbour carries the empty marker at `path`
            // rather than a real one (see `Adjacency::of`): there is no file
            // to hash, so it costs the read set nothing and its binding goes
            // into the resolution below instead.
            if !neighbour.path.is_empty() && !reads.iter().any(|input| input.path == neighbour.path)
            {
                reads.push(digests.input(neighbour.path));
            }
        }

        let view = NeighbourhoodView {
            path: &row.path,
            kind,
            facets: &document.facets,
            neighbours,
            clock,
            reads: reads.clone(),
        };
        // `Adjacency` now admits an anchor neighbour
        // ([#855](https://github.com/headwater-ai/headwater/issues/855)), so
        // this grain can reach one the same way `over_edges` already does, and
        // its key has to carry the binding the same way: `Some(view.resolution())`
        // there, `adjacency.anchor_resolution_of_path` here, folded over every
        // anchor this document's neighbours reach rather than at most one.
        let outcome = cache.outcome(
            C::RULE,
            C::VERSION,
            scope,
            &row.path,
            &reads,
            clock,
            None,
            adjacency.anchor_resolution_of_path(&row.path),
            || check.evaluate(&view),
        );
        instances.push(Instance::of(
            C::RULE,
            Grain::Neighbourhood { depth: 1 },
            reads,
            outcome,
        ));
    }
    instances
}

/// The target of the one instance a corpus-scoped check creates.
///
/// A target tells two instances apart that read the same documents. There is
/// one instance of a corpus-scoped rule, so this is a constant, and it is in
/// the key for the reason every other target is: it says what the instance was
/// about, and no read set says that.
const CORPUS: &str = "the corpus";

/// Instantiate a corpus-scoped check over a census and a graph.
///
/// One instance, whatever the corpus holds. That is the count spec 12 calls the
/// barrier count, and it is the tell that separates this grain from a
/// document-scoped rule with a wide read set: the instance count moves by one
/// and the read set moves by the size of the corpus.
pub fn over_corpus<C: CorpusCheck>(
    check: &C,
    census: &Census,
    graph: &Graph,
    claims: &crate::claim::Claims,
    ctx: &Context,
    cache: &mut Cache,
) -> Vec<Instance> {
    let scope = corpus_scope::<C>();
    let mut reads: Vec<Input> = census
        .rows
        .iter()
        .filter(|row| row.document.is_some())
        .map(|row| Input::new(&row.path, row.digest.as_deref()))
        .collect();
    // The corpus-grained half of `prior_for`, and the same three answers. A
    // rule that did not declare the input receives nothing and pays nothing. A
    // rule that declared it and met a run with no change reports the skip
    // rather than an empty set, because "the change named no departed path" and
    // "there is no change" are the two readings that must not become one.
    let departed = match (C::NEEDS_PRIOR, ctx.change()) {
        (false, _) => Vec::new(),
        (true, Some(change)) => change.departed(),
        (true, None) => {
            cache.undecided();
            return vec![Instance::skipped(
                C::RULE,
                Grain::Corpus,
                reads,
                format!(
                    "{CHANGE_SCOPED_ONLY}: the prior version is available only in change-scoped \
                     evaluation, and this run carries no change"
                ),
            )];
        }
    };
    // The prior bytes of a departed path are an input this instance reads, so
    // they are in the read set and therefore in the key. Without them a verdict
    // about a document that left would survive the change that put it back.
    // The digest is over the version the caller named, which is the only
    // version of it this run ever saw.
    reads.extend(
        departed
            .iter()
            .map(|entry| Input::new(entry.path, Some(entry.digest))),
    );
    // The store, named in the read set with a digest. `readset.rs` says an
    // input a run read has to appear or the union is not a union, and
    // `cache.rs` refuses to key an instance carrying an input with no digest,
    // so a store named and not hashed would leave both claim rules permanently
    // re-evaluated. The path is a directory rather than a file, which is why
    // `headwater gate`'s reader answers for it specially.
    if C::NEEDS_CLAIMS {
        let digest = claims.digest();
        reads.push(Input::new(crate::claim::STORE, Some(digest.as_str())));
    }
    // Built here and only where the trait asked for it, so a rule that did not
    // declare the input pays nothing and receives nothing. It derives from the
    // rows already in `reads` above, which is why no input joins the read set
    // with it. See `NEEDS_ANCHORS`.
    let anchors = match C::NEEDS_ANCHORS {
        true => Some(crate::fragment::Anchors::of(census)),
        false => None,
    };
    let view = CorpusView {
        identity: match C::NEEDS_PHASE_A {
            true => Some(&graph.index.defects),
            false => None,
        },
        departed: &departed,
        claims: match C::NEEDS_CLAIMS {
            true => Some(claims),
            false => None,
        },
        // No input joins the read set with them, and the comment on
        // `NEEDS_LINKS` is where that is argued: the links are derived from the
        // documents already listed above rather than injected beside them.
        links: match C::NEEDS_LINKS {
            true => Some(&graph.links),
            false => None,
        },
        anchors: anchors.as_ref(),
        // No input joins the read set with them either. See `NEEDS_GRAPH`.
        edges: match C::NEEDS_GRAPH {
            true => Some(&graph.edges),
            false => None,
        },
        generated: match C::NEEDS_GRAPH {
            true => Some(
                census
                    .rows
                    .iter()
                    .filter_map(|row| match (&row.outcome, &row.document) {
                        (
                            Classification::Generated {
                                kind: Some(kind), ..
                            },
                            Some(document),
                        ) => graph
                            .index
                            .typed
                            .iter()
                            .find(|node| node.path == row.path)
                            .map(|node| Generated {
                                path: &row.path,
                                id: &node.id,
                                kind,
                                facets: &document.facets,
                            }),
                        _ => None,
                    })
                    .collect(),
            ),
            false => None,
        },
        orphaned: match C::NEEDS_ORPHANED {
            true => Some(ctx.orphaned()),
            false => None,
        },
        reads: reads.clone(),
    };
    // The orphan set, in the key and not in the read set. See
    // `NEEDS_ORPHANED`. The digest is over the sorted paths, one to a line,
    // so an empty set writes a line of its own and a rule that declared the
    // input never keys on its absence.
    let orphaned = C::NEEDS_ORPHANED.then(|| {
        let listing: String = ctx
            .orphaned()
            .iter()
            .map(|path| format!("{path}\n"))
            .collect();
        format!("orphaned {}", headwater_hash::digest(listing.as_bytes()))
    });
    // No clock. `CorpusCheck` declares none, so `clock_for` would have nothing
    // to bind and the key would carry nothing about a day. The first
    // corpus-scoped rule that reads a date brings the declaration with it, on
    // the terms the other three traits already state.
    //
    // No `prior` argument either, and this is the one place the two grains key
    // differently. A document-scoped instance is held against one version and
    // writes that one hash. A corpus-scoped one is held against a set, and the
    // set is in the read set above, where every input of this engine already
    // keys. A second component here would hash the same bytes twice.
    let outcome = cache.outcome(
        C::RULE,
        C::VERSION,
        scope,
        CORPUS,
        &reads,
        None,
        None,
        orphaned.as_deref(),
        || check.evaluate(&view),
    );
    vec![Instance::of(C::RULE, Grain::Corpus, reads, outcome)]
}

/// Every document one relation away from each document, built once per run.
///
/// A pair that both ends declared produces two edges, and both of them reach
/// the same two documents by the same relation. So the entries are deduplicated
/// on the identity that a check reads — the relation, the end, and the far
/// document — and never on the edge, which would count one neighbour twice.
struct Adjacency<'a> {
    by_path: Vec<(&'a str, Vec<Neighbour<'a>>)>,
    /// One folded string per document that declares at least one bound-anchor
    /// edge: every such anchor's own binding, in edge order, joined by `\n`.
    ///
    /// `EdgeView::resolution` carries one anchor's binding into an edge-scoped
    /// key (`over_edges`, `Some(view.resolution())`), because one `EdgeView` is
    /// at most one edge. A neighbourhood is depth 1 over as many edges as the
    /// document declares, so its key needs as many bindings, folded for the
    /// reason [HW-OBL-0117](../../../../docs/obligations/0117-a-cached-verdict-about-an-anchor-survives-the-change-that-falsifies-it.md)
    /// already gives an edge-scoped key one: the identity of a bound anchor is
    /// what it resolved to, not the string an author wrote, so a change to the
    /// binding with no change to any read-set byte still has to move the key.
    anchor_resolutions_by_path: Vec<(&'a str, String)>,
}

impl<'a> Adjacency<'a> {
    fn of(graph: &'a Graph) -> Self {
        let mut adjacency = Adjacency {
            by_path: Vec::new(),
            anchor_resolutions_by_path: Vec::new(),
        };
        for edge in &graph.edges {
            match &edge.target {
                Target::Document { id, path, kind } => {
                    // The direction says which end of the *declared* relation
                    // each document sits at, whichever name its author reached
                    // for.
                    let (near, far) = match edge.direction {
                        Direction::AsDeclared => (End::Source, End::Target),
                        Direction::Inverse => (End::Target, End::Source),
                    };
                    adjacency.push(
                        &edge.source.path,
                        Neighbour {
                            relation: &edge.declared,
                            end: near,
                            path,
                            kind,
                            id,
                            span: edge.span,
                        },
                    );
                    adjacency.push(
                        path,
                        Neighbour {
                            relation: &edge.declared,
                            end: far,
                            path: &edge.source.path,
                            kind: &edge.source.kind,
                            id: &edge.source.id,
                            span: edge.span,
                        },
                    );
                }
                Target::Anchor {
                    anchor_kind,
                    normalized,
                    ..
                } => {
                    // An anchor never declares anything, so it is only ever
                    // the far end, and only the declaring document gets a
                    // neighbour: there is no anchor-side list to push the
                    // reciprocal onto
                    // ([#855](https://github.com/headwater-ai/headwater/issues/855)).
                    // `kind` and `id` are exactly what `Target::Anchor`
                    // already carries. `path` has no answer an anchor can
                    // give — it is not a document and the corpus assigns it
                    // no path — so it is the empty string, an absent marker
                    // rather than a real one: `Neighbour::path` is read for
                    // identity only inside `Adjacency::push`'s own dedup,
                    // which an empty string satisfies the same as any other
                    // value, and the one caller outside this module that
                    // reads it, `over_neighbourhoods`'s read-set loop, skips
                    // exactly this marker rather than asking `Digests` to
                    // hash it.
                    let near = match edge.direction {
                        Direction::AsDeclared => End::Source,
                        Direction::Inverse => End::Target,
                    };
                    adjacency.push(
                        &edge.source.path,
                        Neighbour {
                            relation: &edge.declared,
                            end: near,
                            path: "",
                            kind: anchor_kind,
                            id: normalized,
                            span: edge.span,
                        },
                    );
                    adjacency.push_resolution(&edge.source.path, edge.target.resolution());
                }
                _ => continue,
            }
        }
        adjacency
    }

    fn push(&mut self, path: &'a str, neighbour: Neighbour<'a>) {
        let entry = match self.by_path.iter_mut().find(|(known, _)| *known == path) {
            Some(entry) => entry,
            None => {
                self.by_path.push((path, Vec::new()));
                self.by_path.last_mut().expect("just pushed")
            }
        };
        if !entry.1.iter().any(|known| {
            known.relation == neighbour.relation
                && known.end == neighbour.end
                && known.path == neighbour.path
                && known.id == neighbour.id
        }) {
            entry.1.push(neighbour);
        }
    }

    fn push_resolution(&mut self, path: &'a str, resolution: String) {
        match self
            .anchor_resolutions_by_path
            .iter_mut()
            .find(|(known, _)| *known == path)
        {
            Some((_, existing)) => {
                existing.push('\n');
                existing.push_str(&resolution);
            }
            None => self.anchor_resolutions_by_path.push((path, resolution)),
        }
    }

    fn of_path(&self, path: &str) -> Vec<Neighbour<'a>> {
        self.by_path
            .iter()
            .find(|(known, _)| *known == path)
            .map(|(_, neighbours)| neighbours.clone())
            .unwrap_or_default()
    }

    /// Every bound anchor's own binding this document's neighbours reach,
    /// folded into one string for the cache key. `None` where none of this
    /// document's edges bind to an anchor, so a document with no such edge
    /// costs the key nothing new.
    fn anchor_resolution_of_path(&self, path: &str) -> Option<&str> {
        self.anchor_resolutions_by_path
            .iter()
            .find(|(known, _)| *known == path)
            .map(|(_, resolution)| resolution.as_str())
    }
}