plates-render 0.7.3

The document-to-HTML half of plates: what a published page looks like.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
//! Server-side site reconstruction and rendering (ARK Layer 3, Phase 2).
//!
//! Rebuilds [`PublishedPage`]s from stored **sources** and renders the whole
//! site, mirroring the publish plugin's page-derivation rules so the server can
//! render-on-write. The stored sources are already audience-scoped and
//! visibility-filtered (Layer 2), but pre-template — so the per-page pipeline
//! here is: parse → template → preprocess → render → transform_links → page
//! assembly. Gated behind the `templating` feature.
//!
//! Each source is parsed in its own grammar, which [`crate::body`] reads off the
//! path's extension. A site is not required to be all one format.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};

use crate::frontmatter;
use indexmap::IndexMap;
use prov::ContentFormat;
use prov::Value as YamlValue;
use prov::views::{Row, Selection};
use serde_json::Value as JsonValue;

use crate::dates;

use crate::html::{HtmlRenderer, PageContext, SiteStyle};
use crate::nav::{build_site_nav_tree, forest_roots, nav_for_page, neighbours, reading_order};
use crate::shell::ShellTemplate;
use crate::types::{
    Heading, LinkEdge, NavLink, OutlineNode, PageLayout, PublishedPage, SiteNavNode,
};
// Where it was declared until 0.5.0. It lives in `types` now so that a caller
// that only *assembles* a header or footer — `plates::theme` — does not have
// to enable `templating` to name the type; the path here still resolves.
pub use crate::types::FrameDoc;
use crate::{body, links, page, template};

/// A stored source document to render.
pub struct SourceDoc {
    /// Canonical workspace-relative path including its extension, e.g.
    /// `"subdir/child.md"`. No leading slash. The extension is what decides the
    /// body's grammar, so it is load-bearing rather than decorative.
    pub path: String,
    /// The raw source (frontmatter + visibility-filtered, pre-template body), as
    /// stored by Layer 2.
    pub markdown: String,
    /// Whether this is the workspace root/index page (renders to `index.html`).
    pub is_root: bool,
    /// The documents that link *to* this one, each carrying the relation it is
    /// written in — `None` for a link written in prose.
    ///
    /// Supplied rather than derived, and not because it would be inconvenient:
    /// finding them means reading every document in the archive, and this crate
    /// reads nothing. The caller inverts the archive's links and hands over the
    /// answer in this render's coordinates.
    ///
    /// It is also where the disclosure lives. A path here becomes a titled link
    /// on the target's page, so a caller must pass **only sources this same
    /// site admits** — a document the gate held back must not be named by the
    /// page it happens to link to. A name this render does not recognize is
    /// dropped rather than published as a dead link, which makes the filter
    /// belt-and-braces rather than the whole guarantee; the guarantee is the
    /// caller's.
    ///
    /// A template reads this twice over: grouped by relation as `inbound`, and
    /// flattened to one entry per document as `backlinks`.
    ///
    /// Empty is the honest answer for a caller that computes none.
    pub inbound: Vec<LinkEdge>,
    /// The relation edges this document *writes*, on exactly
    /// [`inbound`](Self::inbound)'s terms — same coordinates, same obligation on
    /// the caller to have narrowed both ends to this site.
    ///
    /// Prose links out are absent by design rather than by omission: they carry
    /// no relation to group under, and the only key that publishes an unnamed
    /// link is the inbound `backlinks`. A template reads this as `relations`.
    pub outbound: Vec<LinkEdge>,
}

/// A fully rendered page: its output filename, HTML, and source identifier.
pub struct RenderedPage {
    /// Destination filename, e.g. `"index.html"` or `"subdir/child.html"`.
    pub dest_filename: String,
    /// The complete HTML document.
    pub html: String,
    /// The source document's identifier (frontmatter `id`), if it has one.
    pub id: Option<String>,
    /// Stylesheets the page links (frontmatter `styles`), as paths below the
    /// site root. The rendered HTML already points at them; **copying the files
    /// there is the caller's**, exactly as it is for `attachments`.
    pub styles: Vec<String>,
    /// Scripts the page loads (frontmatter `scripts`), on the same terms as
    /// [`styles`](Self::styles).
    pub scripts: Vec<String>,
}

pub use crate::types::{Arrangement, Grain, Grouping, serve_at_dest};

/// Options controlling a site render.
pub struct SiteOptions {
    /// Target audience (used for template `viewer_audience` variables).
    ///
    /// The *gate*, not the site's name: a site's public path segment is its own
    /// (`exports.<name>`), deliberately separate so an audience named to be
    /// precise about who is reading never becomes a URL. This field feeds the
    /// body templating only.
    pub audience: Option<String>,
    /// Site title override; defaults to the root page's title.
    pub site_title: Option<String>,
    /// Every file the site ships beside its pages — attachments, on the
    /// terms [`SourceDoc::path`] is spelled: site-relative, forward slashes.
    /// With it, a page's reference to a file the site does *not* ship is
    /// marked the way its link to a page the site does not publish is
    /// (`<span class="unpublished-link">`), instead of pointing at nothing:
    /// a picture whose sidecar says it is for someone else. `None` is a
    /// caller that cannot say, and leaves every file reference as written.
    pub published_files: Option<HashSet<String>>,
    /// Base URL for sitemap/canonical/feeds; when empty those are skipped.
    pub base_url: Option<String>,
    /// Generate SEO meta + sitemap/robots.
    pub generate_seo: bool,
    /// Generate Atom/RSS feeds + feed `<link>` tags. Both together, and only
    /// with a `base_url`: a feed needs absolute URLs, so without one there is
    /// no feed to advertise either.
    pub generate_feeds: bool,
    /// Caller-supplied appearance (theme/custom CSS/custom favicon).
    pub style: SiteStyle,
    /// How the site is arranged, from its declared view.
    pub arrangement: Arrangement,
    /// The archive's **spanning outline**, materialized by the caller: which
    /// document contains which, in declaration order, as a forest of
    /// [`OutlineNode`]s whose paths are spelled the way [`SourceDoc::path`] is.
    ///
    /// This is where a site's hierarchy comes from. A vault names the relation
    /// that contains (prov's `spanning:`), so re-deriving containment from
    /// `contents:`/`part_of:` here would hardcode one vault dialect's spelling
    /// of it and give every other vault the wrong nav. This crate reads no
    /// configuration, so the layer that holds the workspace walks the relation —
    /// `plates::collect_site` does it, and puts the result on
    /// `plates::CollectedSite::outline`.
    ///
    /// Empty falls the nav back to each page's own resolved
    /// `contents`/`part_of` links, which is what every site published before
    /// this existed got. Nodes naming documents this site does not publish are
    /// pruned; their published descendants hoist. See [`crate::nav`].
    pub outline: Vec<OutlineNode>,
    /// The site's shell template, as the text of the template file.
    ///
    /// A string rather than a path because this crate reads nothing: it is
    /// `wasm32-unknown-unknown`-portable, so a caller with a template on disk
    /// loads it and passes it in. `None` uses the built-in shell, which is what
    /// every site published before templates existed gets — byte for byte.
    ///
    /// The template is the whole document, `<!DOCTYPE html>` to `</html>`, with
    /// named slots for the parts a render computes. `{{name}}` inserts a text
    /// slot HTML-escaped; `{{{name}}}` inserts a raw HTML slot verbatim; each
    /// slot is one kind and writing it the other way is an error rather than a
    /// page full of `&lt;div&gt;`.
    ///
    /// | Slot | Kind | What it holds |
    /// |---|---|---|
    /// | `lang` | text | [`SiteOptions::lang`], for `<html lang="…">` |
    /// | `document_title` | text | `"Entry - Site"`, or the site's name on the front page |
    /// | `site_title` | text | the site's name on its own |
    /// | `body_class` | text | `has-site-nav`, or empty — write it inside `class="…"` |
    /// | `root_prefix` | text | `../` per level of depth, for a template's own link to `index.html` or `style.css` |
    /// | `head` | raw | stylesheet, favicon, SEO meta, feed links, the page's `styles:` |
    /// | `site_nav` | raw | the masthead and the navigation sidebar, empty when the site has no tree |
    /// | `breadcrumbs` | raw | the breadcrumb trail |
    /// | `toc` | raw | the page's outline ("On this page"), or empty |
    /// | `site_header` | raw | the site's [`header`](Self::header), rendered for this page |
    /// | `content` | raw | the rendered body, links already rewritten |
    /// | `pager` | raw | links to the previous and next page in reading order |
    /// | `site_footer` | raw | the site's [`footer`](Self::footer), rendered for this page |
    /// | `footer` | raw | the built-in attribution footer |
    /// | `scripts` | raw | the built-in interactivity script, then the page's `scripts:` |
    ///
    /// `<title>` is not part of `head`, so a template decides where its own
    /// title tag goes. A page whose frontmatter says `layout: bare` or
    /// `layout: verbatim` ignores the template entirely — both are statements
    /// that the page carries its own frame. See [`PageLayout`].
    ///
    /// A template that will not compile does not fail the render: the site is
    /// published in the built-in shell and the reason is reported on
    /// [`SiteRender::template_error`], because a broken theme should cost a
    /// site its styling rather than its publication.
    pub template: Option<String>,
    /// Shell templates a *page* may name, keyed by the vault-relative path it
    /// names them by — the text of each file, for the same reason
    /// [`template`](Self::template) is text.
    ///
    /// A page whose frontmatter says `shell: .config/sites/blog/poster.html` is
    /// wrapped in the entry under that key instead of the site's own shell. A
    /// key this map does not hold, or a template that will not compile, falls
    /// back to the site shell and is reported on
    /// [`SiteRender::page_shell_errors`] — the same bargain a broken site
    /// template gets, for the same reason. `bare` and `verbatim` pages take no
    /// shell at all, so a `shell:` on one of them is nothing to apply.
    pub templates: IndexMap<String, String>,
    /// BCP 47 language tag for every page's `<html lang="…">`. `"en"` unless
    /// the caller knows better; a vault written in another language should say
    /// so, since this is what a screen reader picks a voice from.
    pub lang: String,
    /// The caller is supplying `index.html` itself, so do not synthesize one.
    ///
    /// A site fronted by a manifest node (`plates::IndexDirectory`)
    /// serves an authored page copied verbatim, which never passes through this
    /// crate — so from here the render set simply has no root, which is
    /// otherwise precisely the signal that a front page must be generated.
    /// Without this flag the synthesized listing is written over the authored
    /// page, in the build directory and in the published namespace alike, and
    /// the site loses the front door it was fronted with.
    ///
    /// It does not make the nav, the feeds or the sitemap pretend a root exists.
    /// A supplied front page is outside this crate's knowledge — it contributes
    /// no title, no description, no nav entry and no sitemap row, exactly as a
    /// page nobody rendered should. An authored landing page carries its own
    /// `<title>` and meta tags; that is what fronting a site with one is for.
    pub front_page_supplied: bool,
    /// Grammars for highlighting code beyond the built-in set, keyed by the
    /// path the declaration named them by — the **text** of each
    /// `.sublime-syntax` file, for the reason [`template`](Self::template) is
    /// text.
    ///
    /// The built-in set is `two-face`'s 213 grammars, which is already most
    /// languages anyone fences a block in. This is for the rest: an in-house
    /// language, a config dialect, a notation a vault invented. A key here
    /// whose grammar declares `file_extensions: [wat]` is what makes
    /// ```` ```wat ```` colour.
    ///
    /// Assembled once for the whole site. A grammar that will not parse is
    /// reported on [`SiteRender::syntax_errors`] and skipped, never fatal —
    /// the bargain a broken shell template gets, for the same reason.
    ///
    /// Ignored entirely without the `syntax-highlighting` feature, where no
    /// block is coloured and there is nothing for a grammar to do.
    pub syntaxes: IndexMap<String, String>,
    /// The site's header: a document rendered above every page's content,
    /// into the `site_header` shell slot. `None` writes an empty slot.
    ///
    /// A *document* — Markdown, Djot or HTML, read off its path's extension —
    /// rather than a shell partial, because a document already has everything
    /// a frame needs: the template vocabulary, so it can name the site, the
    /// page and the entries; `:vis`, so one footer can carry a line only one
    /// audience sees; and links that are rewritten like any body's, so
    /// `[About](/about.md)` works from a page at any depth. It is rendered
    /// **per page**, against that page's context, and its own metadata block
    /// is stripped and otherwise unread. It is not an entry: it never
    /// publishes as a page, never appears in the nav, and the caller that
    /// plans the site is expected to keep it out of the render set.
    ///
    /// The text, for the reason [`template`](Self::template) is text.
    pub header: Option<FrameDoc>,
    /// The site's footer, on exactly [`header`](Self::header)'s terms, into
    /// the `site_footer` slot. The built-in shell writes it before the
    /// attribution `footer` slot inside one `<footer>`.
    pub footer: Option<FrameDoc>,
}

impl Default for SiteOptions {
    fn default() -> Self {
        Self {
            audience: None,
            site_title: None,
            published_files: None,
            base_url: None,
            generate_seo: true,
            generate_feeds: true,
            style: SiteStyle::default(),
            arrangement: Arrangement::default(),
            outline: Vec::new(),
            template: None,
            templates: IndexMap::new(),
            lang: DEFAULT_LANG.to_string(),
            front_page_supplied: false,
            syntaxes: IndexMap::new(),
            header: None,
            footer: None,
        }
    }
}

/// The grammar set one render uses, and whether it had to be built.
///
/// The overwhelmingly common case is a site with no grammars of its own, which
/// should cost nothing: that arm borrows the process-wide bundle rather than
/// unpacking a second copy of a megabyte of dumps.
#[cfg(feature = "syntax-highlighting")]
enum ResolvedSyntaxes {
    Bundled,
    Custom(crate::syntax::Syntaxes),
}

#[cfg(feature = "syntax-highlighting")]
impl ResolvedSyntaxes {
    fn get(&self) -> &crate::syntax::Syntaxes {
        match self {
            Self::Bundled => crate::syntax::Syntaxes::bundled(),
            Self::Custom(set) => set,
        }
    }

    fn warnings(&self) -> &[String] {
        self.get().warnings()
    }
}

/// Assemble the grammars for one render — **once**, because unpacking the
/// dumps costs far more than using them and a site that did it per page would
/// pay that for every document it publishes.
#[cfg(feature = "syntax-highlighting")]
fn resolve_syntaxes(opts: &SiteOptions) -> ResolvedSyntaxes {
    if opts.syntaxes.is_empty() {
        return ResolvedSyntaxes::Bundled;
    }
    ResolvedSyntaxes::Custom(crate::syntax::Syntaxes::with_custom(
        opts.syntaxes
            .iter()
            .map(|(path, text)| (path.as_str(), text.as_str())),
    ))
}

/// The language a site is assumed to be in when its caller does not say.
const DEFAULT_LANG: &str = "en";

/// The result of rendering a site: the pages plus the static/supplementary
/// assets (`style.css`, favicon, `sitemap.xml`, `robots.txt`, feeds).
pub struct SiteRender {
    /// Rendered pages.
    pub pages: Vec<RenderedPage>,
    /// `(filename, bytes)` assets to write alongside the pages.
    pub assets: Vec<(String, Vec<u8>)>,
    /// Why [`SiteOptions::template`] was ignored, when it was.
    ///
    /// A render has no error channel — every page in `pages` is real HTML — so a
    /// template that will not compile falls back to the built-in shell and says
    /// so here. A caller that can report it should: silently serving the wrong
    /// design is how a broken theme survives a release.
    pub template_error: Option<String>,
    /// Why a page's own `shell:` was ignored, once per shell rather than once
    /// per page that named it.
    ///
    /// Separate from [`template_error`](Self::template_error) because the two
    /// are different failures with different fixes: that one is the site's
    /// shell, this one is a page naming a template the site does not carry or
    /// cannot compile. Both fall back to a shell that works, and both are the
    /// caller's to report.
    pub page_shell_errors: Vec<String>,
    /// Why a grammar in [`SiteOptions::syntaxes`] was ignored, once per
    /// grammar.
    ///
    /// A `.sublime-syntax` that will not parse costs the languages it covered
    /// their colour and nothing else — every other block still highlights, and
    /// the site still publishes. Empty without the `syntax-highlighting`
    /// feature, where no grammar is consulted in the first place.
    pub syntax_errors: Vec<String>,
    /// What went wrong in a page's **body** template, named by the page.
    ///
    /// A body whose template will not expand publishes its own source, which
    /// used to happen with nothing reported at all — the failure this crate
    /// spent [`template_error`](Self::template_error) and
    /// [`page_shell_errors`](Self::page_shell_errors) refusing to allow for a
    /// *shell*, arriving through the one surface that had no channel for it.
    /// It carries the `{{ }}` migration's warnings too, which are not failures:
    /// a brace outside a link destination is no longer a template, and the page
    /// publishes it as the text it is.
    pub body_template_errors: Vec<String>,
}

/// Reconstruct [`PublishedPage`]s from stored sources, fully rendering each
/// page's `rendered_body` (template → preprocess → comrak → link rewrite).
///
/// The returned set does **not** include a synthesized index; that is
/// [`synthesize_index`]'s job, applied by [`render_site`] when no source claims
/// `is_root`.
/// The returned set also drops whatever the body templates had to say. A
/// caller that wants those calls [`render_site`], which carries them in
/// [`SiteRender::body_template_errors`]; this entry point has no error channel
/// and adding one to its return type would change what a page *is*.
pub fn build_pages(sources: &[SourceDoc], opts: &SiteOptions) -> Vec<PublishedPage> {
    #[cfg(feature = "syntax-highlighting")]
    let syntaxes = resolve_syntaxes(opts);
    let (mut pages, mut prepared) = prepare(sources, opts);
    // No front page is synthesized here, so the reading order is the forest's
    // own; `render_site` hangs it under the index first.
    let tree = build_site_nav_tree(&pages, &opts.outline);
    render_bodies(
        &mut pages,
        0,
        sources,
        opts,
        &mut prepared,
        &tree,
        #[cfg(feature = "syntax-highlighting")]
        syntaxes.get(),
        &mut Vec::new(),
    );
    pages
}

/// Everything a render has in hand before the first body is rendered.
///
/// Two phases rather than one, because a body's template can name what the
/// site *is* — the entries, the page after this one — and the site is not
/// known until every source's metadata has been read. So the metadata is read
/// first, into a [`PublishedPage`] with an empty body, and the bodies are
/// rendered against the whole.
struct Prepared {
    /// Sanitized source path → destination, for link rewriting and for
    /// resolving a `contents:`/`part_of:` entry.
    path_to_filename: HashMap<PathBuf, String>,
    /// The template context's site-level half and per-path lookups.
    collected: Collected,
    /// Each source's metadata block and body, parsed once; parallel to the
    /// sources.
    parsed: Vec<frontmatter::ParsedFile>,
    /// Each source page's own half of the template context, parallel to the
    /// sources. Filled by [`render_bodies`], which is where `headings` and
    /// the page's neighbours join it, and read again by whatever renders
    /// *against* the page afterwards — the site's header and footer.
    values: Vec<serde_json::Map<String, JsonValue>>,
}

/// Read every source's metadata into a page with no body yet, and assemble
/// what the bodies will be rendered against.
fn prepare(sources: &[SourceDoc], opts: &SiteOptions) -> (Vec<PublishedPage>, Prepared) {
    // Map sanitized canonical `.md` path → output `.html` filename (root →
    // index.html, a `serve_at:` claim to what it claims). Sources are keyed by
    // their workspace-relative path; we sanitize keys so that frontmatter links
    // (which may carry unsanitized characters) resolve against them.
    //
    // …and, from the same parse, the frontmatter title (for contents/parent
    // titles). One pass because both answers come out of one metadata block,
    // and parsing the corpus twice to ask it two questions is a parse per
    // document nobody needs.
    //
    // …and the resolver a `contents:`/`part_of:` entry is read through, fed
    // from the same block: the `id` a page carries and the names it answers
    // to. See [`Resolver`].
    let mut path_to_filename: HashMap<PathBuf, String> = HashMap::new();
    let mut title_map: HashMap<PathBuf, String> = HashMap::new();
    let mut resolver = Resolver::new();
    let mut parsed = Vec::with_capacity(sources.len());
    for s in sources {
        let key = PathBuf::from(links::sanitize_rel_path(&s.path));
        let file = frontmatter::parse_or_empty(&s.markdown).unwrap_or(frontmatter::ParsedFile {
            frontmatter: IndexMap::new(),
            body: s.markdown.clone(),
        });
        if let Some(t) = frontmatter::get_string(&file.frontmatter, "title") {
            title_map.insert(key.clone(), t.to_string());
        }
        resolver.learn(&key, &file.frontmatter);
        path_to_filename.insert(key, dest_for(&s.path, s.is_root, &file.frontmatter));
        parsed.push(file);
    }

    // The collection context, from the same sources and therefore from the
    // same gate: `build_pages` is handed the audience-admitted set, so a
    // template cannot name a withheld document because the data holding it was
    // never assembled. That is a property of *where* this is built, which is
    // why `a_template_cannot_reach_a_withheld_document` tests the shape of the
    // pipeline rather than a check inside it.
    let collected = collect_context(sources, opts, &path_to_filename, &resolver);

    let pages = sources
        .iter()
        .zip(&parsed)
        .map(|(s, file)| page_skeleton(s, file, opts, &path_to_filename, &title_map, &resolver))
        .collect();

    (
        pages,
        Prepared {
            path_to_filename,
            collected,
            parsed,
            values: Vec::new(),
        },
    )
}

/// Render every source's body into its page.
///
/// `pages` is the whole site — `sources` plus, at index `0` when `offset` is
/// `1`, the front page [`render_site`] synthesized — and `tree` is the nav
/// built over it, which is where a page's neighbours in reading order come
/// from. A synthesized front page has no source and its body is already HTML,
/// so it is skipped here.
#[allow(clippy::too_many_arguments)]
fn render_bodies(
    pages: &mut [PublishedPage],
    offset: usize,
    sources: &[SourceDoc],
    opts: &SiteOptions,
    prepared: &mut Prepared,
    tree: &[SiteNavNode],
    #[cfg(feature = "syntax-highlighting")] syntaxes: &crate::syntax::Syntaxes,
    reports: &mut Vec<String>,
) {
    let order = reading_order(tree);
    for (i, s) in sources.iter().enumerate() {
        let page = &mut pages[i + offset];
        let (prev, next) = neighbours(&order, &page.dest_filename);
        let values = render_body(
            page,
            s,
            &prepared.parsed[i],
            opts,
            &prepared.path_to_filename,
            &prepared.collected,
            (prev, next),
            #[cfg(feature = "syntax-highlighting")]
            syntaxes,
            reports,
        );
        prepared.values.push(values);
    }
}

// ── The template context ────────────────────────────────────────────────────

/// The site-level context, plus the two per-path lookups a page's own half of
/// it is assembled from.
struct Collected {
    /// `site`, `entries` and `groups` — one copy for the whole render, borrowed
    /// by every page rather than cloned into each.
    context: template::SiteContext,
    /// The entry record for each source, keyed by its sanitized path. This is
    /// what a page names as `page`, and what a breadcrumb trail is made of.
    by_path: HashMap<PathBuf, JsonValue>,
    /// The same records keyed by the href each publishes at — the coordinate a
    /// resolved `contents:`/`part_of:` link carries, so `children` and
    /// `parent` can be entries without a walk over every record per child.
    by_href: HashMap<String, PathBuf>,
    /// Each source's container, for walking a trail back to the root.
    parent_of: HashMap<PathBuf, PathBuf>,
    /// Each source's contained pages, when the caller supplied the archive's
    /// [outline](SiteOptions::outline): the spine the *vault* declares, pruned
    /// to what this site publishes by [`crate::nav::pruned_edges`] — the same edges the
    /// nav tree is built from.
    ///
    /// `None` is the fallback, where a page's own `contents:`/`part_of:` is the
    /// only answer available.
    spine: Option<HashMap<PathBuf, Vec<PathBuf>>>,
    /// The entry records of the documents linking *to* each source, keyed the
    /// same way. Resolved against `by_path`, so a name no page in this render
    /// answers to is already gone.
    ///
    /// The flat union — a typed relation and a sentence of prose are one
    /// inbound reference here — which is what `backlinks` has always meant and
    /// goes on meaning.
    backlinks: HashMap<PathBuf, Vec<JsonValue>>,
    /// The same inbound edges filed under the relation that carries each one:
    /// per source, a mapping of relation name to entry records. Prose links are
    /// absent, having no name to file under.
    inbound: HashMap<PathBuf, JsonValue>,
    /// The relation edges each source *writes*, filed the same way.
    relations: HashMap<PathBuf, JsonValue>,
    /// Entry records in the site's order, so a breadcrumb walk and `entries`
    /// agree about what an entry is.
    order: Vec<PathBuf>,
}

/// Assemble everything a template can name, from frontmatter alone.
///
/// Frontmatter alone is the point: an entry record needs a title, a href, a
/// date and its group keys, and every one of those is metadata. Nothing here
/// renders a body, so the context is available *before* the first page is
/// built — which is what breaks the circularity of a page whose template lists
/// the pages.
fn collect_context(
    sources: &[SourceDoc],
    opts: &SiteOptions,
    path_to_filename: &HashMap<PathBuf, String>,
    resolver: &Resolver,
) -> Collected {
    let mut by_path: HashMap<PathBuf, JsonValue> = HashMap::new();
    let mut parent_of: HashMap<PathBuf, PathBuf> = HashMap::new();
    let mut sortable: Vec<(i32, PathBuf)> = Vec::new();
    let mut root_title: Option<String> = None;
    // Kept whole rather than reduced to group keys here, because prov's grouper
    // takes metadata and answers the grouping question itself — see
    // [`groups_of`].
    let mut meta_of: HashMap<PathBuf, YamlValue> = HashMap::new();

    for (idx, s) in sources.iter().enumerate() {
        let key = PathBuf::from(links::sanitize_rel_path(&s.path));
        let fm = frontmatter::parse_or_empty(&s.markdown)
            .map(|parsed| parsed.frontmatter)
            .unwrap_or_default();

        let title = frontmatter::get_string(&fm, "title")
            .map(String::from)
            .unwrap_or_else(|| filename_to_title(&s.path));
        if s.is_root {
            root_title = Some(title.clone());
        }

        let date = frontmatter::get_string(&fm, "date_of_document")
            .or_else(|| frontmatter::get_string(&fm, "created"))
            .or_else(|| frontmatter::get_string(&fm, "updated"))
            .filter(|d| !d.is_empty())
            .map(String::from);
        let group_keys = match &opts.arrangement {
            Arrangement::Containment => Vec::new(),
            Arrangement::Grouped(grouping) => grouping.keys_of(&YamlValue::Mapping(fm.clone())),
        };

        // …unless the caller walked the archive's own spanning relation, which
        // is a better answer to the same question and is applied below.
        if opts.outline.is_empty()
            && let Some(parent) = frontmatter::get_string(&fm, "part_of")
            && let Some(parent) = resolver.key(Path::new(&s.path), parent)
        {
            parent_of.insert(key.clone(), parent);
        }

        let href = path_to_filename
            .get(&key)
            .cloned()
            .unwrap_or_else(|| dest_for(&s.path, s.is_root, &fm));

        by_path.insert(
            key.clone(),
            entry_value(&s.path, &title, &href, date, &fm, group_keys, s.is_root),
        );
        meta_of.insert(key.clone(), YamlValue::Mapping(fm.clone()));

        // Source order, `nav_order` overriding — the rule `crate::nav` sorts
        // siblings by, restated here so a template listing entries and a nav
        // listing them cannot disagree.
        let order_key = fm
            .get("nav_order")
            .and_then(|v| match v {
                YamlValue::Int(i) => Some(*i as i32),
                YamlValue::Float(f) => Some(*f as i32),
                YamlValue::String(st) => st.parse::<i32>().ok(),
                _ => None,
            })
            .unwrap_or(idx as i32);
        sortable.push((order_key, key));
    }

    // The archive's spine, in place of the `part_of` read above. A vault *names*
    // the relation that contains (prov's `spanning:`), so a context assembled
    // from one dialect's spelling of it would give a template a `parent` and a
    // trail that contradict the nav rendered beside them. Pruned by `nav`, from
    // the same edges the nav tree is built out of.
    let spine = (!opts.outline.is_empty()).then(|| {
        let mut spine: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
        for edge in
            crate::nav::pruned_edges(&opts.outline, &|path| by_path.contains_key(Path::new(path)))
        {
            let (container, contained) =
                (PathBuf::from(edge.container), PathBuf::from(edge.contained));
            spine
                .entry(container.clone())
                .or_default()
                .push(contained.clone());
            parent_of.entry(contained).or_insert(container);
        }
        spine
    });

    sortable.sort_by_key(|(k, _)| *k);
    let order: Vec<PathBuf> = sortable.into_iter().map(|(_, key)| key).collect();
    let entries: Vec<JsonValue> = order
        .iter()
        .filter_map(|key| by_path.get(key).cloned())
        .collect();

    // After the loop, because a linked document is an *entry* and the entries do
    // not all exist until the loop has run — a document is routinely linked to
    // by one that comes after it.
    let mut backlinks = HashMap::new();
    let mut inbound = HashMap::new();
    let mut relations = HashMap::new();
    for s in sources {
        let key = PathBuf::from(links::sanitize_rel_path(&s.path));
        backlinks.insert(
            key.clone(),
            entry_records(s.inbound.iter().map(|e| e.path.as_str()), &by_path),
        );
        inbound.insert(key.clone(), edges_by_relation(&s.inbound, &by_path));
        relations.insert(key, edges_by_relation(&s.outbound, &by_path));
    }

    let site = serde_json::json!({
        "title": opts
            .site_title
            .clone()
            .or(root_title)
            .unwrap_or_else(|| DEFAULT_SITE_TITLE.to_string()),
        "lang": opts.lang.clone(),
        "base_url": opts.base_url.clone().unwrap_or_default(),
    });

    let by_href = by_path
        .iter()
        .filter_map(|(path, entry)| Some((entry.get("href")?.as_str()?.to_string(), path.clone())))
        .collect();

    Collected {
        context: template::SiteContext::new(
            site,
            entries.clone(),
            groups_of(&order, &meta_of, &by_path, &opts.arrangement),
        ),
        by_path,
        by_href,
        parent_of,
        spine,
        order,
        backlinks,
        inbound,
        relations,
    }
}

/// The entry records a set of linked paths names.
///
/// Sorted by path and deduplicated here rather than trusted from the caller,
/// because a rendered page is a build artifact and two builds of one archive
/// have to be the same bytes. The caller counts *link sites* — a document
/// linking here from both its frontmatter and its prose is two backlinks — and
/// a reader wants the document once.
///
/// A name `by_path` does not answer to is dropped, on the rule
/// `resolve_link` already follows for a `contents:` entry: a link this render
/// cannot address is a 404 waiting to be published.
fn entry_records<'a>(
    paths: impl IntoIterator<Item = &'a str>,
    by_path: &HashMap<PathBuf, JsonValue>,
) -> Vec<JsonValue> {
    let mut keys: Vec<PathBuf> = paths
        .into_iter()
        .map(|path| PathBuf::from(links::sanitize_rel_path(path)))
        .collect();
    keys.sort();
    keys.dedup();
    keys.iter()
        .filter_map(|key| by_path.get(key).cloned())
        .collect()
}

/// Edges filed under the relation each is written in: a mapping of name to
/// entry records, which is what makes `inbound.sequel.0.title` an address.
///
/// **The names are the vault's.** Whatever relations the archive declares are
/// the keys, and no vocabulary is assumed — including the relation the site's
/// own navigation is built from, which appears here like any other because it
/// is one.
///
/// An unnamed edge — a link written in prose — is dropped rather than gathered
/// under a reserved key: `body` is a name a vault may legitimately give a
/// relation, and the flat `backlinks` already carries those links.
///
/// A relation whose every target this render cannot answer for produces **no
/// key at all**, rather than an empty list. The list would render as nothing
/// either way; the key would still be a statement that the edge exists, which is
/// the one thing a filtered edge must not say.
fn edges_by_relation(edges: &[LinkEdge], by_path: &HashMap<PathBuf, JsonValue>) -> JsonValue {
    let mut by_relation: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for edge in edges {
        let Some(relation) = edge.relation.as_deref() else {
            continue;
        };
        by_relation
            .entry(relation)
            .or_default()
            .push(edge.path.as_str());
    }
    let mut out = serde_json::Map::new();
    for (relation, paths) in by_relation {
        let records = entry_records(paths, by_path);
        if !records.is_empty() {
            out.insert(relation.to_string(), JsonValue::Array(records));
        }
    }
    JsonValue::Object(out)
}

/// One entry, as a template names it.
///
/// `date_year` and `date_month` are here rather than in a filter syntax on
/// purpose: a filter language is the thing that turns a template format into a
/// template *engine*, and this crate already knows how to read a date. A field
/// that turns out to be wanted is one line; a filter grammar is permanent.
///
/// `color` is such a line. It is the word a document names its colour with —
/// `color: green` — read as written, so a listing can dress each entry in the
/// tone its author chose (`class="cover tone-{{book.color}}"`); which tones
/// exist and what they look like is the stylesheet's to say.
fn entry_value(
    path: &str,
    title: &str,
    href: &str,
    date: Option<String>,
    fm: &IndexMap<String, YamlValue>,
    group_keys: Vec<String>,
    is_root: bool,
) -> JsonValue {
    let normalized = date.as_deref().and_then(dates::to_rfc3339);
    serde_json::json!({
        "path": path,
        "title": title,
        "href": href,
        "date": date,
        "date_year": normalized.as_deref().and_then(|d| d.get(0..4)),
        "date_month": normalized.as_deref().and_then(|d| d.get(0..7)),
        "id": frontmatter::get_string(fm, "id"),
        "description": frontmatter::get_string(fm, "description"),
        "color": frontmatter::get_string(fm, "color"),
        "group_keys": group_keys,
        "is_root": is_root,
    })
}

/// Gather entries into `{key, entries}` records, ascending by group key.
///
/// The buckets and their order are prov's, not this crate's: a published site
/// and the picker over the archive it came from must file a letter about two
/// people under both their names, and in the same order, or the site reads
/// differently from the vault. That is the same reasoning that made
/// [`Grouping`] prov's rather than a copy of it, applied one layer further out
/// — the grouper is pure, so it costs this crate none of its portability.
///
/// Empty when the arrangement is containment, because then nothing is grouped —
/// which is also the honest answer for `:::group` on an ungrouped site: no
/// groups, so no repetitions.
///
/// prov's `ungrouped` bucket is deliberately dropped rather than appended as a
/// group of its own: an entry no field gave a key for belongs under no heading,
/// and `entries` already lists every one of them for a template that wants the
/// flat set. The synthesized index keeps its own labelled bucket
/// ([`group_entries`]), which is a *nav* question and answered there.
fn groups_of(
    order: &[PathBuf],
    meta_of: &HashMap<PathBuf, YamlValue>,
    by_path: &HashMap<PathBuf, JsonValue>,
    arrangement: &Arrangement,
) -> Vec<JsonValue> {
    let Arrangement::Grouped(grouping) = arrangement else {
        return Vec::new();
    };
    // The view name is prov's handle for the selection and nothing here reads
    // it back; the arrangement arrives without one.
    let selection = Selection {
        view: String::new(),
        rows: order
            .iter()
            .filter_map(|key| {
                Some(Row {
                    path: key.clone(),
                    meta: meta_of.get(key)?.clone(),
                })
            })
            .collect(),
    };
    prov::views::group(&selection, grouping)
        .groups
        .into_iter()
        .map(|group| {
            let entries: Vec<JsonValue> = group
                .rows
                .iter()
                .filter_map(|row| by_path.get(&row.path).cloned())
                .collect();
            serde_json::json!({ "key": group.key, "entries": entries })
        })
        .collect()
}

/// This page's own half of the context: what it is, what it contains, what
/// contains it, and the trail from the root down to it.
fn page_context_values(
    s: &SourceDoc,
    fm: &IndexMap<String, YamlValue>,
    collected: &Collected,
    contents_links: &[NavLink],
    parent_link: Option<&NavLink>,
    audience: Option<&str>,
) -> serde_json::Map<String, JsonValue> {
    let viewer: Vec<&str> = audience.into_iter().collect();
    let mut values = template::page_values(fm, Path::new(&s.path), None, &viewer);
    let key = PathBuf::from(links::sanitize_rel_path(&s.path));

    if let Some(entry) = collected.by_path.get(&key) {
        values.insert("page".into(), entry.clone());
    }
    // What contains this page and what it contains, from the archive's spine
    // when the caller walked one and from the page's own links otherwise — the
    // same choice `crate::nav` makes, so a template's `parent` and the
    // breadcrumb printed above it can never name two different pages.
    //
    // Each is the *entry* — the record `entries` holds, colour and date and
    // all — rather than a link cut down to a title and an href. A link this
    // site does not publish was dropped when it was resolved, so every one
    // that reaches here has an entry to be.
    let (children, parent) = match &collected.spine {
        Some(spine) => (
            spine
                .get(&key)
                .into_iter()
                .flatten()
                .filter_map(|child| collected.by_path.get(child))
                .cloned()
                .collect(),
            collected
                .parent_of
                .get(&key)
                .and_then(|container| collected.by_path.get(container))
                .cloned()
                .unwrap_or(JsonValue::Null),
        ),
        None => (
            contents_links
                .iter()
                .map(|link| collected.entry_of(link))
                .collect::<Vec<_>>(),
            parent_link
                .map(|link| collected.entry_of(link))
                .unwrap_or(JsonValue::Null),
        ),
    };
    values.insert("children".into(), JsonValue::Array(children));
    values.insert("parent".into(), parent);
    values.insert(
        "breadcrumbs".into(),
        JsonValue::Array(breadcrumbs_of(&key, collected)),
    );
    // Always present, even empty: `:::each{of=backlinks}` over a page nobody
    // links to should produce nothing, not an error about a name the context
    // does not hold. The same for the two typed keys, whose relation names are
    // the vault's own — a template naming one this archive does not declare gets
    // an empty repetition rather than a failed publish.
    values.insert(
        "backlinks".into(),
        JsonValue::Array(collected.backlinks.get(&key).cloned().unwrap_or_default()),
    );
    let empty = || JsonValue::Object(serde_json::Map::new());
    values.insert(
        "relations".into(),
        collected.relations.get(&key).cloned().unwrap_or_else(empty),
    );
    values.insert(
        "inbound".into(),
        collected.inbound.get(&key).cloned().unwrap_or_else(empty),
    );
    values
}

impl Collected {
    /// The entry a resolved nav link names.
    ///
    /// Falls back to the link's own title and href — the shape `children` and
    /// `parent` used to hold — for a link whose target published under a
    /// coordinate no entry claims, which `resolve_link` already makes rare and
    /// this makes harmless: a template reading `.title` and `.href` off it is
    /// still answered.
    fn entry_of(&self, link: &NavLink) -> JsonValue {
        self.by_href
            .get(&link.href)
            .and_then(|path| self.by_path.get(path))
            .cloned()
            .unwrap_or_else(|| serde_json::json!({ "title": link.title, "href": link.href }))
    }
}

/// The trail from the site's root down to one page, itself included.
///
/// Walked over `part_of` rather than over the nav tree, because the nav tree is
/// built from rendered pages and this runs before any of them exist. The walk
/// is bounded by the number of entries and refuses to revisit a path, so a
/// vault whose `part_of` links form a cycle produces a short trail instead of
/// hanging a publish.
fn breadcrumbs_of(from: &Path, collected: &Collected) -> Vec<JsonValue> {
    let mut trail: Vec<JsonValue> = Vec::new();
    let mut seen: Vec<PathBuf> = Vec::new();
    let mut at = from.to_path_buf();
    for _ in 0..=collected.order.len() {
        if seen.contains(&at) {
            break;
        }
        let Some(entry) = collected.by_path.get(&at) else {
            break;
        };
        trail.push(entry.clone());
        seen.push(at.clone());
        let Some(parent) = collected.parent_of.get(&at) else {
            break;
        };
        at = parent.clone();
    }
    trail.reverse();
    trail
}

/// Reconstruct and render a whole site from stored sources.
///
/// When no source claims `is_root`, a front page is synthesized from the render
/// set (see [`synthesize_index`]). Under explicit-only audience visibility that
/// is the ordinary case, not a fallback: a vault's root document is private
/// unless its author tagged it, and promoting whichever entry happened to sort
/// first made the site's front page — and, through the publish layer, its ARK —
/// depend on traversal order.
pub fn render_site(sources: &[SourceDoc], opts: &SiteOptions) -> SiteRender {
    #[cfg(feature = "syntax-highlighting")]
    let syntaxes = resolve_syntaxes(opts);
    let mut body_template_errors = Vec::new();
    let (mut pages, mut prepared) = prepare(sources, opts);

    // Read the site's name off an **authored** root, before synthesis can add
    // one. A synthesized front page is named *after* the site, so asking it
    // what the site is called only ever returns the placeholder back — which is
    // how every page of a rootless site came to be titled "… - Index" and to
    // announce `og:site_name: Index` to every reader that scraped it.
    let site_title = opts
        .site_title
        .clone()
        .or_else(|| pages.iter().find(|p| p.is_root).map(|p| p.title.clone()))
        .unwrap_or_else(|| DEFAULT_SITE_TITLE.to_string());

    // Synthesized from metadata alone, which is all a front page lists — and
    // before the bodies, because the nav hangs the forest under it and the
    // bodies are rendered against that nav's reading order.
    let synthesized =
        !pages.iter().any(|p| p.is_root) && !pages.is_empty() && !opts.front_page_supplied;
    if synthesized {
        let index = synthesize_index(&pages, opts);
        pages.insert(0, index);
    }

    let renderer = HtmlRenderer::with_style(opts.style.clone());
    let nav_tree = build_site_nav_tree(&pages, &opts.outline);
    render_bodies(
        &mut pages,
        usize::from(synthesized),
        sources,
        opts,
        &mut prepared,
        &nav_tree,
        #[cfg(feature = "syntax-highlighting")]
        syntaxes.get(),
        &mut body_template_errors,
    );

    // Compiled once for the whole site, not once per page: a template's errors
    // are about the template, and reporting them per page would say the same
    // thing as many times as the vault has entries.
    let (template, template_error) = match opts.template.as_deref() {
        None => (None, None),
        Some(source) => match ShellTemplate::parse(source) {
            Ok(compiled) => (Some(compiled), None),
            Err(err) => (None, Some(err.to_string())),
        },
    };

    // Every shell a page named, compiled once per shell — not once per page
    // that named it. A poster template shared by forty entries is one template,
    // and a template that will not compile is one report.
    let mut page_shell_errors: Vec<String> = Vec::new();
    let mut page_templates: IndexMap<&str, Option<ShellTemplate>> = IndexMap::new();
    for p in &pages {
        let Some(key) = p.shell.as_deref() else {
            continue;
        };
        if page_templates.contains_key(key) {
            continue;
        }
        let compiled = match opts.templates.get(key) {
            None => {
                page_shell_errors.push(format!(
                    "{} asks for the shell {key:?}, which this site does not carry — \
                     it is rendered in the site's own shell",
                    p.source_path.display()
                ));
                None
            }
            Some(source) => match ShellTemplate::parse(source) {
                Ok(compiled) => Some(compiled),
                Err(err) => {
                    page_shell_errors.push(format!(
                        "the shell {key:?}, which {} asks for, will not compile ({err}) — \
                         it is rendered in the site's own shell",
                        p.source_path.display()
                    ));
                    None
                }
            },
        };
        page_templates.insert(key, compiled);
    }

    let base_url = opts.base_url.as_deref().unwrap_or("");
    let writes_feeds = opts.generate_feeds && !base_url.is_empty();

    let mut out_pages = Vec::with_capacity(pages.len());
    for (i, p) in pages.iter().enumerate() {
        let nav = nav_for_page(&nav_tree, &p.dest_filename, &pages);
        // The site's header and footer, rendered *for this page*: against its
        // context, at its depth. A synthesized front page has no context of
        // its own to render them against, so it takes them against the site's
        // alone.
        let values = i
            .checked_sub(usize::from(synthesized))
            .and_then(|source_index| prepared.values.get(source_index));
        let empty = serde_json::Map::new();
        let context = template::Context::new(&prepared.collected.context, values.unwrap_or(&empty));
        let mut frame = |doc: Option<&FrameDoc>, what: &str| {
            doc.map(|doc| {
                render_frame_doc(
                    doc,
                    what,
                    p,
                    context,
                    opts,
                    &prepared.path_to_filename,
                    #[cfg(feature = "syntax-highlighting")]
                    syntaxes.get(),
                    &mut body_template_errors,
                )
            })
            .unwrap_or_default()
        };
        let site_header = frame(opts.header.as_ref(), "header");
        let site_footer = frame(opts.footer.as_ref(), "footer");
        let seo = if opts.generate_seo {
            page::generate_seo_meta(p, &site_title, base_url)
        } else {
            String::new()
        };
        // Advertised on exactly the condition the files are written under
        // below. The tags used to hang off `generate_feeds` alone, so a render
        // with no base URL — every published site, since no client sent one —
        // put a `<link rel="alternate">` on every page pointing at a
        // `feed.xml` the same render had just decided to skip.
        let feeds = if writes_feeds {
            page::generate_feed_link_tags(&links::root_prefix(&p.dest_filename))
        } else {
            String::new()
        };
        // The page's own shell when it named one this render could compile,
        // and the site's otherwise — which is also what a page that named a
        // shell nobody could load falls back to.
        let shell = p
            .shell
            .as_deref()
            .and_then(|key| page_templates.get(key))
            .and_then(Option::as_ref)
            .or(template.as_ref());
        let html = renderer.render_page_in_site(
            p,
            &PageContext {
                site_title: &site_title,
                nav: &nav,
                seo_meta: &seo,
                feed_links: &feeds,
                // The page's own language when it declared one, and the site's
                // otherwise — the same shape as its own shell above, for the
                // same reason: what is true of one document is written in that
                // document.
                lang: p.lang.as_deref().unwrap_or(&opts.lang),
                template: shell,
                site_header: &site_header,
                site_footer: &site_footer,
            },
        );
        out_pages.push(RenderedPage {
            dest_filename: p.dest_filename.clone(),
            html,
            id: p.id.clone(),
            styles: p.styles.clone(),
            scripts: p.scripts.clone(),
        });
    }

    // Static assets (style.css + favicon) always; supplementary files need a base URL.
    let mut assets = renderer.static_assets();
    if !base_url.is_empty() {
        if opts.generate_seo {
            assets.push((
                "sitemap.xml".to_string(),
                page::generate_sitemap(&pages, base_url).into_bytes(),
            ));
            assets.push((
                "robots.txt".to_string(),
                page::generate_robots_txt(base_url, true).into_bytes(),
            ));
        }
        if writes_feeds {
            let root = pages.iter().find(|p| p.is_root);
            let desc = root.and_then(|r| r.description.as_deref()).unwrap_or("");
            let author = root.and_then(|r| r.author.as_deref()).unwrap_or("");
            assets.push((
                "feed.xml".to_string(),
                page::generate_atom_feed(&pages, &site_title, base_url, desc, author).into_bytes(),
            ));
            assets.push((
                "rss.xml".to_string(),
                page::generate_rss_feed(&pages, &site_title, base_url, desc, author).into_bytes(),
            ));
        }
    }

    SiteRender {
        pages: out_pages,
        assets,
        template_error,
        page_shell_errors,
        #[cfg(feature = "syntax-highlighting")]
        syntax_errors: syntaxes.warnings().to_vec(),
        #[cfg(not(feature = "syntax-highlighting"))]
        syntax_errors: Vec::new(),
        body_template_errors,
    }
}

// ── Per-page reconstruction ─────────────────────────────────────────────────

/// A page from its metadata alone: everything a [`PublishedPage`] carries
/// except its body, which [`render_body`] fills once the whole site is known.
fn page_skeleton(
    s: &SourceDoc,
    parsed: &frontmatter::ParsedFile,
    opts: &SiteOptions,
    path_to_filename: &HashMap<PathBuf, String>,
    title_map: &HashMap<PathBuf, String>,
    resolver: &Resolver,
) -> PublishedPage {
    let fm = &parsed.frontmatter;

    let current_path = PathBuf::from(&s.path);
    let dest_filename = path_to_filename
        .get(&PathBuf::from(links::sanitize_rel_path(&s.path)))
        .cloned()
        .unwrap_or_else(|| dest_for(&s.path, s.is_root, fm));

    let title = frontmatter::get_string(fm, "title")
        .map(String::from)
        .unwrap_or_else(|| {
            Path::new(&s.path)
                .file_stem()
                .and_then(|x| x.to_str())
                .unwrap_or("Untitled")
                .to_string()
        });

    // Resolve only against THIS audience's rendered set: a `contents`/`part_of`
    // link whose target was excluded for this audience is dropped, so it never
    // surfaces as a dead nav/breadcrumb entry that 404s. The render set is the
    // manifest — no separate per-audience list is needed.
    let contents_links: Vec<NavLink> = frontmatter::get_string_array(fm, "contents")
        .into_iter()
        .filter_map(|child| {
            resolve_link(&child, &current_path, path_to_filename, title_map, resolver)
        })
        .collect();

    let parent_link = frontmatter::get_string(fm, "part_of")
        .and_then(|p| resolve_link(p, &current_path, path_to_filename, title_map, resolver));

    let layout = PageLayout::parse(frontmatter::get_string(fm, "layout"));

    let nav_order = fm.get("nav_order").and_then(|v| match v {
        YamlValue::Int(i) => Some(*i as i32),
        YamlValue::Float(f) => Some(*f as i32),
        YamlValue::String(st) => st.parse::<i32>().ok(),
        _ => None,
    });

    let created = frontmatter::get_string(fm, "created").map(String::from);
    let updated = frontmatter::get_string(fm, "updated").map(String::from);
    let date_of_document = frontmatter::get_string(fm, "date_of_document").map(String::from);
    // One line, because the chain, the grain and the multi-valued case are all
    // the view spec's to answer now — including the two spellings a field
    // permits (`people: Grandpa` and `people: [Grandpa, Nan]`), which prov
    // reads the same way.
    let group_keys = match &opts.arrangement {
        Arrangement::Containment => Vec::new(),
        Arrangement::Grouped(grouping) => grouping.keys_of(&YamlValue::Mapping(fm.clone())),
    };

    let styles = resolve_asset_paths(fm, "styles", &current_path);
    let scripts = resolve_asset_paths(fm, "scripts", &current_path);

    PublishedPage {
        source_path: current_path,
        dest_filename,
        title,
        rendered_body: String::new(),
        markdown_body: String::new(),
        contents_links,
        parent_link,
        is_root: s.is_root,
        description: frontmatter::get_string(fm, "description").map(String::from),
        author: frontmatter::get_string(fm, "author").map(String::from),
        created,
        updated,
        date_of_document,
        group_keys,
        attachments: frontmatter::get_string_array(fm, "attachments"),
        styles,
        scripts,
        layout,
        // Only for a page that wears a shell at all: `bare` and `verbatim` are
        // statements that this page carries its own frame, and recording a
        // request they cannot act on would report a missing template for a page
        // that was never going to use one.
        shell: match layout {
            PageLayout::Site => frontmatter::get_string(fm, "shell")
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(String::from),
            PageLayout::Bare | PageLayout::Verbatim => None,
        },
        // Unlike `shell`, read for every layout that writes a document at all:
        // a `bare` page still gets an `<html lang>` from this crate, and the
        // language it is in is a fact about the document rather than a request
        // for a frame.
        lang: frontmatter::get_string(fm, "lang")
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .map(String::from),
        nav_title: frontmatter::get_string(fm, "nav_title").map(String::from),
        nav_order,
        hide_from_nav: fm
            .get("hide_from_nav")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        hide_from_feed: fm
            .get("hide_from_feed")
            .and_then(|v| v.as_bool())
            .unwrap_or(false),
        id: frontmatter::get_string(fm, "id").map(String::from),
        source_markdown: s.markdown.clone(),
        headings: Vec::new(),
        toc: fm.get("toc").and_then(|v| v.as_bool()).unwrap_or(true),
    }
}

/// Render one source's body into its page: template → twig → heading anchors
/// → link rewrite. Returns the page's own half of the template context, with
/// `headings` and its neighbours in it, for whatever renders against the page
/// next.
///
/// `neighbours` is the page before and after this one in the nav's reading
/// order — `None` at either end, and both `None` for a page the nav does not
/// hold.
#[allow(clippy::too_many_arguments)]
fn render_body(
    page: &mut PublishedPage,
    s: &SourceDoc,
    parsed: &frontmatter::ParsedFile,
    opts: &SiteOptions,
    path_to_filename: &HashMap<PathBuf, String>,
    collected: &Collected,
    neighbours: (Option<&NavLink>, Option<&NavLink>),
    #[cfg(feature = "syntax-highlighting")] syntaxes: &crate::syntax::Syntaxes,
    reports: &mut Vec<String>,
) -> serde_json::Map<String, JsonValue> {
    let audience = opts.audience.as_deref();
    let fm = &parsed.frontmatter;
    let current_path = Path::new(&s.path);
    let format = ContentFormat::from_extension(current_path).unwrap_or(ContentFormat::Markdown);

    let mut values = page_context_values(
        s,
        fm,
        collected,
        &page.contents_links,
        page.parent_link.as_ref(),
        audience,
    );
    let (prev, next) = neighbours;
    values.insert(
        "prev".into(),
        prev.map(|link| collected.entry_of(link))
            .unwrap_or(JsonValue::Null),
    );
    values.insert(
        "next".into(),
        next.map(|link| collected.entry_of(link))
            .unwrap_or(JsonValue::Null),
    );

    // A `verbatim` page skips everything: a hand-authored HTML file is a
    // document someone designed, and rewriting anything inside it is exactly
    // the kind of help it asked not to be given. Its headings are its own too.
    if page.layout.is_verbatim() {
        page.rendered_body = parsed.body.clone();
        page.markdown_body = parsed.body.clone();
        values.insert("headings".into(), JsonValue::Array(Vec::new()));
        return values;
    }

    // An attachment's body is its payload, and the sidecar wrote no prose to
    // expand: the page is the embed, and the headings are none. Before the
    // Markdown pass rather than through it so a title containing `_` or `*`
    // reaches the `alt` as written.
    if let Some(payload) = crate::attachment::payload_of(fm) {
        let (html, markdown) = crate::attachment::render(&page.title, payload);
        page.rendered_body = html;
        page.markdown_body = markdown;
        values.insert("headings".into(), JsonValue::Array(Vec::new()));
        return values;
    }

    // Always present so `:::each{of=headings}` over a page with none produces
    // nothing rather than an error — and a body that *names* it is expanded
    // twice below, because a page's headings are not known until its template
    // has run: a template that generates its headings still gets them listed.
    values.insert("headings".into(), JsonValue::Array(Vec::new()));
    let (expanded, html, headings) = render_source_body(
        &parsed.body,
        format,
        template::Context::new(&collected.context, &values),
        audience,
        current_path,
        reports,
        #[cfg(feature = "syntax-highlighting")]
        syntaxes,
    );
    values.insert("headings".into(), headings_value(&headings));
    let (expanded, html, headings) = if !headings.is_empty() && parsed.body.contains("headings") {
        render_source_body(
            &parsed.body,
            format,
            template::Context::new(&collected.context, &values),
            audience,
            current_path,
            // The first pass already said what there was to say.
            &mut Vec::new(),
            #[cfg(feature = "syntax-highlighting")]
            syntaxes,
        )
    } else {
        (expanded, html, headings)
    };

    // Rewrite internal document links last, so a heading anchor's own `#id`
    // is not a link this pass would try to resolve. The empty workspace dir
    // means canonical paths are used directly as `path_to_filename` keys.
    page.rendered_body = links::transform_links_with_files(
        &html,
        current_path,
        path_to_filename,
        Path::new(""),
        &page.dest_filename,
        opts.published_files.as_ref(),
    );
    page.markdown_body = expanded;
    page.headings = headings;
    values
}

/// Template → twig → heading anchors, for a body that is not verbatim.
///
/// Returns the expanded source, the anchored HTML, and the headings found.
///
/// The stored body is already visibility-filtered; template expansion still
/// needs to run (sources are stored pre-template). `template::render*`
/// re-applies visibility (a no-op now) and then expands the directives.
///
/// A template that will not expand still publishes its own source — there is
/// no better body to publish — but it no longer does so *quietly*. The page
/// names itself in `reports`, which `render_site` carries out as
/// `SiteRender::body_template_errors`, on the principle the shell templates
/// already hold to: silently serving the wrong thing is how a broken theme
/// survives a release.
///
/// The format is the *document's*, read off its extension, not the vault's
/// `content_format`: one site can hold a `.md` transcription beside the
/// `.html` artifact it transcribes, and each has to be parsed as what it is.
/// A path with no recognized extension falls back to Markdown, which is what
/// every document in every vault written before this was.
fn render_source_body(
    body: &str,
    format: ContentFormat,
    context: template::Context<'_>,
    audience: Option<&str>,
    at: &Path,
    reports: &mut Vec<String>,
    #[cfg(feature = "syntax-highlighting")] syntaxes: &crate::syntax::Syntaxes,
) -> (String, String, Vec<Heading>) {
    let mut warnings = Vec::new();
    let rendered = match audience {
        Some(a) => template::render_for_audiences(body, format, context, &[a], &mut warnings),
        None => template::render(body, format, context, &mut warnings),
    };
    reports.extend(
        warnings
            .into_iter()
            .map(|w| format!("{}: {w}", at.display())),
    );
    let expanded = match rendered {
        Ok(body) => body,
        Err(err) => {
            reports.push(format!(
                "{}: {err} — the page is published as its own source",
                at.display()
            ));
            body.to_string()
        }
    };

    // The site's grammars, not the built-in set that plain `render_body`
    // reaches for: a site that declared one of its own declared it to be used
    // here.
    #[cfg(feature = "syntax-highlighting")]
    let converted = body::render_body_with(&expanded, format, syntaxes);
    #[cfg(not(feature = "syntax-highlighting"))]
    let converted = body::render_body(&expanded, format);
    let (anchored, headings) = crate::headings::anchor_headings(&converted);
    (expanded, anchored, headings)
}

/// `headings`, as a template names it: a list of `{level, id, text}`.
fn headings_value(headings: &[Heading]) -> JsonValue {
    JsonValue::Array(
        headings
            .iter()
            .map(|h| serde_json::json!({ "level": h.level, "id": h.id, "text": h.text }))
            .collect(),
    )
}

/// Render the site's header or footer document for one page.
///
/// The same pipeline a body goes through — template expansion against the
/// page's context, `:vis` filtering for the site's audience, twig, link
/// rewriting to the page's depth — minus the heading anchors, since a frame is
/// not part of the page's outline. The document's own metadata block, if it
/// carries one, is stripped and otherwise unread: a frame is not an entry.
///
/// Relative links in it resolve against *its* path, so a header at
/// `.config/sites/docs/header.md` reaches `about.md` as `/about.md` (or
/// `../../../about.md`) and the rewrite lands the link wherever the page is.
#[allow(clippy::too_many_arguments)]
fn render_frame_doc(
    doc: &FrameDoc,
    what: &str,
    page: &PublishedPage,
    context: template::Context<'_>,
    opts: &SiteOptions,
    path_to_filename: &HashMap<PathBuf, String>,
    #[cfg(feature = "syntax-highlighting")] syntaxes: &crate::syntax::Syntaxes,
    reports: &mut Vec<String>,
) -> String {
    let at = Path::new(&doc.path);
    let format = ContentFormat::from_extension(at).unwrap_or(ContentFormat::Markdown);
    let body = frontmatter::parse_or_empty(&doc.source)
        .map(|parsed| parsed.body)
        .unwrap_or_else(|_| doc.source.clone());

    let mut warnings = Vec::new();
    let rendered = match opts.audience.as_deref() {
        Some(a) => template::render_for_audiences(&body, format, context, &[a], &mut warnings),
        None => template::render(&body, format, context, &mut warnings),
    };
    reports.extend(
        warnings
            .into_iter()
            .map(|w| format!("site {what} {}: {w}", at.display())),
    );
    let expanded = match rendered {
        Ok(body) => body,
        Err(err) => {
            reports.push(format!(
                "site {what} {}: {err} — it is published as its own source",
                at.display()
            ));
            body
        }
    };

    #[cfg(feature = "syntax-highlighting")]
    let converted = body::render_body_with(&expanded, format, syntaxes);
    #[cfg(not(feature = "syntax-highlighting"))]
    let converted = body::render_body(&expanded, format);
    links::transform_links_with_files(
        &converted,
        at,
        path_to_filename,
        Path::new(""),
        &page.dest_filename,
        opts.published_files.as_ref(),
    )
}

/// Resolve a frontmatter list of asset references (`styles`, `scripts`) into
/// paths below the site root.
///
/// A vault names a file either from its own root (`/assets/theme.css`, prov's
/// `path_style: root`) or relative to the document holding the reference
/// (`../assets/theme.css`); both spellings mean one file, and both arrive here.
/// Resolving them the way [`resolve_link`] resolves a `contents:` entry — and
/// the way [`crate::links::transform_links`] rebases an `<img src>` in the body
/// — is what makes a stylesheet named from a nested entry point at the same
/// object as one named from the front page.
///
/// The paths are **not** sanitized, matching how an attachment's own `src`
/// survives the body: a file keeps the name it has on disk, and the caller
/// copying it there is the same caller that copies attachments.
fn resolve_asset_paths(fm: &prov::Mapping, key: &str, current_relative: &Path) -> Vec<String> {
    frontmatter::get_string_array(fm, key)
        .iter()
        .filter_map(|raw| {
            let trimmed = raw.trim();
            if trimmed.is_empty() {
                return None;
            }
            let link = prov::Link::parse_path_only(trimmed);
            Some(
                prov::link::resolve(current_relative, &link.target)
                    .to_string_lossy()
                    .into_owned(),
            )
        })
        .collect()
}

// ── Generated index ─────────────────────────────────────────────────────────

/// The heading a page with nothing to group by is filed under.
const UNGROUPED: &str = "Other";

/// What a site is called when nobody said — no [`SiteOptions::site_title`], and
/// no authored root page to take a title from.
///
/// It is deliberately a word about the *thing* rather than about its front page.
/// The generated index answers to it too, so a site with no name reads
/// "Site" everywhere instead of disagreeing with itself; and a caller that
/// knows better — the CLI has the site's label, the server has its name —
/// should pass one rather than land here.
const DEFAULT_SITE_TITLE: &str = "Site";

/// Build a front page for a site whose render set contains none.
///
/// The page is a real [`PublishedPage`] with `is_root` set, so everything
/// downstream — nav, breadcrumbs, SEO, sitemap, feeds — treats it exactly like
/// an authored index and needs no special case. Its `contents_links` are the
/// entries in arrangement order, which is what makes
/// [`build_site_nav_tree`] hang the forest
/// underneath it.
///
/// Under [`Arrangement::Containment`] it lists the forest roots — the pages
/// nothing in this site contains, because the gate or the view removed whatever
/// did — and lets containment show the rest. Under [`Arrangement::Grouped`] it lists every entry under its group's
/// heading, because a site that declared an arrangement asked to be read that
/// way rather than by hierarchy.
pub fn synthesize_index(pages: &[PublishedPage], opts: &SiteOptions) -> PublishedPage {
    // The site's title, not a title of its own: this page *is* the site's front
    // door, and naming it separately is what made a rootless site call itself
    // "Index" in its `<title>`, its `og:site_name` and its feeds.
    let title = opts
        .site_title
        .clone()
        .unwrap_or_else(|| DEFAULT_SITE_TITLE.to_string());

    let (body, links) = match &opts.arrangement {
        Arrangement::Containment => {
            let roots = forest_roots(pages, &opts.outline);
            (render_entry_list(&roots), nav_links(&roots))
        }
        Arrangement::Grouped(grouping) => {
            let groups = group_entries(pages, grouping);
            let ordered: Vec<&PublishedPage> = groups
                .iter()
                .flat_map(|(_, ps)| ps.iter().copied())
                .collect();
            (render_groups(&groups), nav_links(&ordered))
        }
    };

    // Group headings get anchors like any body's, so a dated site's front
    // page has an outline and a month can be linked to.
    let (body, headings) = crate::headings::anchor_headings(&body);

    PublishedPage {
        source_path: PathBuf::from("index.md"),
        dest_filename: "index.html".to_string(),
        title,
        rendered_body: body,
        markdown_body: String::new(),
        contents_links: links,
        parent_link: None,
        is_root: true,
        description: None,
        author: None,
        created: None,
        updated: None,
        date_of_document: None,
        group_keys: Vec::new(),
        attachments: Vec::new(),
        styles: Vec::new(),
        scripts: Vec::new(),
        layout: PageLayout::default(),
        shell: None,
        // No frontmatter to declare one: a synthesized index is the site
        // speaking about itself, so it is in the site's language.
        lang: None,
        nav_title: None,
        nav_order: None,
        hide_from_nav: false,
        // A generated index is a listing of entries that are themselves in the
        // feed; syndicating it too would put a duplicate of the whole site at
        // the top of every reader.
        hide_from_feed: true,
        // No ARK: nothing in the vault corresponds to this page, so there is no
        // document identity to mint one against.
        id: None,
        source_markdown: String::new(),
        headings,
        toc: true,
    }
}

/// Group pages for a grouped arrangement. Date groups come back newest first,
/// field groups alphabetically; the ungrouped bucket is always last so a page
/// missing its grouping value is still reachable rather than dropped.
fn group_entries<'p>(
    pages: &'p [PublishedPage],
    grouping: &Grouping,
) -> Vec<(String, Vec<&'p PublishedPage>)> {
    let mut groups: BTreeMap<String, Vec<&PublishedPage>> = BTreeMap::new();
    let mut ungrouped: Vec<&PublishedPage> = Vec::new();

    for page in pages {
        if page.hide_from_nav {
            continue;
        }
        if page.group_keys.is_empty() {
            ungrouped.push(page);
            continue;
        }
        // A page with several values for the grouping field appears under each,
        // which is what a field lens means: filing under `people` puts a story
        // about two people in both their groups.
        for key in &page.group_keys {
            groups.entry(key.clone()).or_default().push(page);
        }
    }

    // A calendar reads newest-first, an A–Z index reads A-first. That used to
    // fall out of matching the `Date` variant; with the variant gone it is a
    // question about the *grain*, which is the more honest place for it — a view
    // over `taken_on` by month is just as chronological as one over `created`,
    // and the field name was never what made it so.
    let descending = matches!(grouping.by, Some(Grain::Year | Grain::Month | Grain::Day));
    let mut out: Vec<(String, Vec<&PublishedPage>)> = groups.into_iter().collect();
    if descending {
        out.reverse();
    }
    for (_, entries) in &mut out {
        sort_entries(entries, descending);
    }
    if !ungrouped.is_empty() {
        sort_entries(&mut ungrouped, descending);
        out.push((UNGROUPED.to_string(), ungrouped));
    }
    out
}

/// Sort entries within a group: by date when the arrangement is dated (newest
/// first, undated last), else by title.
///
/// The dated order is [`page::newest_first`] — the comparator the feeds use —
/// rather than a second implementation of it. Two orderings of one set of
/// entries is one ordering that will drift, and the drift shows up as a site
/// whose front page and whose feed disagree about what came first.
fn sort_entries(entries: &mut [&PublishedPage], by_date: bool) {
    if by_date {
        entries.sort_by(|a, b| page::newest_first(a, b));
    } else {
        entries.sort_by(|a, b| a.title.cmp(&b.title));
    }
}

// `cut_date` and `field_values` used to live here. `Grain::cut` and
// `Grouping::keys_of` are both, and are the ones the vault already uses — the
// date cut with its validation (`banana` at year grain is not the group `bana`)
// and the two field spellings permitted (`people: Grandpa` and
// `people: [Grandpa, Nan]`) included.

/// `<ul>` of links to entries.
fn render_entry_list(entries: &[&PublishedPage]) -> String {
    let mut out = String::from("<ul class=\"entry-list\">\n");
    for page in entries {
        out.push_str(&format!(
            "<li><a href=\"{}\">{}</a>{}</li>\n",
            page::html_escape(&page.dest_filename),
            page::html_escape(page.nav_title.as_deref().unwrap_or(&page.title)),
            match page.description.as_deref() {
                Some(d) if !d.is_empty() => format!(
                    " <span class=\"entry-description\">{}</span>",
                    page::html_escape(d)
                ),
                _ => String::new(),
            }
        ));
    }
    out.push_str("</ul>\n");
    out
}

/// A `<section>` per group, each with a heading and its entry list.
fn render_groups(groups: &[(String, Vec<&PublishedPage>)]) -> String {
    let mut out = String::new();
    for (label, entries) in groups {
        out.push_str(&format!(
            "<section class=\"entry-group\">\n<h2>{}</h2>\n",
            page::html_escape(label)
        ));
        out.push_str(&render_entry_list(entries));
        out.push_str("</section>\n");
    }
    out
}

/// Nav links to entries, in the order given.
fn nav_links(entries: &[&PublishedPage]) -> Vec<NavLink> {
    entries
        .iter()
        .map(|p| NavLink {
            href: p.dest_filename.clone(),
            title: p.nav_title.clone().unwrap_or_else(|| p.title.clone()),
        })
        .collect()
}

/// Resolve a `contents`/`part_of` link string to a [`NavLink`] whose href is the
/// target's output `.html` filename and whose title comes from the target's
/// frontmatter or the link text.
///
/// Returns `None` when the target is not part of the current render set (e.g.
/// excluded by audience visibility). Dropping it keeps nav/breadcrumbs limited
/// to pages that actually exist for this audience — without any separate
/// manifest, since `path_to_filename` already is the rendered-page set.
fn resolve_link(
    link_str: &str,
    current_relative: &Path,
    path_to_filename: &HashMap<PathBuf, String>,
    title_map: &HashMap<PathBuf, String>,
    resolver: &Resolver,
) -> Option<NavLink> {
    let link = prov::Link::parse(link_str.trim());
    let key = resolver.key(current_relative, link_str)?;

    // A whole-file node — an attachment's `photo.jpg.yaml` — is collected
    // under the spelling a source has, `photo.jpg.md`, because its metadata
    // travels re-fenced as a Markdown document's would (`plates::collect`
    // swaps an extension prov reads no prose from for the default grammar's).
    // A `contents:` entry names the node by the path on disk, so the lookup
    // makes the same swap.
    let key = if !path_to_filename.contains_key(&key)
        && prov::document::whole_file_format(&key).is_some()
    {
        key.with_extension("md")
    } else {
        key
    };

    let href = path_to_filename.get(&key)?.clone();

    let title = title_map
        .get(&key)
        .cloned()
        .or_else(|| link.label.clone())
        .unwrap_or_else(|| filename_to_title(&key.to_string_lossy()));

    Some(NavLink { href, title })
}

/// What a `contents:`/`part_of:` entry names, answered the way prov answers
/// it.
///
/// A relation entry is written in whatever spelling prov's reference grammar
/// allows — a path relative to the document or to the root, an `id:<id>`
/// that survives a move, the legacy `colophon:` form of it, a `[[Title]]` or
/// bare name that resolves by title or file stem, a `[label](target)` around
/// any of those. prov's [`Graph::resolve_link_with`](prov::Graph) is the one
/// reading of all of them, and this is that resolver over the render set:
/// an id index and a title index filled from the sources' own frontmatter,
/// over a filesystem nothing reads, because everything resolution needs was
/// read when the sources were. Every spelling prov learns arrives here with
/// no code of this crate's, and a spelling the vault's own `prov check`
/// accepts cannot be one the site refuses.
///
/// What it does not know is the workspace's name, so a reference qualified
/// with it (`id:<this workspace>/<id>`) is foreign here and names nothing —
/// as it did before.
///
/// Read as a path alone, an `id:` entry named a file called `id:…` that no
/// source has, and the page it pointed at landed flat at the top of the nav
/// as a one-sided link — listed by its container, in a spelling the fallback
/// could not read.
struct Resolver {
    graph: prov::Graph<prov::InMemoryFs, prov::InMemoryIndex>,
    titles: prov::TitleIndex,
}

impl Resolver {
    fn new() -> Self {
        Self {
            graph: prov::Graph::new(
                prov::InMemoryFs::new(),
                PathBuf::new(),
                prov::InMemoryIndex::new(),
                prov::ReadSettings::default(),
            ),
            titles: prov::TitleIndex::new(),
        }
    }

    /// Register what a source at `key` answers to: its `id`, and — as prov's
    /// own title scan does — its file stem and its `title`.
    fn learn(&mut self, key: &Path, fm: &prov::Mapping) {
        use prov::IndexStore as _;
        if let Some(id) = frontmatter::get_string(fm, "id") {
            self.graph
                .index_mut()
                .register(&prov::Id(id.to_string()), key);
        }
        if let Some(stem) = key.file_stem().and_then(|s| s.to_str()) {
            self.titles.insert(stem, key);
        }
        if let Some(title) = frontmatter::get_string(fm, "title") {
            self.titles.insert(title, key);
        }
    }

    /// The sanitized source-path key `target`, written in the document at
    /// `doc`, names — or `None` when it names nothing this render can address.
    fn key(&self, doc: &Path, target: &str) -> Option<PathBuf> {
        let link = prov::Link::parse(target.trim());
        match self.graph.resolve_link_with(doc, &link, Some(&self.titles)) {
            prov::Target::Path(path) => Some(PathBuf::from(links::sanitize_rel_path(
                &path.to_string_lossy(),
            ))),
            _ => None,
        }
    }
}

// ── Filename helpers (ported from the publish plugin) ────────────────────────

pub use crate::types::output_filename;

/// Where one source publishes: `index.html` for the site's front page, the
/// destination its frontmatter `serve_at:` claims, else [`output_filename`].
///
/// The single rule, so a caller that must know a page's destination before the
/// render — the server, naming the object it will write; the publish client,
/// naming the key it uploads against — asks rather than re-derives. Two
/// derivations of one filename is one filename that will drift, and the drift
/// is a page whose ARK resolves to an object nothing wrote.
pub fn dest_of(source: &SourceDoc) -> String {
    let fm = frontmatter::parse_or_empty(&source.markdown)
        .map(|parsed| parsed.frontmatter)
        .unwrap_or_default();
    dest_for(&source.path, source.is_root, &fm)
}

/// [`dest_of`] for a caller that has already parsed the metadata block.
fn dest_for(path: &str, is_root: bool, fm: &prov::Mapping) -> String {
    // The site's front page is its front door rather than a page with an
    // address of its own, so a `serve_at:` on it has nothing to claim.
    if is_root {
        return "index.html".to_string();
    }
    frontmatter::get_string(fm, "serve_at")
        .and_then(serve_at_dest)
        .unwrap_or_else(|| output_filename(path))
}

/// Convert a filename to a display title (snake/kebab case → Title Case).
fn filename_to_title(filename: &str) -> String {
    let stem = Path::new(filename)
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or(filename);
    humanize_name(stem)
}

/// Turn a machine name into something to show a reader: `family-letters` →
/// `Family Letters`.
///
/// Public because a site's *name* needs the same treatment as a document's
/// filename, and the callers that hold one — the server, which knows a site
/// only by the segment it is served under — are outside this crate. A caller
/// with a real label should pass that instead.
pub fn humanize_name(name: &str) -> String {
    name.split(['_', '-'])
        .filter(|s| !s.is_empty())
        .map(|word| {
            let mut chars: Vec<char> = word.chars().collect();
            if let Some(first) = chars.first_mut() {
                *first = first.to_ascii_uppercase();
            }
            chars.into_iter().collect::<String>()
        })
        .collect::<Vec<_>>()
        .join(" ")
}

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

    fn src(path: &str, markdown: &str, is_root: bool) -> SourceDoc {
        SourceDoc {
            path: path.to_string(),
            markdown: markdown.to_string(),
            is_root,
            inbound: Vec::new(),
            outbound: Vec::new(),
        }
    }

    /// [`src`], told who links to it in prose — the shape the collector hands
    /// over for an untyped link.
    fn linked(path: &str, markdown: &str, backlinks: &[&str]) -> SourceDoc {
        SourceDoc {
            inbound: backlinks
                .iter()
                .map(|s| LinkEdge {
                    relation: None,
                    path: (*s).to_string(),
                })
                .collect(),
            ..src(path, markdown, false)
        }
    }

    /// `(relation, path)` pairs as the collector spells them.
    fn edges(pairs: &[(&str, &str)]) -> Vec<LinkEdge> {
        pairs
            .iter()
            .map(|(relation, path)| LinkEdge {
                relation: Some((*relation).to_string()),
                path: (*path).to_string(),
            })
            .collect()
    }

    /// The date chain these tests declare for their own views, written out
    /// here because it is a declaration a vault makes rather than something
    /// this crate knows: the layer that owns a vault's vocabulary names the
    /// same three fields, above this one.
    fn date_grouping(by: Grain) -> Grouping {
        Grouping {
            keys: ["date_of_document", "created", "updated"]
                .iter()
                .map(|k| (*k).to_string())
                .collect(),
            by: Some(by),
        }
    }

    #[test]
    fn output_filename_sanitizes_and_sets_html() {
        assert_eq!(output_filename("notes/My Note!.md"), "notes/My Note.html");
        assert_eq!(output_filename("a/b/c.md"), "a/b/c.html");
    }

    /// Every content format lands on `.html`, and a source that is already
    /// `.html` keeps its name rather than gaining a second extension.
    #[test]
    fn output_filename_covers_every_content_format() {
        assert_eq!(output_filename("notes/entry.dj"), "notes/entry.html");
        assert_eq!(output_filename("notes/entry.djot"), "notes/entry.html");
        assert_eq!(
            output_filename("notes/artifact.html"),
            "notes/artifact.html"
        );
        assert_eq!(output_filename("notes/artifact.htm"), "notes/artifact.html");
    }

    /// A folder note — a file named for the directory holding it — is that
    /// directory's index, whatever content format it is written in. The
    /// comparison is against the immediate directory only, and a file with no
    /// directory above it is nobody's note.
    #[test]
    fn output_filename_makes_a_folder_note_its_directorys_index() {
        assert_eq!(output_filename("page/page.md"), "page/index.html");
        assert_eq!(output_filename("page/page.dj"), "page/index.html");
        assert_eq!(output_filename("page/page.djot"), "page/index.html");
        assert_eq!(output_filename("about/about.html"), "about/index.html");
        assert_eq!(
            output_filename("a/physics-121/physics-121.md"),
            "a/physics-121/index.html"
        );

        // `index.md` reaches the same destination by the plain extension swap,
        // which is why it needs no case of its own.
        assert_eq!(output_filename("page/index.md"), "page/index.html");

        // And what is not a folder note.
        assert_eq!(output_filename("notes/page.md"), "notes/page.html");
        assert_eq!(output_filename("page.md"), "page.html");
        assert_eq!(
            output_filename("page/pages.md"),
            "page/pages.html",
            "near is not the same"
        );
    }

    /// The link half, end to end: `dest_for` feeds the rewrite map, so a link
    /// to a folder note lands on the directory's index without anything at the
    /// link site knowing the rule.
    #[test]
    fn a_link_to_a_folder_note_is_rewritten_to_its_directorys_index() {
        let index = "---\ntitle: Home\ncontents:\n  - \"[Page](/page/page.md)\"\n---\nSee [the page](/page/page.md).\n";
        let page = "---\ntitle: Page\npart_of: \"/index.md\"\n---\nBack [home](/index.md).\n";

        let sources = vec![
            src("index.md", index, true),
            src("page/page.md", page, false),
        ];
        let pages = build_pages(&sources, &SiteOptions::default());

        let folder_note = pages.iter().find(|p| p.title == "Page").unwrap();
        assert_eq!(
            folder_note.dest_filename, "page/index.html",
            "the folder note is its directory's index"
        );

        let home = pages.iter().find(|p| p.is_root).unwrap();
        assert!(
            home.rendered_body.contains(r#"href="page/index.html""#),
            "the body link follows the destination: {}",
            home.rendered_body
        );
        assert_eq!(
            home.contents_links[0].href, "page/index.html",
            "and so does the contents entry"
        );

        // And back the other way, rebased for the depth the folder note sits
        // at — one level down, so `../`.
        assert!(
            folder_note
                .rendered_body
                .contains(r#"href="../index.html""#),
            "got {}",
            folder_note.rendered_body
        );
    }

    /// One site, three grammars — the case a vault reaches by importing an
    /// `.html` artifact next to the `.md` note that describes it. Each body is
    /// parsed as what its extension says it is, and the links between them are
    /// rewritten regardless of which format either end is written in.
    #[test]
    fn a_site_may_mix_content_formats() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/note.dj\"\n  - \"/artifact.html\"\n---\nSee [the note](/note.dj).\n";
        let note = "---\ntitle: Note\npart_of: \"/index.md\"\n---\nA _djot_ note with a ==highlight== and a [link](/artifact.html).\n";
        let artifact =
            "---\ntitle: Artifact\npart_of: \"/index.md\"\n---\n<p>Already <em>HTML</em>.</p>\n";

        let sources = vec![
            src("index.md", index, true),
            src("note.dj", note, false),
            src("artifact.html", artifact, false),
        ];
        let pages = build_pages(&sources, &SiteOptions::default());

        let note_page = pages.iter().find(|p| p.title == "Note").unwrap();
        assert!(
            note_page.rendered_body.contains("<em>djot</em>"),
            "djot emphasis is `_x_`, which Markdown would not have italicized: {}",
            note_page.rendered_body
        );
        assert!(
            note_page.rendered_body.contains("highlight-mark"),
            "Diaryx's custom syntax works in djot too: {}",
            note_page.rendered_body
        );
        assert!(
            note_page.rendered_body.contains(r#"href="artifact.html""#),
            "a djot link to an html document is rewritten: {}",
            note_page.rendered_body
        );

        let artifact_page = pages.iter().find(|p| p.title == "Artifact").unwrap();
        assert!(artifact_page.rendered_body.contains("<em>HTML</em>"));

        // The root's link to the `.dj` note resolves to the note's dest page,
        // which is the half `md_link_canonical`'s `.md` test used to miss.
        let home = pages.iter().find(|p| p.is_root).unwrap();
        assert!(
            home.rendered_body.contains(r#"href="note.html""#),
            "got {}",
            home.rendered_body
        );
        assert_eq!(home.contents_links.len(), 2);
    }

    #[test]
    fn filename_to_title_titlecases() {
        assert_eq!(filename_to_title("hello-world.md"), "Hello World");
        assert_eq!(filename_to_title("my_cool_note.md"), "My Cool Note");
    }

    #[test]
    fn build_pages_derives_graph_and_renders() {
        let index = "---\ntitle: Home\ncontents:\n  - \"[Child](/child.md)\"\n---\nWelcome to :val[title].\n";
        let child = "---\ntitle: Child Page\npart_of: \"/index.md\"\n---\nSee [home](/index.md) and a ==highlight==.\n";

        let sources = vec![src("index.md", index, true), src("child.md", child, false)];
        let pages = build_pages(&sources, &SiteOptions::default());

        let home = pages.iter().find(|p| p.is_root).unwrap();
        let kid = pages.iter().find(|p| !p.is_root).unwrap();

        // dest filenames
        assert_eq!(home.dest_filename, "index.html");
        assert_eq!(kid.dest_filename, "child.html");

        // the value directive resolved against frontmatter
        assert!(home.rendered_body.contains("Welcome to Home."));

        // contents_links resolved to child's html + frontmatter title
        assert_eq!(home.contents_links.len(), 1);
        assert_eq!(home.contents_links[0].href, "child.html");
        assert_eq!(home.contents_links[0].title, "Child Page");

        // parent_link resolves back to index
        let parent = kid.parent_link.as_ref().unwrap();
        assert_eq!(parent.href, "index.html");
        assert_eq!(parent.title, "Home");

        // internal .md link rewritten to .html, and custom syntax expanded
        assert!(kid.rendered_body.contains(r#"href="index.html""#));
        assert!(kid.rendered_body.contains("highlight-mark"));
    }

    #[test]
    fn root_by_workspace_name_and_special_chars_resolve() {
        // Option 1: sources keyed by workspace path; root keeps its real name
        // ("Welcome.md"), not "index". Child links reference workspace paths,
        // including a special character that the dest sanitizer strips.
        let root = "---\ntitle: Home\ncontents:\n  - \"/My Note!.md\"\n---\nHi.\n";
        let note = "---\ntitle: My Note\npart_of: \"/Welcome.md\"\n---\nBody.\n";

        let sources = vec![
            src("Welcome.md", root, true),
            src("My Note.md", note, false), // stored under sanitized workspace path
        ];
        let pages = build_pages(&sources, &SiteOptions::default());

        let home = pages.iter().find(|p| p.is_root).unwrap();
        let note_page = pages.iter().find(|p| !p.is_root).unwrap();

        // Root renders to index.html despite its workspace name.
        assert_eq!(home.dest_filename, "index.html");
        // Child's contents link (with "!") resolves to the sanitized dest + title.
        assert_eq!(home.contents_links.len(), 1);
        assert_eq!(home.contents_links[0].href, "My Note.html");
        assert_eq!(home.contents_links[0].title, "My Note");
        // Child's part_of points at the root by its workspace name → index.html.
        let parent = note_page.parent_link.as_ref().unwrap();
        assert_eq!(parent.href, "index.html");
        assert_eq!(parent.title, "Home");
    }

    /// A `contents:`/`part_of:` entry is read in every spelling prov reads —
    /// a path, an `id:<id>` (what a document keeps across moves, and what
    /// diaryx writes for a page it creates under a section), the legacy
    /// `colophon:` form, a `[[Title]]` alias, a bare file stem — and lands on
    /// the page it names, exactly as a path entry does. With no outline
    /// supplied, the nav is built from these links, and a child its container
    /// listed only by id used to fall out of the section and onto the top
    /// level as a one-sided link.
    #[test]
    fn a_relation_entry_resolves_in_every_spelling_prov_reads() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/blog/blog.md\"\n---\nHi.\n";
        let blog = concat!(
            "---\ntitle: Blog\nid: mn1j30r\npart_of: \"/index.md\"\ncontents:\n",
            "  - \"[By path](/blog/by-path.md)\"\n",
            "  - id:9wq31fj\n",
            "  - colophon:k2h7f0a\n",
            "  - \"[[By alias]]\"\n",
            "  - by-stem\n",
            "  - id:elsewhere/zzzzzzz\n",
            "  - id:\n",
            "---\nPosts.\n",
        );
        let by_path = "---\ntitle: By path\nid: x8qqhzx\npart_of: \"/blog/blog.md\"\n---\nBody.\n";
        let by_id = "---\ntitle: By id\nid: 9wq31fj\npart_of: id:mn1j30r\n---\nBody.\n";
        let by_legacy =
            "---\ntitle: By legacy id\nid: k2h7f0a\npart_of: colophon:mn1j30r\n---\nBody.\n";
        let by_alias = "---\ntitle: By alias\npart_of: \"[[Blog]]\"\n---\nBody.\n";
        let by_stem = "---\ntitle: By stem\npart_of: blog\n---\nBody.\n";

        let sources = vec![
            src("index.md", index, true),
            src("blog/blog.md", blog, false),
            src("blog/by-path.md", by_path, false),
            src("blog/by-id.md", by_id, false),
            src("blog/by-legacy.md", by_legacy, false),
            src("blog/by-alias.md", by_alias, false),
            src("blog/by-stem.md", by_stem, false),
        ];
        let pages = build_pages(&sources, &SiteOptions::default());

        let listed = [
            "blog/by-path.html",
            "blog/by-id.html",
            "blog/by-legacy.html",
            "blog/by-alias.html",
            "blog/by-stem.html",
        ];
        let blog = pages.iter().find(|p| p.title == "Blog").unwrap();
        let hrefs: Vec<&str> = blog
            .contents_links
            .iter()
            .map(|l| l.href.as_str())
            .collect();
        assert_eq!(
            hrefs, listed,
            "every spelling resolves; a foreign id and a malformed one name nothing here"
        );
        assert_eq!(
            blog.contents_links[1].title, "By id",
            "titled from the target, as a path entry is"
        );

        for page in pages
            .iter()
            .filter(|p| listed.contains(&p.dest_filename.as_str()))
        {
            let parent = page
                .parent_link
                .as_ref()
                .unwrap_or_else(|| panic!("{}'s part_of resolves too", page.dest_filename));
            assert_eq!(parent.href, "blog/index.html", "{}", page.dest_filename);
        }

        // …and the nav nests every one under the section rather than beside it.
        let tree = crate::nav::build_site_nav_tree(&pages, &[]);
        let home = &tree[0];
        assert_eq!(
            home.children.len(),
            1,
            "only the section hangs off the root: {:?}",
            home.children.iter().map(|n| &n.href).collect::<Vec<_>>()
        );
        let section = &home.children[0];
        assert_eq!(section.href, "blog/index.html");
        let nested: Vec<&str> = section.children.iter().map(|n| n.href.as_str()).collect();
        assert_eq!(nested, listed);

        // The template context reads the same spine: the page's `parent` is
        // the section, not nothing.
        let out = render_site(&sources, &SiteOptions::default());
        let by_id_html = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "blog/by-id.html")
            .unwrap();
        assert!(
            by_id_html.html.contains("blog/index.html"),
            "breadcrumbs reach the section"
        );
    }

    #[test]
    fn contents_link_to_excluded_page_is_dropped() {
        // The root lists two children, but only one is in the render set (the
        // other was excluded for this audience). Nav/contents must not link to
        // the missing page — that's the source-side cause of the 404 sidebar
        // entries.
        let index = "---\ntitle: Home\ncontents:\n  - \"/public-child.md\"\n  - \"/private-child.md\"\n---\nHi.\n";
        let public_child = "---\ntitle: Public Child\npart_of: \"/index.md\"\n---\nBody.\n";

        let sources = vec![
            src("index.md", index, true),
            src("public-child.md", public_child, false),
        ];
        let pages = build_pages(&sources, &SiteOptions::default());

        let home = pages.iter().find(|p| p.is_root).unwrap();
        assert_eq!(home.contents_links.len(), 1, "excluded child dropped");
        assert_eq!(home.contents_links[0].href, "public-child.html");

        // And the rendered nav reflects only the included child.
        let out = render_site(&sources, &SiteOptions::default());
        let home_html = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home_html.html.contains("public-child.html"));
        assert!(!home_html.html.contains("private-child.html"));
    }

    #[test]
    fn parent_link_to_excluded_page_is_dropped() {
        // A page whose parent was excluded for this audience must not carry a
        // dead breadcrumb/parent link.
        let index = "---\ntitle: Home\n---\nHi.\n";
        let orphan = "---\ntitle: Orphan\npart_of: \"/excluded.md\"\n---\nBody.\n";

        let sources = vec![
            src("index.md", index, true),
            src("orphan.md", orphan, false),
        ];
        let pages = build_pages(&sources, &SiteOptions::default());

        let orphan_page = pages
            .iter()
            .find(|p| p.dest_filename == "orphan.html")
            .unwrap();
        assert!(orphan_page.parent_link.is_none());
    }

    // ── generated index ─────────────────────────────────────────────────────

    fn entry(title: &str, date: &str) -> String {
        format!("---\ntitle: {title}\ndate_of_document: {date}\n---\nBody of {title}.\n")
    }

    /// A grammar the site declared reaches the pages it publishes — the whole
    /// point of [`SiteOptions::syntaxes`], and the one step that is neither
    /// `syntax`'s nor `body`'s to test.
    #[cfg(feature = "syntax-highlighting")]
    #[test]
    fn a_declared_grammar_colours_the_sites_code() {
        let note = "---\ntitle: Note\n---\n```wat\n;; a note\n```\n";
        let mut opts = SiteOptions::default();
        opts.syntaxes.insert(
            ".config/sites/blog/wat.sublime-syntax".to_string(),
            "name: Wat\nfile_extensions: [wat]\nscope: source.wat\ncontexts:\n  main:\n    \
             - match: ';;.*$'\n      scope: comment.line.wat\n"
                .to_string(),
        );

        let out = render_site(&[src("index.md", note, true)], &opts);
        assert!(out.syntax_errors.is_empty(), "{:?}", out.syntax_errors);
        assert!(
            out.pages[0].html.contains("plates-comment"),
            "the site's own grammar did not reach the page: {}",
            out.pages[0].html
        );
    }

    /// And one that will not parse costs the site some colour rather than its
    /// publication — the bargain a broken shell template gets.
    #[cfg(feature = "syntax-highlighting")]
    #[test]
    fn a_broken_declared_grammar_is_reported_not_fatal() {
        let note = "---\ntitle: Note\n---\n```rust\nlet x = 1;\n```\n";
        let mut opts = SiteOptions::default();
        opts.syntaxes.insert(
            ".config/sites/blog/broken.sublime-syntax".to_string(),
            "this: is: not: a grammar".to_string(),
        );

        let out = render_site(&[src("index.md", note, true)], &opts);
        assert_eq!(out.syntax_errors.len(), 1, "{:?}", out.syntax_errors);
        assert!(
            out.syntax_errors[0].contains("broken.sublime-syntax"),
            "names the file: {:?}",
            out.syntax_errors
        );
        assert!(
            out.pages[0].html.contains("plates-storage"),
            "rust still highlights: {}",
            out.pages[0].html
        );
    }

    /// The case per-file audiences create: three entries tagged for a site,
    /// none of them the vault's (private) root. There is no page to promote, so
    /// the render synthesizes one rather than crowning whichever entry sorted
    /// first.
    #[test]
    fn a_rootless_set_gets_a_generated_index() {
        let sources = vec![
            src("mon.md", &entry("Monday", "2026-07-27"), false),
            src("tue.md", &entry("Tuesday", "2026-07-28"), false),
        ];

        let out = render_site(&sources, &SiteOptions::default());

        let index = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .expect("a synthesized index");
        assert!(index.html.contains("mon.html"));
        assert!(index.html.contains("tue.html"));
        assert!(index.id.is_none(), "nothing in the vault to identify");
        assert_eq!(out.pages.len(), 3, "the index plus both entries");
    }

    /// An attachment is a page: its sidecar, collected under a source's
    /// spelling with its metadata re-fenced and no body, renders in the site
    /// frame with the payload embedded by a sibling reference; the parent
    /// that lists it by the path on disk finds it in the nav and its child
    /// list; and the pager walks through it.
    #[test]
    fn an_attachment_renders_as_a_page_its_parent_lists() {
        let sources = vec![
            src(
                "index.md",
                "---\ntitle: Home\ncontents:\n- archive/archive.md\n---\nHome.\n",
                true,
            ),
            src(
                "archive/archive.md",
                "---\ntitle: Archive\npart_of: /index.md\ncontents:\n- attachments/scan.pdf.yaml\n- notes.md\n---\nPapers.\n",
                false,
            ),
            src(
                "archive/attachments/scan.pdf.md",
                "---\ntitle: The Scan\ncontent: scan.pdf\nattachment: true\npart_of: /archive/archive.md\n---\n",
                false,
            ),
            src(
                "archive/notes.md",
                "---\ntitle: Notes\npart_of: /archive/archive.md\n---\nNotes.\n",
                false,
            ),
        ];
        let out = render_site(&sources, &SiteOptions::default());

        let scan = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "archive/attachments/scan.pdf.html")
            .expect("the sidecar is a page");
        assert!(
            scan.html
                .contains(r#"<iframe src="scan.pdf" title="The Scan">"#),
            "the payload is the body: {}",
            scan.html
        );
        assert!(
            scan.html
                .contains(r#"<a href="scan.pdf" download>Download scan.pdf</a>"#),
            "{}",
            scan.html
        );
        assert!(scan.html.contains("<title>The Scan"), "framed like a page");
        // The nav on the parent lists the attachment by its title, at the
        // page's address — not the sidecar's path on disk.
        let archive = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "archive/index.html")
            .unwrap();
        assert!(
            archive
                .html
                .contains(r#"<a href="../archive/attachments/scan.pdf.html">The Scan</a>"#),
            "listed by the page that holds it: {}",
            archive.html
        );
        assert!(
            !archive.html.contains("scan.pdf.yaml"),
            "the sidecar's own spelling never reaches the page: {}",
            archive.html
        );
        // The pager walks through it: the attachment's next is its sibling.
        assert!(
            scan.html.contains(r#"rel="next""#) && scan.html.contains("notes.html"),
            "in the reading order: {}",
            scan.html
        );
    }

    /// …but not when the caller is supplying the front page itself. A site
    /// fronted by a covered directory publishes an authored `index.html` that
    /// never passes through this crate, so from here it looks exactly like a
    /// rootless set — and generating one anyway writes it straight over the
    /// page the site was fronted with.
    #[test]
    fn a_supplied_front_page_is_not_generated_over() {
        let sources = vec![
            src("mon.md", &entry("Monday", "2026-07-27"), false),
            src("tue.md", &entry("Tuesday", "2026-07-28"), false),
        ];

        let out = render_site(
            &sources,
            &SiteOptions {
                site_title: Some("Diaryx".to_string()),
                front_page_supplied: true,
                ..SiteOptions::default()
            },
        );

        assert!(
            !out.pages.iter().any(|p| p.dest_filename == "index.html"),
            "the render must leave the site's root key alone"
        );
        assert_eq!(out.pages.len(), 2, "the entries, and nothing invented");
        // The entries still render, still know the site's name, and still link
        // to each other — a supplied front page removes a page, not a site.
        let mon = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "mon.html")
            .expect("the entries still render");
        assert!(mon.html.contains("<title>Monday - Diaryx<"));
    }

    /// A feed is absolute URLs, so a render with no base URL writes none —
    /// and, since these two were separate conditions, used to put a
    /// `<link rel="alternate">` on every page pointing at the `feed.xml` it
    /// had just skipped. Every published site was in that state, because the
    /// base URL came from a parameter no client sent.
    #[test]
    fn a_site_with_no_base_url_advertises_no_feed() {
        let sources = vec![src("mon.md", &entry("Monday", "2026-07-27"), false)];
        let out = render_site(&sources, &SiteOptions::default());

        assert!(
            !out.assets
                .iter()
                .any(|(n, _)| n == "feed.xml" || n == "rss.xml"),
            "no absolute URL to write them against"
        );
        for page in &out.pages {
            assert!(
                !page.html.contains("rel=\"alternate\""),
                "nor anything to advertise: {}",
                page.dest_filename
            );
        }
    }

    /// A site with no authored root used to be named after the index
    /// synthesized for it, so every page announced the site as "Index" — in its
    /// `<title>`, its `og:site_name` and both feeds.
    #[test]
    fn a_rootless_site_is_not_named_after_its_generated_index() {
        let sources = vec![src("mon.md", &entry("Monday", "2026-07-27"), false)];
        let opts = SiteOptions {
            site_title: Some("Family Letters".to_string()),
            base_url: Some("https://example.test".to_string()),
            ..SiteOptions::default()
        };

        let out = render_site(&sources, &opts);
        let entry_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "mon.html")
            .unwrap();
        assert!(entry_page.html.contains("<title>Monday - Family Letters<"));
        assert!(
            entry_page
                .html
                .contains(r#"og:site_name" content="Family Letters""#)
        );
        assert!(!entry_page.html.contains("Index"));

        // The generated front page answers to the site's name rather than
        // inventing one, so it does not disagree with the pages under it.
        let index = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(index.html.contains("<title>Family Letters</title>"));

        let feed = out
            .assets
            .iter()
            .find(|(n, _)| n == "feed.xml")
            .map(|(_, b)| String::from_utf8_lossy(b).into_owned())
            .unwrap();
        assert!(feed.contains("<title>Family Letters</title>"));
    }

    /// Told nothing, a site is called something about itself rather than about
    /// its front page — and still agrees with its own index.
    #[test]
    fn an_unnamed_rootless_site_falls_back_to_one_word_everywhere() {
        let sources = vec![src("mon.md", &entry("Monday", "2026-07-27"), false)];
        let out = render_site(&sources, &SiteOptions::default());

        let index = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(index.html.contains("<title>Site</title>"));
        let entry_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "mon.html")
            .unwrap();
        assert!(entry_page.html.contains("<title>Monday - Site<"));
    }

    /// An authored root still names the site — the fix is about where the name
    /// comes from when there is no such page, not about overriding one.
    #[test]
    fn an_authored_root_still_names_the_site() {
        let root = "---\ntitle: Home\n---\nHand written.\n";
        let sources = vec![
            src("index.md", root, true),
            src("mon.md", &entry("Monday", "2026-07-27"), false),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let entry_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "mon.html")
            .unwrap();
        assert!(entry_page.html.contains("<title>Monday - Home<"));
    }

    #[test]
    fn humanize_name_title_cases_a_machine_name() {
        assert_eq!(humanize_name("family-letters"), "Family Letters");
        assert_eq!(humanize_name("blog"), "Blog");
    }

    /// An authored index is left alone — synthesis is the fallback, not the rule.
    #[test]
    fn an_authored_index_is_not_replaced() {
        let root = "---\ntitle: Home\n---\nHand written.\n";
        let sources = vec![
            src("index.md", root, true),
            src("mon.md", &entry("Monday", "2026-07-27"), false),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let index = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(index.html.contains("Hand written."));
        assert_eq!(out.pages.len(), 2);
    }

    /// A dated arrangement groups by the grain and puts the newest group first —
    /// the ordering a journal wants when hierarchy is not what organizes it.
    #[test]
    fn a_dated_arrangement_groups_newest_first() {
        let sources = vec![
            src("old.md", &entry("Old", "2024-01-02"), false),
            src("new.md", &entry("New", "2026-07-27"), false),
            src("mid.md", &entry("Mid", "2025-05-05"), false),
        ];
        let opts = SiteOptions {
            arrangement: Arrangement::Grouped(date_grouping(Grain::Year)),
            ..SiteOptions::default()
        };

        let pages = build_pages(&sources, &opts);
        let index = synthesize_index(&pages, &opts);

        let order: Vec<&str> = index
            .contents_links
            .iter()
            .map(|l| l.href.as_str())
            .collect();
        assert_eq!(order, ["new.html", "mid.html", "old.html"]);

        let y26 = index.rendered_body.find("2026").expect("a 2026 heading");
        let y25 = index.rendered_body.find("2025").expect("a 2025 heading");
        let y24 = index.rendered_body.find("2024").expect("a 2024 heading");
        assert!(y26 < y25 && y25 < y24, "groups run newest to oldest");
    }

    /// Month grain cuts the same ISO prefix the app's lens does.
    #[test]
    fn a_month_grain_cuts_to_the_month() {
        let sources = vec![
            src("a.md", &entry("A", "2026-07-27"), false),
            src("b.md", &entry("B", "2026-08-01"), false),
        ];
        let opts = SiteOptions {
            arrangement: Arrangement::Grouped(date_grouping(Grain::Month)),
            ..SiteOptions::default()
        };
        let index = synthesize_index(&build_pages(&sources, &opts), &opts);
        assert!(index.rendered_body.contains("2026-08"));
        assert!(index.rendered_body.contains("2026-07"));
    }

    /// A field arrangement groups by the field's values, accepting both the
    /// scalar and the list spelling, and files a document under each value it
    /// carries.
    #[test]
    fn a_field_arrangement_groups_by_value() {
        let scalar = "---\ntitle: Lunch\npeople: Nan\n---\nBody.\n";
        let list = "---\ntitle: Trip\npeople:\n  - Nan\n  - Grandpa\n---\nBody.\n";
        let sources = vec![src("lunch.md", scalar, false), src("trip.md", list, false)];
        let opts = SiteOptions {
            arrangement: Arrangement::Grouped(Grouping::field("people")),
            ..SiteOptions::default()
        };

        let pages = build_pages(&sources, &opts);
        assert_eq!(
            pages
                .iter()
                .find(|p| p.title == "Lunch")
                .unwrap()
                .group_keys,
            vec!["Nan".to_string()],
            "a scalar field value groups like a one-element list"
        );

        let index = synthesize_index(&pages, &opts);
        assert!(index.rendered_body.contains(r#"<h2 id="grandpa">Grandpa "#));
        assert!(index.rendered_body.contains(r#"<h2 id="nan">Nan "#));
        // The trip is filed under both people it names.
        let trips = index.rendered_body.matches("trip.html").count();
        assert_eq!(trips, 2, "one entry per group it belongs to");
    }

    /// A page carrying nothing to group by lands in a bucket rather than being
    /// dropped: an entry missing its date must still be reachable.
    #[test]
    fn an_entry_with_no_grouping_value_is_still_listed() {
        let sources = vec![
            src("dated.md", &entry("Dated", "2026-07-27"), false),
            src("undated.md", "---\ntitle: Undated\n---\nBody.\n", false),
        ];
        let opts = SiteOptions {
            arrangement: Arrangement::Grouped(date_grouping(Grain::Year)),
            ..SiteOptions::default()
        };
        let index = synthesize_index(&build_pages(&sources, &opts), &opts);
        assert!(index.rendered_body.contains("undated.html"));
        assert!(index.rendered_body.contains(UNGROUPED));
    }

    /// The generated index lists the entries; syndicating it as well would put
    /// a copy of the whole site at the top of every reader.
    #[test]
    fn a_generated_index_stays_out_of_the_feed() {
        let sources = vec![src("mon.md", &entry("Monday", "2026-07-27"), false)];
        let opts = SiteOptions {
            base_url: Some("https://example.test".to_string()),
            ..SiteOptions::default()
        };
        let index = synthesize_index(&build_pages(&sources, &opts), &opts);
        assert!(index.hide_from_feed);

        let out = render_site(&sources, &opts);
        let feed = out
            .assets
            .iter()
            .find(|(n, _)| n == "feed.xml")
            .map(|(_, b)| String::from_utf8_lossy(b).into_owned())
            .expect("a feed");
        assert!(feed.contains("mon.html"));
        assert!(!feed.contains("index.html"), "the index is not an entry");
    }

    /// Under a containment arrangement the generated index lists the forest
    /// roots and lets hierarchy show the rest — it does not flatten a vault
    /// that still has a shape.
    #[test]
    fn a_containment_index_lists_the_forest_roots() {
        let parent_doc = "---\ntitle: Daily\ncontents:\n  - \"/mon.md\"\n---\nBody.\n";
        let child = "---\ntitle: Monday\npart_of: \"/daily.md\"\n---\nBody.\n";
        let loose = "---\ntitle: Loose\n---\nBody.\n";
        let sources = vec![
            src("daily.md", parent_doc, false),
            src("mon.md", child, false),
            src("loose.md", loose, false),
        ];

        let opts = SiteOptions::default();
        let index = synthesize_index(&build_pages(&sources, &opts), &opts);

        let listed: Vec<&str> = index
            .contents_links
            .iter()
            .map(|l| l.href.as_str())
            .collect();
        assert_eq!(
            listed,
            ["daily.html", "loose.html"],
            "the nested child is reached through its parent, not listed twice"
        );

        // And the rendered nav nests the child under its parent.
        let out = render_site(&sources, &opts);
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home.html.contains("mon.html"), "still reachable in nav");
    }

    // ── Shell template, layout, per-page assets ─────────────────────────────

    /// A shell template replaces the built-in document. The slots it fills are
    /// the ones the built-in one fills, so nothing about the page is invisible
    /// to it — including the nav, which the entries still appear in.
    #[test]
    fn a_template_replaces_the_built_in_shell() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/child.md\"\n---\nHi.\n";
        let child = "---\ntitle: Child\npart_of: \"/index.md\"\n---\nKid.\n";
        let sources = vec![src("index.md", index, true), src("child.md", child, false)];

        let out = render_site(
            &sources,
            &SiteOptions {
                template: Some(
                    "<!DOCTYPE html>\n<html lang=\"{{lang}}\"><head><title>{{document_title}}</title>{{{head}}}</head>\
                     <body class=\"{{body_class}}\">{{{site_nav}}}<article>{{{content}}}</article>{{{scripts}}}</body></html>"
                        .to_string(),
                ),
                lang: "cy".to_string(),
                ..SiteOptions::default()
            },
        );

        assert!(out.template_error.is_none(), "{:?}", out.template_error);
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home.html.contains(r#"<html lang="cy">"#));
        assert!(
            home.html.contains("<title>Home</title>"),
            "got {}",
            home.html
        );
        assert!(home.html.contains(r#"<body class="has-site-nav">"#));
        assert!(home.html.contains("child.html"), "the nav is still there");
        assert!(
            !home.html.contains(r#"<div class="site-content">"#),
            "and the built-in furniture the template did not ask for is not"
        );
    }

    /// A theme that will not compile costs the site its design, not its
    /// publication — and says why.
    #[test]
    fn a_broken_template_falls_back_and_reports_itself() {
        let sources = vec![src("index.md", "---\ntitle: Home\n---\nHi.\n", true)];
        let out = render_site(
            &sources,
            &SiteOptions {
                template: Some("<html>{{contnet}}</html>".to_string()),
                ..SiteOptions::default()
            },
        );

        let error = out.template_error.expect("the reason it was ignored");
        assert!(error.contains("unknown shell slot `contnet`"), "{error}");
        assert!(
            out.pages[0].html.contains(r#"<div class="site-content">"#),
            "the built-in shell"
        );
    }

    /// `layout: bare` is a page that carries its own design. It still belongs to
    /// the site — nav, sitemap and feeds all know it — it just is not wearing
    /// the site's frame.
    #[test]
    fn a_bare_page_keeps_its_place_in_the_site() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/poster.md\"\n---\nHi.\n";
        let poster = "---\ntitle: Poster\npart_of: \"/index.md\"\nlayout: bare\nstyles:\n  - \"/assets/poster.css\"\n---\nArt.\n";
        let sources = vec![
            src("index.md", index, true),
            src("poster.md", poster, false),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let bare = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "poster.html")
            .unwrap();
        assert!(bare.html.starts_with("<!DOCTYPE html>"));
        assert!(bare.html.contains(r#"href="assets/poster.css""#));
        assert!(!bare.html.contains("site-nav"), "no frame: {}", bare.html);
        assert!(!bare.html.contains("style.css"), "no site stylesheet");

        // …and the site still lists it.
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home.html.contains("poster.html"));
    }

    /// `layout: verbatim` publishes the body unread. Asserted as an equality
    /// over a whole document rather than a handful of `contains`, because the
    /// promise is about *bytes*: everything twig would change on the way through
    /// — attribute order, void-tag spelling, entity normalization, the exact
    /// whitespace of an inline `<script>` — is a difference this test exists to
    /// catch and no substring assertion can see.
    #[test]
    fn a_verbatim_page_is_published_byte_for_byte() {
        // Every shape the pipeline would otherwise touch: a `{{handlebars}}`
        // expression, a `.md` link, a vault-root-absolute asset path, an
        // `==highlight==`, an `![embed](x.html)`, a script full of braces and
        // angle brackets, an unclosed void tag, and single-quoted attributes.
        let mut body = String::from(
            "<!doctype html>\n\
             <html lang=\"en\" data-theme='dark'>\n\
             <head>\n\
             <meta charset=utf-8>\n\
             <title>Diaryx — {{ not a template }}</title>\n\
             <style>.a{color:red}.b{color:blue}</style>\n\
             </head>\n\
             <body>\n\
             <img src=\"/img/hero.png\" alt=\"a ==highlight== and ![an](embed.html)\">\n\
             <a href=\"/about.md\">about</a>\n\
             <script>if (a<b && c>d) { f({x: 1}); }</script>\n",
        );
        for i in 0..400 {
            body.push_str(&format!(
                "<p class='row' data-i={i}>Line {i} &amp; more<br>\n"
            ));
        }
        body.push_str("</body>\n</html>\n");

        let source = format!("---\ntitle: Front\nlayout: verbatim\n---\n{body}");
        let sources = vec![src("index.md", &source, true)];
        let out = render_site(&sources, &SiteOptions::default());

        let page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert_eq!(page.html, body, "the body is the file");
    }

    /// A verbatim page is still a page: the site knows it, links to it, and
    /// syndicates it exactly as it would any other. `verbatim` is a statement
    /// about the bytes, not about membership.
    #[test]
    fn a_verbatim_page_keeps_its_place_in_the_site() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/landing.md\"\n---\nHi.\n";
        let landing =
            "---\ntitle: Landing\npart_of: \"/index.md\"\nlayout: verbatim\n---\n<h1>Hi</h1>\n";
        let sources = vec![
            src("index.md", index, true),
            src("landing.md", landing, false),
        ];

        let opts = SiteOptions {
            base_url: Some("https://example.test".to_string()),
            ..SiteOptions::default()
        };
        let out = render_site(&sources, &opts);

        let landing_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "landing.html")
            .unwrap();
        assert_eq!(landing_page.html, "<h1>Hi</h1>\n");

        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home.html.contains("landing.html"), "listed in the nav");

        let sitemap = out
            .assets
            .iter()
            .find(|(n, _)| n == "sitemap.xml")
            .map(|(_, b)| String::from_utf8_lossy(b).into_owned())
            .expect("a sitemap");
        assert!(sitemap.contains("landing.html"));
    }

    /// `styles:`/`scripts:` are asset references like any other: written from
    /// the vault root or relative to the document, and resolved to one path
    /// below the site root — then rebased to the depth of each page that names
    /// them, so a nested entry and the front page point at the same file.
    #[test]
    fn page_assets_resolve_and_rebase_like_attachments() {
        let front = "---\ntitle: Home\nstyles:\n  - \"/assets/site.css\"\nscripts:\n  - \"assets/site.js\"\n---\nHi.\n";
        let deep = "---\ntitle: Deep\nstyles:\n  - \"../assets/site.css\"\n---\nBody.\n";
        let sources = vec![
            src("index.md", front, true),
            src("notes/deep.md", deep, false),
        ];

        let out = render_site(&sources, &SiteOptions::default());

        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert_eq!(home.styles, vec!["assets/site.css".to_string()]);
        assert_eq!(home.scripts, vec!["assets/site.js".to_string()]);
        assert!(
            home.html
                .contains(r#"<link rel="stylesheet" href="assets/site.css">"#)
        );
        assert!(
            home.html
                .contains(r#"<script defer src="assets/site.js"></script>"#)
        );

        let deep_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "notes/deep.html")
            .unwrap();
        assert_eq!(
            deep_page.styles,
            vec!["assets/site.css".to_string()],
            "one file, however the document spelled its way to it"
        );
        assert!(
            deep_page
                .html
                .contains(r#"<link rel="stylesheet" href="../assets/site.css">"#),
            "rebased to the page's own depth: {}",
            deep_page.html
        );
    }

    // ── `serve_at` ──────────────────────────────────────────────────────────

    /// The normalizations, one by one: a leading `/` is required, `.html` is
    /// implied, components are sanitized, and nothing reaches above the site
    /// root.
    #[test]
    fn serve_at_normalizes_a_site_root_claim() {
        assert_eq!(serve_at_dest("/privacy"), Some("privacy.html".to_string()));
        assert_eq!(
            serve_at_dest("/privacy.html"),
            Some("privacy.html".to_string()),
            "the two spellings are one claim"
        );
        assert_eq!(
            serve_at_dest("  /legal/privacy  "),
            Some("legal/privacy.html".to_string())
        );
        assert_eq!(
            serve_at_dest("/My Page!"),
            Some("My Page.html".to_string()),
            "sanitized like every other published path"
        );
        assert_eq!(
            serve_at_dest("/../../etc/passwd"),
            Some("etc/passwd.html".to_string()),
            "there is nothing above a site's root to reach"
        );
        // Not a claim at all.
        assert_eq!(serve_at_dest("privacy.html"), None, "must be site-absolute");
        assert_eq!(serve_at_dest("/"), None);
        assert_eq!(serve_at_dest(""), None);
    }

    /// A document declaring `serve_at:` publishes where it says, and everything
    /// downstream follows it: the nav, the body links that point at it, the
    /// sitemap.
    #[test]
    fn a_serve_at_page_publishes_where_it_claims() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/docs/privacy.md\"\n---\nSee [the policy](/docs/privacy.md).\n";
        let privacy =
            "---\ntitle: Privacy\npart_of: \"/index.md\"\nserve_at: /privacy\n---\nThe policy.\n";
        let sources = vec![
            src("index.md", index, true),
            src("docs/privacy.md", privacy, false),
        ];

        let opts = SiteOptions {
            base_url: Some("https://example.test".to_string()),
            ..SiteOptions::default()
        };
        let pages = build_pages(&sources, &opts);
        let page = pages.iter().find(|p| p.title == "Privacy").unwrap();
        assert_eq!(page.dest_filename, "privacy.html");

        let home = pages.iter().find(|p| p.is_root).unwrap();
        assert_eq!(home.contents_links[0].href, "privacy.html");
        assert!(
            home.rendered_body.contains(r#"href="privacy.html""#),
            "a body link follows the claim: {}",
            home.rendered_body
        );

        let out = render_site(&sources, &opts);
        assert!(
            out.pages.iter().any(|p| p.dest_filename == "privacy.html"),
            "the rendered page is written at the claimed key"
        );
        let sitemap = out
            .assets
            .iter()
            .find(|(n, _)| n == "sitemap.xml")
            .map(|(_, b)| String::from_utf8_lossy(b).into_owned())
            .unwrap();
        assert!(sitemap.contains("privacy.html"));
        assert!(!sitemap.contains("docs/privacy.html"));
    }

    /// A claim is site-root-absolute, so a page at depth linking to it gets a
    /// path back up to the root — not one relative to where the target's
    /// *source* sits.
    #[test]
    fn a_link_from_depth_to_a_serve_at_page_is_rebased() {
        let index = "---\ntitle: Home\n---\nHi.\n";
        let about =
            "---\ntitle: About\npart_of: \"/index.md\"\n---\nSee [privacy](../docs/privacy.md).\n";
        let privacy = "---\ntitle: Privacy\nserve_at: /privacy.html\n---\nThe policy.\n";
        let sources = vec![
            src("index.md", index, true),
            src("about/index.md", about, false),
            src("docs/privacy.md", privacy, false),
        ];

        let pages = build_pages(&sources, &SiteOptions::default());
        let about_page = pages.iter().find(|p| p.title == "About").unwrap();
        assert_eq!(about_page.dest_filename, "about/index.html");
        assert!(
            about_page
                .rendered_body
                .contains(r#"href="../privacy.html""#),
            "got {}",
            about_page.rendered_body
        );
    }

    /// The site's index is `index.html` by definition — it is the front door,
    /// not a page with an address — so a `serve_at:` on it claims nothing.
    #[test]
    fn the_site_index_ignores_serve_at() {
        let index = "---\ntitle: Home\nserve_at: /home.html\n---\nHi.\n";
        let sources = vec![src("index.md", index, true)];

        let pages = build_pages(&sources, &SiteOptions::default());
        assert_eq!(pages[0].dest_filename, "index.html");
        assert_eq!(dest_of(&sources[0]), "index.html");
    }

    /// [`dest_of`] is the rule the render applies, asked before the render —
    /// which is the only reason it is public.
    #[test]
    fn dest_of_answers_for_a_source_the_way_the_render_will() {
        let claimed = src(
            "docs/privacy.md",
            "---\ntitle: Privacy\nserve_at: /privacy\n---\nBody.\n",
            false,
        );
        let plain = src("docs/note.md", "---\ntitle: Note\n---\nBody.\n", false);
        assert_eq!(dest_of(&claimed), "privacy.html");
        assert_eq!(dest_of(&plain), "docs/note.html");

        let pages = build_pages(&[claimed, plain], &SiteOptions::default());
        assert_eq!(pages[0].dest_filename, "privacy.html");
        assert_eq!(pages[1].dest_filename, "docs/note.html");
    }

    // ── per-page `shell:` ───────────────────────────────────────────────────

    fn templates(pairs: &[(&str, &str)]) -> IndexMap<String, String> {
        pairs
            .iter()
            .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
            .collect()
    }

    const POSTER: &str = "<!DOCTYPE html><html lang=\"{{lang}}\"><head><title>{{document_title}}</title>\
         {{{head}}}</head><body class=\"poster\">{{{content}}}</body></html>";

    /// A page naming a shell wears it; the rest of the site keeps its own.
    #[test]
    fn a_page_may_name_its_own_shell() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/poster.md\"\n---\nHi.\n";
        let poster =
            "---\ntitle: Poster\npart_of: \"/index.md\"\nshell: themes/poster.html\n---\nArt.\n";
        let sources = vec![
            src("index.md", index, true),
            src("poster.md", poster, false),
        ];

        let out = render_site(
            &sources,
            &SiteOptions {
                template: Some(
                    "<!DOCTYPE html><html><body class=\"site\">{{{content}}}</body></html>"
                        .to_string(),
                ),
                templates: templates(&[("themes/poster.html", POSTER)]),
                ..SiteOptions::default()
            },
        );

        assert!(out.template_error.is_none());
        assert!(
            out.page_shell_errors.is_empty(),
            "{:?}",
            out.page_shell_errors
        );

        let page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "poster.html")
            .unwrap();
        assert!(
            page.html.contains(r#"<body class="poster">"#),
            "{}",
            page.html
        );
        assert!(page.html.contains("<title>Poster - Home</title>"));

        // …and the site's own shell is untouched by the page that opted out.
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home.html.contains(r#"<body class="site">"#));
    }

    /// A page naming a shell the site does not carry falls back to the site's
    /// and says so — the bargain a broken site template already gets.
    #[test]
    fn a_missing_page_shell_falls_back_and_reports_itself() {
        let poster = "---\ntitle: Poster\nshell: themes/gone.html\n---\nArt.\n";
        let sources = vec![src("poster.md", poster, false)];

        let out = render_site(
            &sources,
            &SiteOptions {
                template: Some(
                    "<!DOCTYPE html><html><body class=\"site\">{{{content}}}</body></html>"
                        .to_string(),
                ),
                ..SiteOptions::default()
            },
        );

        assert_eq!(out.page_shell_errors.len(), 1);
        let report = &out.page_shell_errors[0];
        assert!(report.contains("poster.md"), "{report}");
        assert!(report.contains("themes/gone.html"), "{report}");
        let page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "poster.html")
            .unwrap();
        assert!(page.html.contains(r#"<body class="site">"#));
    }

    /// A page shell that will not compile costs that page its design, not the
    /// site's publication — and is reported once however many pages named it.
    #[test]
    fn a_broken_page_shell_is_reported_once_for_the_shell() {
        let one = "---\ntitle: One\nshell: themes/poster.html\n---\nA.\n";
        let two = "---\ntitle: Two\nshell: themes/poster.html\n---\nB.\n";
        let sources = vec![src("one.md", one, false), src("two.md", two, false)];

        let out = render_site(
            &sources,
            &SiteOptions {
                templates: templates(&[("themes/poster.html", "<html>{{contnet}}</html>")]),
                ..SiteOptions::default()
            },
        );

        assert_eq!(
            out.page_shell_errors.len(),
            1,
            "one broken template is one report: {:?}",
            out.page_shell_errors
        );
        assert!(
            out.page_shell_errors[0].contains("unknown shell slot `contnet`"),
            "{:?}",
            out.page_shell_errors
        );
        assert!(out.template_error.is_none(), "the site's shell is fine");
        for page in &out.pages {
            assert!(
                page.html.contains(r#"<div class="site-content">"#),
                "the built-in shell"
            );
        }
    }

    /// The site's own shell keeps its own error channel, and a page's failure
    /// does not appear in it.
    #[test]
    fn a_page_shell_does_not_disturb_the_site_shells_report() {
        let sources = vec![src(
            "poster.md",
            "---\ntitle: Poster\nshell: themes/gone.html\n---\nArt.\n",
            false,
        )];
        let out = render_site(
            &sources,
            &SiteOptions {
                template: Some("<html>{{contnet}}</html>".to_string()),
                ..SiteOptions::default()
            },
        );
        assert!(
            out.template_error
                .as_deref()
                .is_some_and(|e| e.contains("unknown shell slot")),
            "{:?}",
            out.template_error
        );
        assert_eq!(out.page_shell_errors.len(), 1);
    }

    /// `bare` and `verbatim` carry their own frame, so a `shell:` on one of
    /// them applies to nothing — and is not reported as missing either.
    #[test]
    fn a_bare_or_verbatim_page_takes_no_page_shell() {
        let bare = "---\ntitle: Bare\nlayout: bare\nshell: themes/gone.html\n---\nArt.\n";
        let verbatim =
            "---\ntitle: Verbatim\nlayout: verbatim\nshell: themes/poster.html\n---\n<h1>Hi</h1>\n";
        let sources = vec![
            src("bare.md", bare, false),
            src("verbatim.md", verbatim, false),
        ];

        let out = render_site(
            &sources,
            &SiteOptions {
                templates: templates(&[("themes/poster.html", POSTER)]),
                ..SiteOptions::default()
            },
        );

        assert!(
            out.page_shell_errors.is_empty(),
            "nothing was going to wear it: {:?}",
            out.page_shell_errors
        );
        let verbatim_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "verbatim.html")
            .unwrap();
        assert_eq!(verbatim_page.html, "<h1>Hi</h1>\n");
        let bare_page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "bare.html")
            .unwrap();
        assert!(!bare_page.html.contains("class=\"poster\""));
    }

    /// A page shell and a `serve_at:` on the same document are independent
    /// claims, and both hold.
    #[test]
    fn a_page_may_claim_a_shell_and_a_destination_at_once() {
        let poster =
            "---\ntitle: Poster\nserve_at: /poster\nshell: themes/poster.html\n---\nArt.\n";
        let sources = vec![src("deep/nested/poster.md", poster, false)];

        let out = render_site(
            &sources,
            &SiteOptions {
                templates: templates(&[("themes/poster.html", POSTER)]),
                ..SiteOptions::default()
            },
        );

        let page = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "poster.html")
            .expect("the claimed destination");
        assert!(page.html.contains(r#"<body class="poster">"#));
    }

    // ── per-page `lang:` ────────────────────────────────────────────────────

    /// The language a document is in is a fact about the document, so the site's
    /// tag is a default rather than an answer — and a page that says otherwise
    /// is published in what it said, without disturbing the pages that did not.
    #[test]
    fn a_page_may_declare_its_own_language() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/letter.md\"\n---\nHi.\n";
        let letter = "---\ntitle: Letter\npart_of: \"/index.md\"\nlang: '  cy  '\n---\nBore da.\n";
        let sources = vec![
            src("index.md", index, true),
            src("letter.md", letter, false),
        ];

        let out = render_site(
            &sources,
            &SiteOptions {
                lang: "en".to_string(),
                ..SiteOptions::default()
            },
        );

        let page = |name: &str| {
            out.pages
                .iter()
                .find(|p| p.dest_filename == name)
                .unwrap()
                .html
                .clone()
        };
        assert!(page("letter.html").contains(r#"<html lang="cy">"#));
        assert!(
            page("index.html").contains(r#"<html lang="en">"#),
            "and the site's own tag is untouched by the page that declared one"
        );
    }

    /// `lang:` with nothing after it is a key left in place, not a claim that
    /// the page is in no language at all — which is what `<html lang="">` says.
    #[test]
    fn a_blank_page_language_reads_as_absent() {
        let sources = vec![src(
            "index.md",
            "---\ntitle: Home\nlang: '   '\n---\nHi.\n",
            true,
        )];

        let out = render_site(
            &sources,
            &SiteOptions {
                lang: "en".to_string(),
                ..SiteOptions::default()
            },
        );

        assert!(out.pages[0].html.contains(r#"<html lang="en">"#));
    }

    /// A synthesized index has no frontmatter to declare one, and nothing to
    /// inherit from either: it is the site speaking about itself.
    #[test]
    fn a_synthesized_index_keeps_the_sites_language() {
        let sources = vec![src(
            "letter.md",
            "---\ntitle: Letter\nlang: cy\n---\nBore da.\n",
            false,
        )];

        let out = render_site(
            &sources,
            &SiteOptions {
                lang: "en".to_string(),
                ..SiteOptions::default()
            },
        );

        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .expect("a synthesized front page");
        assert!(home.html.contains(r#"<html lang="en">"#), "{}", home.html);
    }

    #[test]
    fn render_site_produces_pages_nav_and_assets() {
        let index = "---\ntitle: Home\ncontents:\n  - \"[Child](/child.md)\"\n---\nHi.\n";
        let child = "---\ntitle: Child\npart_of: \"/index.md\"\n---\nKid.\n";
        let sources = vec![src("index.md", index, true), src("child.md", child, false)];

        let out = render_site(&sources, &SiteOptions::default());

        assert_eq!(out.pages.len(), 2);
        // index page carries the site nav with a link to the child
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        assert!(home.html.contains("site-nav"));
        assert!(home.html.contains("child.html"));
        assert!(home.html.contains("<!DOCTYPE html>"));

        // assets include the stylesheet
        assert!(out.assets.iter().any(|(n, _)| n == "style.css"));
    }

    /// The whole point of widening the context: a page can list the other
    /// pages, which is the thing no amount of template *engine* could fix.
    #[test]
    fn a_page_can_list_the_sites_entries() {
        let index =
            "---\ntitle: Home\n---\n:::each{of=entries as=e}\n- [:val[e.title]]({{e.href}})\n:::\n";
        let sources = vec![
            src("index.md", index, true),
            src("a.md", "---\ntitle: Alpha\n---\nA.\n", false),
            src("b.md", "---\ntitle: Beta\n---\nB.\n", false),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();

        let content = &home.html[home.html.find(r#"<div class="content">"#).unwrap()..];
        assert!(
            content.contains(r#"<li><a href="a.html">Alpha</a></li>"#),
            "the link survives the rewrite: {content}"
        );
        assert!(home.html.contains("Beta"), "got {}", home.html);
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );
    }

    /// A listing can dress each entry in its own colour: the entry carries
    /// the word, the attribute carries it to the element, and the element is
    /// what a stylesheet sees.
    #[test]
    fn a_page_can_dress_each_child_in_its_color() {
        let index = "---\ntitle: Home\ncontents:\n- '[Lake](lake.md)'\n- '[Kitchen](kitchen.md)'\n---\n\
                     :::each{of=children as=book}\n\
                     :::article{class=\"cover tone-{{book.color}}\"}\n\
                     [:val[book.title]]({{book.href}})\n\
                     :::\n\
                     :::\n";
        let sources = vec![
            src("index.md", index, true),
            src("lake.md", "---\ntitle: Lake\ncolor: blue\n---\nA.\n", false),
            src(
                "kitchen.md",
                "---\ntitle: Kitchen\ncolor: green\n---\nB.\n",
                false,
            ),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();

        let content = &home.html[home.html.find(r#"<div class="content">"#).unwrap()..];
        assert!(
            content.contains(r#"<article class="cover tone-blue">"#),
            "{content}"
        );
        assert!(
            content.contains(r#"<article class="cover tone-green">"#),
            "{content}"
        );
        assert!(
            content.contains(r#"<a href="lake.html">Lake</a>"#),
            "{content}"
        );
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );
    }

    /// `groups` comes back in prov's order — ascending by key — however the
    /// sources happened to be handed over. Source order was the old rule, and
    /// it made the same archive read two ways depending on which document the
    /// walk reached first.
    #[test]
    fn a_templates_groups_are_ordered_by_key_not_by_arrival() {
        let index = "---\ntitle: Home\n---\n:::each{of=groups as=g}\n- :val[g.key]\n:::\n";
        let sources = vec![
            src("index.md", index, true),
            src("c.md", "---\ntitle: C\npeople: Nan\n---\nC.\n", false),
            src("a.md", "---\ntitle: A\npeople: Ada\n---\nA.\n", false),
        ];
        let opts = SiteOptions {
            arrangement: Arrangement::Grouped(Grouping::field("people")),
            ..SiteOptions::default()
        };

        let out = render_site(&sources, &opts);
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        let ada = home.html.find("Ada").expect("an Ada group");
        let nan = home.html.find("Nan").expect("a Nan group");
        assert!(
            ada < nan,
            "ascending by key, not `Nan` first: {}",
            home.html
        );
    }

    /// The gate property, tested as a property of the pipeline rather than of a
    /// check: `entries` is built from the sources this render was handed, and
    /// audience exclusion happens before that — so there is no path by which a
    /// withheld document reaches a template. Remove the document, and the
    /// listing simply has nothing to say about it.
    #[test]
    fn a_template_cannot_reach_a_withheld_document() {
        let index = "---\ntitle: Home\n---\n:::each{of=entries as=e}\n- :val[e.title]\n:::\n";
        let admitted = vec![
            src("index.md", index, true),
            src("public.md", "---\ntitle: Public\n---\nP.\n", false),
        ];

        let out = render_site(&admitted, &SiteOptions::default());
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();

        assert!(home.html.contains("Public"), "got {}", home.html);
        assert!(!home.html.contains("Private"), "got {}", home.html);
    }

    /// A backlink is an entry like any other, so a template addresses it with
    /// the same fields and links it with the same href.
    #[test]
    fn backlinks_are_entries_the_linked_page_can_list() {
        let body = "---\ntitle: Beta\n---\n:::each{of=backlinks as=b}\n- [:val[b.title]]({{b.href}})\n:::\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            src("a.md", "---\ntitle: Alpha\n---\nSee [Beta](b.md).\n", false),
            linked("b.md", body, &["a.md"]),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let beta = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "b.html")
            .unwrap();

        assert!(beta.html.contains("Alpha"), "got {}", beta.html);
        assert!(beta.html.contains(r#"href="a.html""#), "got {}", beta.html);
    }

    /// One document, however many times it links here. The collector counts
    /// link *sites* — a `related:` and a sentence of prose are two — and the
    /// ordering is by path so two builds of one archive agree.
    #[test]
    fn backlinks_name_each_linking_document_once_and_in_path_order() {
        let body = "---\ntitle: Beta\n---\n:::each{of=backlinks as=b}\n:val[b.path];\n:::\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            src("z.md", "---\ntitle: Zed\n---\nZ.\n", false),
            src("a.md", "---\ntitle: Alpha\n---\nA.\n", false),
            linked("b.md", body, &["z.md", "a.md", "a.md"]),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let beta = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "b.html")
            .unwrap();

        let listed: Vec<&str> = beta
            .html
            .split(';')
            .filter_map(|chunk| ["a.md", "z.md"].into_iter().find(|p| chunk.contains(p)))
            .collect();
        assert_eq!(listed, ["a.md", "z.md"], "got {}", beta.html);
    }

    /// The disclosure this key could have been. A page nobody in this render
    /// answers for is not named, so a caller that failed to filter its own
    /// inbound links does not publish the name of a withheld document — and a
    /// page with no backlinks at all lists nothing rather than failing.
    #[test]
    fn a_backlink_to_a_document_outside_this_render_is_not_published() {
        let body = "---\ntitle: Beta\n---\nLinked from:\n:::each{of=backlinks as=b}\n- :val[b.path]\n:::\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            linked("b.md", body, &["private.md"]),
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let beta = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "b.html")
            .unwrap();

        assert!(beta.html.contains("Linked from"), "got {}", beta.html);
        assert!(!beta.html.contains("private"), "got {}", beta.html);
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );
    }

    /// A relation is addressed by **the name the vault gave it**. Nothing in
    /// this crate knows what a `sequel` is; it is a key because the archive
    /// declared one, and `inbound` is a mapping so the dotted path reaches it.
    #[test]
    fn an_inbound_relation_is_addressed_by_the_name_the_vault_gave_it() {
        let body = "---\ntitle: Beta\n---\n:::each{of=inbound.sequel as=s}\n- [:val[s.title]]({{s.href}})\n:::\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            src("a.md", "---\ntitle: Alpha\n---\nA.\n", false),
            SourceDoc {
                inbound: edges(&[("sequel", "a.md")]),
                ..src("b.md", body, false)
            },
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let beta = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "b.html")
            .unwrap();

        assert!(beta.html.contains("Alpha"), "got {}", beta.html);
        assert!(beta.html.contains(r#"href="a.html""#), "got {}", beta.html);
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );
    }

    /// The other direction, and the two rules that keep the vocabulary the
    /// vault's: an edge a page *writes* is under `relations`, and a link written
    /// in prose is under neither — it has no name, and inventing one would take
    /// a name a vault may declare.
    #[test]
    fn an_outbound_relation_is_published_and_a_prose_link_is_not_named_as_one() {
        let body = "---\ntitle: Alpha\n---\nSequels:\n:::each{of=relations.sequel as=s}\n- :val[s.path]\n:::\nProse:\n:::each{of=relations.body as=s}\n- :val[s.path]\n:::\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            src("b.md", "---\ntitle: Beta\n---\nB.\n", false),
            src("c.md", "---\ntitle: Gamma\n---\nC.\n", false),
            SourceDoc {
                outbound: edges(&[("sequel", "b.md")]),
                inbound: vec![LinkEdge {
                    relation: None,
                    path: "c.md".into(),
                }],
                ..src("a.md", body, false)
            },
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let alpha = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "a.html")
            .unwrap();

        assert!(alpha.html.contains("b.md"), "got {}", alpha.html);
        assert!(!alpha.html.contains("c.md"), "got {}", alpha.html);
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );
    }

    /// `backlinks` is unchanged by any of it: the flat union of the typed and
    /// the prose, each document once.
    #[test]
    fn backlinks_stay_the_union_of_the_typed_and_the_untyped() {
        let body = "---\ntitle: Beta\n---\n:::each{of=backlinks as=b}\n:val[b.path];\n:::\n";
        let mut beta = src("b.md", body, false);
        beta.inbound = edges(&[("sequel", "z.md")]);
        beta.inbound.push(LinkEdge {
            relation: None,
            path: "a.md".into(),
        });
        // The same document twice, in a relation and in prose: one entry.
        beta.inbound.push(LinkEdge {
            relation: Some("sequel".into()),
            path: "a.md".into(),
        });
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            src("z.md", "---\ntitle: Zed\n---\nZ.\n", false),
            src("a.md", "---\ntitle: Alpha\n---\nA.\n", false),
            beta,
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let beta = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "b.html")
            .unwrap();

        let listed: Vec<&str> = beta
            .html
            .split(';')
            .filter_map(|chunk| ["a.md", "z.md"].into_iter().find(|p| chunk.contains(p)))
            .collect();
        assert_eq!(listed, ["a.md", "z.md"], "got {}", beta.html);
    }

    /// A relation every one of whose targets this render cannot answer for
    /// produces no key at all. The list would render as nothing either way; the
    /// key would still be a statement that the edge exists.
    #[test]
    fn a_relation_pointing_only_outside_this_render_leaves_no_key() {
        let body = "---\ntitle: Alpha\n---\n:::if{has=relations.sequel}\nHas a sequel.\n:::\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nH.\n", true),
            SourceDoc {
                outbound: edges(&[("sequel", "private.md")]),
                ..src("a.md", body, false)
            },
        ];

        let out = render_site(&sources, &SiteOptions::default());
        let alpha = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "a.html")
            .unwrap();

        assert!(!alpha.html.contains("Has a sequel"), "got {}", alpha.html);
        assert!(!alpha.html.contains("private"), "got {}", alpha.html);
    }

    /// The `{{ }}` migration: a brace outside a link destination publishes as
    /// itself and names its own page, rather than vanishing or being
    /// substituted.
    #[test]
    fn a_stray_brace_is_reported_against_the_page_that_wrote_it() {
        let index = "---\ntitle: Home\n---\nWelcome to {{ title }}.\n";
        let sources = vec![src("index.md", index, true)];

        let out = render_site(&sources, &SiteOptions::default());
        let home = &out.pages[0];

        assert!(home.html.contains("{{ title }}"), "got {}", home.html);
        assert_eq!(out.body_template_errors.len(), 1);
        assert!(
            out.body_template_errors[0].starts_with("index.md:"),
            "{:?}",
            out.body_template_errors
        );
    }

    /// A body template that will not expand publishes its own source — and
    /// says so, which is the half that used to be missing.
    #[test]
    fn a_broken_body_template_is_reported_rather_than_swallowed() {
        let index = "---\ntitle: Home\n---\n:::if{equals=title}\nX\n:::\n";
        let sources = vec![src("index.md", index, true)];

        let out = render_site(&sources, &SiteOptions::default());

        assert_eq!(out.body_template_errors.len(), 1);
        assert!(
            out.body_template_errors[0].contains("equals"),
            "{:?}",
            out.body_template_errors
        );
    }

    #[test]
    fn a_page_can_name_its_parent_children_and_trail() {
        let index = "---\ntitle: Home\ncontents:\n  - \"[Child](/child.md)\"\n---\n:::each{of=children as=c}\n- :val[c.title]\n:::\n";
        let child = "---\ntitle: Child\npart_of: \"/index.md\"\n---\nparent: :val[parent.title]\n\n:::each{of=breadcrumbs as=b}\n- :val[b.title]\n:::\n";
        let sources = vec![src("index.md", index, true), src("child.md", child, false)];

        let out = render_site(&sources, &SiteOptions::default());
        let home = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "index.html")
            .unwrap();
        let kid = out
            .pages
            .iter()
            .find(|p| p.dest_filename == "child.html")
            .unwrap();

        assert!(home.html.contains("<li>Child</li>"), "got {}", home.html);
        assert!(kid.html.contains("parent: Home"), "got {}", kid.html);
        // Root first, this page last.
        let trail = kid
            .html
            .find("<li>Home</li>")
            .zip(kid.html.find("<li>Child</li>"));
        let (root_at, self_at) = trail.unwrap_or_else(|| panic!("got {}", kid.html));
        assert!(root_at < self_at, "got {}", kid.html);
    }

    /// The whole hand-off, end to end. These sources say nothing about what
    /// contains what — the vault spells its spine through some other relation,
    /// and `plates` walked it — so the sidebar, the breadcrumb trail and the
    /// `parent` a template names exist only because the outline was passed in.
    #[test]
    fn the_site_nests_by_the_outline_it_is_given() {
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nHi.\n", true),
            src("letters.md", "---\ntitle: Letters\n---\nBody.\n", false),
            src(
                "letters/first.md",
                "---\ntitle: The First Letter\n---\nin: :val[parent.title]\n",
                false,
            ),
        ];
        let outline = vec![OutlineNode {
            path: "index.md".into(),
            label: None,
            children: vec![OutlineNode {
                path: "letters.md".into(),
                label: None,
                children: vec![OutlineNode {
                    path: "letters/first.md".into(),
                    label: None,
                    children: Vec::new(),
                }],
            }],
        }];

        let letter = |opts: &SiteOptions| {
            render_site(&sources, opts)
                .pages
                .into_iter()
                .find(|p| p.dest_filename == "letters/first.html")
                .expect("the letter")
                .html
        };

        // The breadcrumb trail alone: the sidebar names every page either way,
        // so it is the trail that says where this one *sits*.
        let trail = |html: &str| {
            let start = html
                .find(r#"<nav class="breadcrumbs""#)
                .expect("a breadcrumb trail");
            let end = html[start..].find("</nav>").expect("a closed one") + start;
            html[start..end].to_string()
        };

        let placed = letter(&SiteOptions {
            outline,
            ..SiteOptions::default()
        });
        assert!(
            trail(&placed).contains(">Letters</a>"),
            "the trail the archive's own hierarchy gives it: {}",
            trail(&placed)
        );
        assert!(
            placed.contains("in: Letters"),
            "and the same answer where a template asks for it: {placed}"
        );

        // Without it, the same sources are three pages that know nothing about
        // each other — which is all this crate can see on its own.
        let loose = letter(&SiteOptions::default());
        assert!(
            !trail(&loose).contains(">Letters</a>"),
            "nothing here nests them: {}",
            trail(&loose)
        );
    }
    // ── The site frame: anchors, outline, pager, header and footer ──────────

    fn page_named<'a>(out: &'a SiteRender, dest: &str) -> &'a RenderedPage {
        out.pages
            .iter()
            .find(|p| p.dest_filename == dest)
            .unwrap_or_else(|| panic!("no page at {dest}"))
    }

    /// Every heading on a rendered page carries an `id` and an anchor, in
    /// each grammar, and the outline lists the `h2`–`h3` ones.
    #[test]
    fn headings_are_anchored_and_outlined() {
        let index = "---\ntitle: Home\n---\n# Home\n\n## First\n\ntext\n\n### Inner\n\n## Second\n";
        let djot = "---\ntitle: Note\n---\n## Alpha\n\n## Beta\n";
        let sources = vec![src("index.md", index, true), src("note.dj", djot, false)];
        let out = render_site(&sources, &SiteOptions::default());

        let home = &page_named(&out, "index.html").html;
        assert!(
            home.contains(r##"<h2 id="first">First <a class="heading-anchor" href="#first" aria-label="Link to this section">#</a></h2>"##),
            "got {home}"
        );
        assert!(
            home.contains(r##"<nav class="toc" aria-label="On this page"><details open><summary>On this page</summary><ul><li><a href="#first">First</a><ul><li><a href="#inner">Inner</a></li></ul></li><li><a href="#second">Second</a></li></ul></details></nav>"##),
            "got {home}"
        );

        let note = &page_named(&out, "note.html").html;
        assert!(
            note.contains(r##"<h2 id="alpha">Alpha "##),
            "djot too: {note}"
        );
        assert!(note.contains(r##"<a href="#beta">Beta</a>"##), "got {note}");
    }

    /// One heading is not an outline, and `toc: false` turns the built-in
    /// one off without taking the anchors with it.
    #[test]
    fn the_outline_is_omitted_when_short_or_refused() {
        let short = "---\ntitle: Short\n---\n## Only\n";
        let refused = "---\ntitle: Refused\ntoc: false\n---\n## One\n\n## Two\n";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nHi.\n", true),
            src("short.md", short, false),
            src("refused.md", refused, false),
        ];
        let out = render_site(&sources, &SiteOptions::default());
        assert!(
            !page_named(&out, "short.html")
                .html
                .contains(r#"class="toc""#)
        );
        let refused = &page_named(&out, "refused.html").html;
        assert!(!refused.contains(r#"class="toc""#), "got {refused}");
        assert!(
            refused.contains(r##"<h2 id="one">"##),
            "anchors stay: {refused}"
        );
    }

    /// A page can spell its own outline: `headings` is in the body context,
    /// with the ids the anchors got — which means the body is expanded once
    /// to find them and once more with them in scope.
    #[test]
    fn a_page_can_list_its_own_headings() {
        let body = "---\ntitle: Home\n---\n:::each{of=headings as=h}\n- [:val[h.text]](#{{h.id}})\n:::\n\n## Ben & Co\n\n## Second\n";
        let out = render_site(&[src("index.md", body, true)], &SiteOptions::default());
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );
        let home = &page_named(&out, "index.html").html;
        assert!(
            home.contains(r##"<a href="#ben-co">Ben &amp; Co</a>"##),
            "got {home}"
        );
        assert!(
            home.contains(r##"<a href="#second">Second</a>"##),
            "got {home}"
        );
    }

    /// A verbatim page is published unread, headings included: no anchors, no
    /// outline.
    #[test]
    fn a_verbatim_page_keeps_its_headings_as_written() {
        let verbatim = "---\ntitle: Landing\nlayout: verbatim\n---\n<h2>Raw</h2><h2>Rawer</h2>";
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nHi.\n", true),
            src("landing.html", verbatim, false),
        ];
        let out = render_site(&sources, &SiteOptions::default());
        assert_eq!(
            page_named(&out, "landing.html").html,
            "<h2>Raw</h2><h2>Rawer</h2>"
        );
    }

    /// The pager follows the sidebar's reading order — the front page, then
    /// its subtree depth-first — and `prev`/`next` in the body context are
    /// the same two pages.
    #[test]
    fn the_pager_and_the_context_agree_on_the_reading_order() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/a.md\"\n  - \"/b.md\"\n---\nHi.\n";
        let a = "---\ntitle: A\npart_of: \"/index.md\"\ncontents:\n  - \"/a/kid.md\"\n---\nA. Next: [:val[next.title]]({{next.href}}); prev: :val[prev.title].\n";
        let kid = "---\ntitle: Kid\npart_of: \"/a.md\"\n---\nKid.\n";
        let b = "---\ntitle: B\npart_of: \"/index.md\"\n---\nB.\n";
        let sources = vec![
            src("index.md", index, true),
            src("a.md", a, false),
            src("a/kid.md", kid, false),
            src("b.md", b, false),
        ];
        let out = render_site(&sources, &SiteOptions::default());
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );

        let a = &page_named(&out, "a.html").html;
        assert!(
            a.contains(r#"<a class="pager-prev" rel="prev" href="index.html"><span>Previous</span> Home</a>"#),
            "got {a}"
        );
        assert!(
            a.contains(
                r#"<a class="pager-next" rel="next" href="a/kid.html"><span>Next</span> Kid</a>"#
            ),
            "got {a}"
        );
        assert!(
            a.contains(r#"Next: <a href="a/kid.html">Kid</a>; prev: Home."#),
            "the context names the same neighbours: {a}"
        );

        let kid = &page_named(&out, "a/kid.html").html;
        assert!(
            kid.contains(r#"rel="next" href="../b.html""#),
            "depth-first, rebased: {kid}"
        );
        let b = &page_named(&out, "b.html").html;
        assert!(!b.contains("pager-next"), "the last page has no next: {b}");
    }

    /// A `hide_from_nav` page is in no sequence: no pager, and nothing points
    /// at it.
    #[test]
    fn a_hidden_page_is_in_no_sequence() {
        let sources = vec![
            src("index.md", "---\ntitle: Home\n---\nHi.\n", true),
            src("a.md", "---\ntitle: A\n---\nA.\n", false),
            src(
                "h.md",
                "---\ntitle: H\nhide_from_nav: true\n---\nH.\n",
                false,
            ),
        ];
        let out = render_site(&sources, &SiteOptions::default());
        assert!(!page_named(&out, "h.html").html.contains(r#"class="pager""#));
        assert!(!page_named(&out, "a.html").html.contains("h.html"));
    }

    /// A rootless site's synthesized front page heads the order, so the first
    /// entry's "previous" is the front page.
    #[test]
    fn a_synthesized_front_page_heads_the_reading_order() {
        let sources = vec![
            src("a.md", "---\ntitle: A\n---\nA.\n", false),
            src("b.md", "---\ntitle: B\n---\nB.\n", false),
        ];
        let out = render_site(&sources, &SiteOptions::default());
        let a = &page_named(&out, "a.html").html;
        assert!(a.contains(r#"rel="prev" href="index.html""#), "got {a}");
        let home = &page_named(&out, "index.html").html;
        assert!(home.contains(r#"rel="next" href="a.html""#), "got {home}");
    }

    fn frame(path: &str, source: &str) -> Option<FrameDoc> {
        Some(FrameDoc {
            path: path.to_string(),
            source: source.to_string(),
        })
    }

    /// The header and footer are documents rendered for every page: templated
    /// against that page's context, with links rewritten to its depth.
    #[test]
    fn the_header_and_footer_are_rendered_per_page() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/notes/entry.md\"\n---\nHi.\n";
        let entry = "---\ntitle: Entry\npart_of: \"/index.md\"\n---\nE.\n";
        let opts = SiteOptions {
            site_title: Some("My Site".into()),
            header: frame(
                ".config/sites/docs/header.md",
                "---\ntitle: never published\n---\n- [Home](/index.md)\n- [About](/about.md)\n",
            ),
            footer: frame(
                ".config/sites/docs/footer.md",
                "© :val[site.title] · you are reading :val[page.title]\n",
            ),
            ..SiteOptions::default()
        };
        let out = render_site(
            &[
                src("index.md", index, true),
                src("notes/entry.md", entry, false),
            ],
            &opts,
        );
        assert!(
            out.body_template_errors.is_empty(),
            "{:?}",
            out.body_template_errors
        );

        let home = &page_named(&out, "index.html").html;
        assert!(
            home.contains(r#"<header class="site-header"><ul>"#),
            "the header is a rendered document: {home}"
        );
        assert!(
            home.contains(r#"<a href="index.html">Home</a>"#),
            "got {home}"
        );
        assert!(
            home.contains(
                r#"<span class="unpublished-link" title="This page isn’t published">About</span>"#
            ),
            "a link to a page the site does not publish goes inert: {home}"
        );
        assert!(
            home.contains("© My Site · you are reading Home"),
            "the footer names the page: {home}"
        );
        assert!(
            !home.contains("never published"),
            "the frame's own metadata is unread"
        );

        let entry = &page_named(&out, "notes/entry.html").html;
        assert!(
            entry.contains(r#"<a href="../index.html">Home</a>"#),
            "rebased: {entry}"
        );
        assert!(entry.contains("you are reading Entry"), "got {entry}");
        assert!(
            entry.contains(r#"</footer>"#)
                && entry.contains(r#"<footer class="site-footer"><p>© "#),
            "the footer is inside the shell's footer: {entry}"
        );
    }

    /// A `:vis` region in a frame is filtered for the site's audience, so one
    /// footer can carry a line only one audience sees.
    #[test]
    fn a_frame_is_filtered_for_the_audience() {
        let footer = ":::vis{.family}\nfor family\n:::\n\n:::vis{.public}\nfor everyone\n:::\n";
        let sources = vec![src("index.md", "---\ntitle: Home\n---\nHi.\n", true)];
        let out = render_site(
            &sources,
            &SiteOptions {
                audience: Some("public".into()),
                footer: frame("footer.md", footer),
                ..SiteOptions::default()
            },
        );
        let home = &page_named(&out, "index.html").html;
        assert!(home.contains("for everyone"), "got {home}");
        assert!(!home.contains("for family"), "got {home}");
    }

    /// A frame whose template will not expand publishes its source and says
    /// so, named as the site's header or footer rather than as a page.
    #[test]
    fn a_broken_frame_is_reported_against_the_frame() {
        let sources = vec![src("index.md", "---\ntitle: Home\n---\nHi.\n", true)];
        let out = render_site(
            &sources,
            &SiteOptions {
                header: frame(
                    ".config/sites/docs/header.md",
                    ":::if{equals=title}\nX\n:::\n",
                ),
                ..SiteOptions::default()
            },
        );
        assert_eq!(
            out.body_template_errors.len(),
            1,
            "{:?}",
            out.body_template_errors
        );
        assert!(
            out.body_template_errors[0].starts_with("site header .config/sites/docs/header.md:"),
            "{:?}",
            out.body_template_errors
        );
    }

    /// A site that declares no frame publishes empty frame elements — the
    /// stylesheet collapses them — and the attribution line still lands.
    #[test]
    fn an_undeclared_frame_is_an_empty_slot() {
        let sources = vec![src("index.md", "---\ntitle: Home\n---\nHi.\n", true)];
        let out = render_site(&sources, &SiteOptions::default());
        let home = &page_named(&out, "index.html").html;
        assert!(
            home.contains(r#"<header class="site-header"></header>"#),
            "got {home}"
        );
        assert!(
            home.contains(r#"<footer class="site-footer"></footer>"#),
            "got {home}"
        );
    }

    /// A template names the new slots like any other.
    #[test]
    fn a_template_may_place_the_frame_the_outline_and_the_pager() {
        let index = "---\ntitle: Home\ncontents:\n  - \"/a.md\"\n---\n## One\n\n## Two\n";
        let sources = vec![
            src("index.md", index, true),
            src(
                "a.md",
                "---\ntitle: A\npart_of: \"/index.md\"\n---\nA.\n",
                false,
            ),
        ];
        let out = render_site(
            &sources,
            &SiteOptions {
                template: Some(
                    "<a href=\"{{root_prefix}}index.html\">home</a>[{{{site_header}}}][{{{toc}}}][{{{content}}}][{{{pager}}}][{{{site_footer}}}]"
                        .to_string(),
                ),
                header: frame("h.md", "H\n"),
                footer: frame("f.md", "F\n"),
                ..SiteOptions::default()
            },
        );
        assert!(out.template_error.is_none(), "{:?}", out.template_error);
        let home = &page_named(&out, "index.html").html;
        assert!(
            home.starts_with(r#"<a href="index.html">home</a>[<p>H</p>"#),
            "got {home}"
        );
        assert!(home.contains(r#"[<nav class="toc""#), "got {home}");
        assert!(home.contains(r#"[<nav class="pager""#), "got {home}");
        assert!(home.ends_with("[<p>F</p>\n]"), "got {home}");
    }
}