roteiro 5.13.0

Roteiro: a provenance-tagged knowledge graph for your codebase — structure, intent, and context in one queryable store
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
//! The served half of the OKF viewer (ADR-0022).
//!
//! axum routes over `rto_render::okf::view`, which owns every rule about untrusted
//! content and is compiled by the default build.
//!
//! [`rto_render::okf::view`] decides *what* a reader is shown and what is never
//! emitted; this module is the HTTP around it, exactly as `graph_api` is the
//! served half of the explorer.
//!
//! # It reads a bundle, and only reads it
//!
//! Nothing here writes: not to the graph, not to a store, not to the bundle.
//! `roteiro import --from okf` remains the only way a peer's content enters the
//! graph, and it keeps its consent gate. A viewer that could import would make
//! "have a look at this bundle" a trust decision, which is the thing ADR-0021
//! spent a consent prompt avoiding.
//!
//! The bundle is loaded **per request**, which is what makes this dynamic: an
//! author editing a concept sees it on reload. A bundle of a few hundred concepts
//! is a few hundred small files, and correctness under editing is worth more here
//! than a cache that can be stale.
//!
//! # Serving somebody else's directory
//!
//! Every rule about untrusted content lives in `rto_render::okf::view` and is
//! tested there. The one this module owns is [`file()`]: a reader can type a URL,
//! so the route re-applies `view::safe_bundle_file` rather than trusting that
//! only hrefs our own renderer produced will arrive. A guard that assumed its
//! input came from us would be a guard on the wrong side of the boundary.
//!
//! Responses carry `Content-Security-Policy: default-src 'self'`, so even if
//! something were to slip past the renderer the page cannot reach the network.
//! That is a second line, not the first: the first is that raw HTML is escaped
//! and never emitted.

use std::fmt::Write as _;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};

use axum::Router;
use axum::extract::{Path as UrlPath, Query, State};
use axum::http::{StatusCode, header};
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::get;
use rto_render::okf::view;

/// The bundle this viewer serves.
#[derive(Clone)]
struct Viewer {
    root: Arc<PathBuf>,
    /// Where this page's "up" links point. See [`Nav`].
    nav: Arc<Nav>,
    /// The last bundle read, and the stamp it was read at.
    ///
    /// ADR-0022 renders at request time so an author editing a concept sees it
    /// on reload, and the first implementation took that literally: every HTML
    /// route re-read and re-parsed the whole bundle. Measured against this
    /// repository's own 9,511-concept bundle, `/` took **6.7 s** and
    /// `/api/graph.json` 1.4 s — and on a current-thread runtime eight
    /// concurrent requests did not finish in ten minutes, because each waited
    /// for the one before it.
    ///
    /// Re-reading is now conditional on the bundle having changed, which costs
    /// a walk of its `mtime`s: **58 ms** for those same 9,517 files, 115x less
    /// than the parse it avoids. The promise ADR-0022 makes is kept — an edit
    /// still appears on the next request — while the cost is paid only when
    /// there was an edit.
    cache: Arc<Mutex<Option<Cached>>>,
    /// The path this viewer is mounted under: empty when served alone, `/okf`
    /// when nested into `serve` beside the explorer.
    ///
    /// Every generated href carries it. Relative hrefs are not an option — a
    /// concept id contains slashes, so `/c/a/b` and `/c/a/b/c` sit at different
    /// depths — and a nested router emitting unprefixed absolute paths would
    /// produce a UI whose every link 404s.
    base: Arc<String>,
}

/// A bundle, what it looked like on disk when it was read, and the whole-bundle
/// views derived from it.
///
/// The derived views are cached because loading is not the only cost. With the
/// bundle cached, `/` still took 5.8 s against 9,511 concepts while
/// `/api/graph.json` took 0.28 s — the difference being that the index runs the
/// content screener over every concept, and the graph only walks links. Caching
/// the parse and then re-deriving that on each request would have fixed the
/// smaller half of the problem and reported it as fixed.
///
/// Both are filled on demand rather than at load, so a bundle nobody asks the
/// index about does not pay for one.
struct Cached {
    stamp: Stamp,
    bundle: Arc<view::Bundle>,
    overview: Option<Arc<view::BundleView>>,
    graph: Option<Arc<view::GraphView>>,
}

/// A cheap fingerprint of a bundle directory: how many files it holds, and the
/// newest modification time among **both its files and its directories**.
///
/// Not a hash of the contents. Hashing 9,517 files would cost more than the
/// parse it is meant to avoid, and this only has to answer "did anything change
/// since I last looked", which an author editing a concept always makes true.
///
/// Both halves earn their place, and so does looking at directories. The count
/// catches a deletion, which can leave the newest `mtime` untouched. The
/// directories catch a **rename**, which changes neither the count nor any
/// file's `mtime`.
///
/// It inherits `mtime`'s limits and does not pretend otherwise: a filesystem
/// with coarse timestamps could hide an edit made in the same second as the
/// read, in a bundle whose file count did not change. The failure that would
/// cause is a stale page until the next edit, on a read-only viewer — which is
/// why this is acceptable here and would not be in the import path.
#[derive(PartialEq, Eq, Clone, Copy)]
struct Stamp {
    files: usize,
    newest: Option<std::time::SystemTime>,
}

fn stamp(root: &std::path::Path) -> Stamp {
    fn walk(dir: &std::path::Path, out: &mut Stamp) {
        // The directory's own `mtime`, as well as its files'. A **rename** inside
        // the bundle changes neither any file's `mtime` nor the total count, so a
        // files-only stamp was identical before and after one and the cache never
        // reloaded — the viewer went on serving the old concept id and 404ing the
        // new one. Measured: renaming `one.md` to `renamed.md` left a files-only
        // stamp byte-identical while the directory's `mtime` moved by a second.
        // `metadata`, which follows, **for the directory itself** — the one
        // place in this walk where following is right. `walk` is only ever
        // called on the root the user named or on an entry already shown to be
        // a real directory by `file_type()`, so for everything but the root the
        // two calls agree. For the root they do not: pointing the viewer at a
        // symlink to a bundle, `symlink_metadata` reads the link's own `mtime`,
        // which a rename inside the target never changes — reintroducing exactly
        // the staleness this stamp exists to catch. Verified: after a rename in
        // the target, the link's own `mtime` is unchanged and the target's has
        // moved.
        if let Ok(modified) = std::fs::metadata(dir).and_then(|m| m.modified()) {
            out.newest = Some(out.newest.map_or(modified, |n| n.max(modified)));
        }
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            // This walks a directory a peer controls, so a symlink must never
            // be recursed into: `loop -> ..` inside a bundle would send it
            // round for ever, on *every* request, since the stamp is what
            // decides whether to reload.
            //
            // `file_type()` is documented not to follow the link, and that is
            // why it is used. The honest note is that `metadata()` did not
            // follow it either: `DirEntry::metadata` is `lstat` on Unix, so the
            // loop above never actually reproduced here — verified directly,
            // after a reproduction in Python wrongly suggested it did, because
            // Python's `DirEntry.stat()` *does* follow. The std documentation
            // says `metadata` "will traverse symbolic links", so relying on it
            // not to would be relying on the implementation over its contract.
            //
            // So this is the explicit form of a rule that currently holds by
            // platform accident, in the same spirit as refusing an unknown URL
            // scheme in `view.rs` rather than leaving it to a colon check.
            //
            // A symlink is counted as the file it is, by its own `mtime` via
            // `symlink_metadata`. Its target is not consulted, which is right:
            // if the target is inside the bundle it is already being walked, and
            // if it is outside then `safe_bundle_file` refuses to serve it, so
            // its changes cannot reach a reader and should not force a reload.
            let Ok(kind) = entry.file_type() else {
                continue;
            };
            let path = entry.path();
            if kind.is_dir() {
                walk(&path, out);
            } else {
                out.files += 1;
                if let Ok(modified) = std::fs::symlink_metadata(&path).and_then(|m| m.modified()) {
                    out.newest = Some(out.newest.map_or(modified, |n| n.max(modified)));
                }
            }
        }
    }
    let mut out = Stamp {
        files: 0,
        newest: None,
    };
    walk(root, &mut out);
    out
}

impl Viewer {
    /// The bundle, re-read only if the directory changed since it was last read.
    ///
    /// Blocking: every caller runs it inside [`blocking`].
    fn bundle(&self) -> Result<Arc<view::Bundle>, rto_render::okf::inspect::InspectError> {
        self.with_cache(|cached| Arc::clone(&cached.bundle))
    }

    /// The index view, derived once per bundle read.
    fn overview(&self) -> Result<Arc<view::BundleView>, rto_render::okf::inspect::InspectError> {
        let root = self.root.display().to_string();
        self.with_cache(|cached| {
            Arc::clone(
                cached
                    .overview
                    .get_or_insert_with(|| Arc::new(view::overview_in(&cached.bundle, &root))),
            )
        })
    }

    /// The concept graph, derived once per bundle read.
    fn graph(&self) -> Result<Arc<view::GraphView>, rto_render::okf::inspect::InspectError> {
        self.with_cache(|cached| {
            Arc::clone(
                cached
                    .graph
                    .get_or_insert_with(|| Arc::new(view::graph_in(&cached.bundle))),
            )
        })
    }

    /// Re-read the bundle if the directory changed, then hand the entry to `f`.
    ///
    /// Blocking, and holds the lock across the load: a burst of concurrent cold
    /// requests reads the bundle once rather than once each. That serialises
    /// them behind one parse — which is the cost being avoided anyway, and far
    /// better than N parses competing for the same page cache.
    fn with_cache<T>(
        &self,
        f: impl FnOnce(&mut Cached) -> T,
    ) -> Result<T, rto_render::okf::inspect::InspectError> {
        let current = stamp(&self.root);
        let mut cache = self
            .cache
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        let stale = cache.as_ref().is_none_or(|cached| cached.stamp != current);
        if stale {
            // The derived views go with it. Keeping them beside a new bundle is
            // how a viewer shows an edited concept in the body and the old title
            // in the sidebar — the two halves of one page disagreeing.
            *cache = Some(Cached {
                stamp: current,
                bundle: Arc::new(view::load(&self.root)?),
                overview: None,
                graph: None,
            });
        }
        Ok(f(cache.as_mut().expect("just populated")))
    }
}

/// Run blocking work off the async executor.
///
/// Every route here touches the filesystem, and the standalone server runs on a
/// current-thread runtime, so doing that work inline stalls every other request
/// for its duration — measured at ten minutes for eight concurrent requests
/// against a 9,511-concept bundle. `spawn_blocking` is the portable fix: it is
/// correct whether the viewer is standalone or nested inside `serve`'s runtime.
async fn blocking<T, F>(work: F) -> Option<T>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    // `Option` rather than `Result<T, Response>`: the only failure is the task
    // panicking or being cancelled, which carries no information a caller can
    // act on, and a `Response` in the error position makes every `Result` in
    // this module 128 bytes wide for a case that never carries a message.
    tokio::task::spawn_blocking(work).await.ok()
}

/// The response when the blocking pool could not run the work.
fn spawn_failed() -> Response {
    (
        StatusCode::INTERNAL_SERVER_ERROR,
        [(header::CONTENT_SECURITY_POLICY, CSP)],
        Html("<p>The viewer failed to read the bundle.</p>"),
    )
        .into_response()
}

/// The links a viewer page offers *above* the bundle it is showing.
///
/// Empty when the viewer is the whole server, which is the case ADR-0022 v1.0
/// built for: a path, any conformant bundle, nothing else on the port. Populated
/// when a `roteiro serve` or `roteiro explorer` holds several bundles and a graph
/// beside them (v1.2) — the reader then needs a way *out* of one bundle, and a
/// page with no way out is the "half the info" this fold exists to remove.
#[derive(Debug, Clone, Default)]
pub struct Nav {
    /// The prefix of the bundle this page belongs to.
    ///
    /// `None` on the chooser, which belongs to no single bundle — and a
    /// "Concepts"/"Graph" pair there would point at `{base}/` and `{base}/graph`,
    /// which are routes of a *bundle* and do not exist at the mount base. Two
    /// dead links on the one page whose whole job is to send a reader somewhere.
    pub bundle: Option<String>,
    /// The mount base, when this server holds more than one bundle.
    ///
    /// `None` for a lone bundle: an "All bundles" link to a page that redirects
    /// straight back here is a loop with a label on it.
    pub bundles: Option<String>,
    /// The graph explorer's root, when the same server serves one.
    pub explorer: Option<String>,
}

/// One bundle a server has mounted: where it lives, and what to call it.
///
/// A server hosts *workspaces*, not a bundle path (ADR-0008), so which bundles
/// exist is a property of what it is serving rather than of an argument somebody
/// typed. This is that answer, resolved once at startup.
#[derive(Debug, Clone)]
pub struct Mount {
    /// The path segment under the mount base, e.g. `Roteiro`.
    ///
    /// Derived by [`slug`] and made unique by [`disambiguate`], because two
    /// projects of the same name in different workspaces are the ordinary case
    /// and one silently shadowing the other would be a wrong answer rather than
    /// a missing one.
    pub slug: String,
    /// How the chooser names it — `<workspace>/<project>`, or the directory.
    pub label: String,
    /// Where it came from, shown so a reader can tell two similar bundles apart.
    pub origin: String,
    /// The bundle directory.
    pub root: PathBuf,
}

/// A URL-safe segment for `raw`, keeping only what a path segment carries plainly.
///
/// Workspace and project names are directory names, so they may hold anything a
/// filesystem allows — spaces, a `/` in a label built from two of them, non-ASCII.
/// Percent-encoding would round-trip but produces a URL nobody can read or type,
/// and this is a path a person is meant to be able to share; it is folded instead
/// and [`disambiguate`] resolves the collisions folding creates.
#[must_use]
pub fn slug(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    for c in raw.chars() {
        if c.is_ascii_alphanumeric() || c == '.' || c == '_' || c == '-' {
            out.push(c);
        } else if !out.ends_with('-') {
            out.push('-');
        }
    }
    let trimmed = out.trim_matches('-');
    if trimmed.is_empty() {
        "bundle".to_owned()
    } else {
        trimmed.to_owned()
    }
}

/// The path segments the mount base owns, which no bundle may be given.
///
/// [`mounts_router`] registers `{base}/okf-viewer.css` so the chooser — the one
/// page that is not inside a bundle — is styled. axum does not shadow an
/// overlapping route, it **panics at startup**, so a bundle landing on that
/// segment does not merely become unreachable: it stops the server booting. And
/// the label need not be strange to get there, because [`slug`] folds: a project
/// called `okf viewer.css` is enough.
const RESERVED_SLUGS: &[&str] = &["okf-viewer.css"];

/// Make every slug in `mounts` distinct, in place, preserving order.
///
/// [`slug`] is lossy, so `my repo` and `my/repo` fold to one segment — and two
/// mounts sharing a segment means the second `nest` registers over the first and
/// one bundle becomes silently unreachable. A numeric suffix is the smallest fix
/// that keeps the readable name for the first and loses nothing for the rest.
///
/// Distinct **from the mount base's own routes as well**, not just from each
/// other — see [`RESERVED_SLUGS`].
pub fn disambiguate(mounts: &mut [Mount]) {
    // Seeded, not checked afterwards: a reserved segment is simply already
    // taken, so the same suffix loop that resolves a collision between two
    // bundles resolves a collision with the base's own routes.
    let mut seen: std::collections::BTreeSet<String> =
        RESERVED_SLUGS.iter().map(|s| (*s).to_owned()).collect();
    for m in mounts.iter_mut() {
        if seen.insert(m.slug.clone()) {
            continue;
        }
        for n in 2.. {
            let candidate = format!("{}-{n}", m.slug);
            if seen.insert(candidate.clone()) {
                m.slug = candidate;
                break;
            }
        }
    }
}

/// Mount every bundle in `mounts` under `base`, with a chooser at `base` itself.
///
/// Each bundle is nested at `{base}/{slug}` and told that prefix, so every link
/// it writes is correct wherever the whole is mounted — which is what lets one
/// implementation serve `roteiro serve`, `roteiro explorer` and a bare bundle
/// without knowing which it is.
///
/// **A lone bundle redirects rather than listing.** A chooser with one row is a
/// click that tells the reader nothing they did not already know, and the mount
/// base pointing straight at the only bundle is what this route did when it could
/// hold only one.
pub fn mounts_router(base: &str, mounts: Vec<Mount>, explorer: Option<String>) -> Router {
    assert_mountable(base);
    let mut app = Router::new();
    for m in &mounts {
        let prefix = format!("{base}/{}", m.slug);
        let nav = Nav {
            bundle: Some(prefix.clone()),
            // Only when there is somewhere else to go — see `Nav::bundles`.
            bundles: (mounts.len() > 1).then(|| base.to_owned()),
            explorer: explorer.clone(),
        };
        app = app.nest(&prefix, router(m.root.clone(), &prefix, nav));
    }
    // At `base` itself, and as an **absolute** path: this router is `merge`d into
    // a server that already owns `/`, so registering the chooser at `/` claims a
    // route somebody else has. axum reports that by panicking at startup —
    // `Overlapping method route. Handler for \`GET /\` already exists` — which is
    // a loud failure and still one no compiler catches, so the route table is
    // what the tests below assert on.
    // The chooser is a viewer page, so the mount base serves the viewer's
    // stylesheet too. Without it the one page that is *not* inside a bundle is
    // the one page with no styling — `{base}/okf-viewer.css` resolves to a
    // bundle's route everywhere else.
    let at = base.to_owned();
    let owned = Arc::new(base.to_owned());
    // Behind an `Arc` because the handler closure must own what it reads and is
    // called once per request. The list is short — one per hosted project with a
    // bundle, six here — and the clone was cheaper than the page it precedes, so
    // this is not a measured cost; it is one line to stop doing per-request work
    // that has no per-request reason to happen.
    let shared = Arc::new(mounts);
    let app = app.route(&format!("{base}/okf-viewer.css"), get(stylesheet));
    app.route(
        &at,
        get(move || {
            let (base, mounts) = (Arc::clone(&owned), Arc::clone(&shared));
            let explorer = explorer.clone();
            async move { chooser(&base, &mounts, explorer.as_deref()) }
        }),
    )
}

/// Where a page links to when it means "this bundle's index".
///
/// `{base}/` is wrong under `nest`, and quietly: axum serves `/okf/x` and **not**
/// `/okf/x/`, so a trailing slash gives a 404 while every other link on the page
/// works. `roteiro serve` has nested this viewer at `/okf` since ADR-0022 v1.0
/// and its "Concepts" link has 404'd for exactly that reason — invisible while
/// the standalone server, where `base` is empty and `/` is right, was the case
/// anyone used. Folding the viewer in makes nested the *only* case, so the rule
/// is written down once here instead of being spelled out at four call sites.
fn index_href(base: &str) -> &str {
    if base.is_empty() { "/" } else { base }
}

/// The mount base's index: where to go, or straight there when there is one place.
fn chooser(base: &str, mounts: &[Mount], explorer: Option<&str>) -> Response {
    if let [only] = mounts {
        return Redirect::temporary(&format!("{base}/{}", only.slug)).into_response();
    }
    let mut body = String::with_capacity(512 + mounts.len() * 256);
    if mounts.is_empty() {
        // Reachable when a server mounts this route and every bundle disappears
        // underneath it. Says what is missing and what writes one, rather than
        // rendering an empty list that reads as "these projects have no concepts".
        body.push_str(
            "<article><h1>OKF bundles</h1><p class=\"scope\">No bundle is mounted. \
             A project gets one when <code>roteiro render okf</code> writes it, and \
             this server picks it up on the next start.</p></article>",
        );
    } else {
        let _ = write!(
            body,
            "<article><h1>OKF bundles</h1><p class=\"scope\">{} bundles are mounted \
             here. Each is served read-only from the directory named beside it.</p>\
             <ol class=\"hubs\">",
            mounts.len()
        );
        for m in mounts {
            let _ = write!(
                body,
                "<li><a href=\"{}/{}\">{}</a> <span class=\"deg\">{}</span></li>",
                escape(base),
                escape(&m.slug),
                escape(&m.label),
                escape(&m.origin)
            );
        }
        body.push_str("</ol></article>");
    }
    page(
        "OKF bundles",
        "",
        base,
        &Nav {
            bundle: None,
            bundles: None,
            explorer: explorer.map(ToOwned::to_owned),
        },
        &body,
    )
}

/// Refuse a mount path this module cannot safely write into markup.
///
/// `base` is interpolated raw into `href` and `src` attributes at a dozen call
/// sites. That is *not* a case for `escape`: escaping is for text, and a URL
/// that needed it would be a broken URL, not a safe one — `&lt;script&gt;` in an
/// `href` is nonsense either way. What the pages actually rely on is that `base`
/// is a path this module built itself, out of [`slug`], whose charset already
/// excludes every character that could leave an attribute.
///
/// So the fix for "interpolated without escaping" is to make the assumption a
/// **checked** one at the single point where a router is built, rather than a
/// remark in a comment eleven interpolations away. Raised by review on #785.
///
/// # Panics
///
/// If `base` is not empty and not a `/`-prefixed path of `[A-Za-z0-9._-]`
/// segments. Callers construct it; there is no input that reaches this from a
/// bundle or a request, so a bad one is a bug in this crate and should stop the
/// server rather than render.
fn assert_mountable(base: &str) {
    assert!(
        base.is_empty()
            || (base.starts_with('/')
                && base.split('/').skip(1).all(|seg| !seg.is_empty()
                    && seg
                        .chars()
                        .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')))),
        "mount path is not slug-safe and must not be written into markup: {base:?}"
    );
}

/// One bundle's routes, mounted at `base`.
///
/// Stateless from the caller's side — it holds a path and where it sits — so it
/// merges into a larger router the way `crate::explorer_app::router` does.
///
/// `base` is the mount path and every generated href carries it: `/okf/{slug}`
/// under [`mounts_router`], and empty only in tests that drive one bundle
/// directly. `nav` is what else the same server holds, which the bundle cannot
/// know and must not guess — see [`Nav`].
pub fn router(root: PathBuf, base: &str, nav: Nav) -> Router {
    assert_mountable(base);
    let state = Viewer {
        root: Arc::new(root),
        base: Arc::new(base.to_owned()),
        nav: Arc::new(nav),
        cache: Arc::new(Mutex::new(None)),
    };
    Router::new()
        .route("/", get(index))
        .route("/graph", get(graph_page))
        .route("/api/graph.json", get(graph_json))
        .route("/c/{*id}", get(concept))
        .route("/f/{*path}", get(file))
        .route("/okf-viewer.css", get(stylesheet))
        .route("/cytoscape.min.js", get(cytoscape))
        .with_state(state)
}

const STYLE: &str = include_str!("assets/okf-viewer.css");
/// The same vendored build the explorer uses (ADR-0010) — one copy in the
/// binary, and no fetch from a CDN.
const CYTOSCAPE: &str = include_str!("assets/cytoscape.min.js");

/// `default-src 'self'` and nothing else: no CDN, no font host, no analytics.
///
/// The renderer already refuses to emit raw HTML, so this is a second line
/// rather than the defence. It is worth having because the two fail
/// independently — a bug in the escaping does not also disable the header.
const CSP: &str = "default-src 'self'; img-src 'self'; object-src 'none'; base-uri 'none'";

/// The policy for `/f/`, which serves **bytes a peer wrote**.
///
/// Tighter than [`CSP`], and deliberately a different constant. The page policy
/// says `default-src 'self'` because the viewer's own pages legitimately load
/// their own stylesheet and script. A file out of the bundle needs neither, and
/// `'self'` is too generous for one: `script-src` falls back to `default-src`,
/// so an SVG served from here and opened directly could have pulled in
/// `/f/anything.js` from the same bundle.
///
/// That was blocked in practice — the mime table serves an unknown extension as
/// `application/octet-stream` and `nosniff` refuses to execute it as script — but
/// that is three unrelated rules happening to line up, not a policy. SVG is
/// active content, unlike every other type in the table, and the bundle chooses
/// its contents.
///
/// `sandbox` puts a directly-opened file in a unique origin with scripting off;
/// `default-src 'none'` stops it fetching anything at all. Neither affects an
/// image embedded with `<img>`, which is how the viewer itself loads them —
/// scripts never run in that context regardless.
const FILE_CSP: &str = "default-src 'none'; sandbox; base-uri 'none'";

/// The most `/f/` will read into memory for one request.
///
/// The route reads a whole file before answering, and the bundle is somebody
/// else's: without a bound, one large file — or a handful of concurrent requests
/// for it — is memory pressure a peer chooses for you. This is a **memory bound,
/// not a policy**: it says nothing about what a bundle may contain, only what
/// this process will hold at once, and it is per request, so concurrency
/// multiplies it.
///
/// 32 MiB is far above any image a concept embeds and far below anything that
/// threatens a server. A bundle carrying something genuinely larger is not
/// refused as a bundle — every other command still reads it — it simply is not
/// served down this route.
const MAX_FILE_BYTES: u64 = 32 * 1024 * 1024;

/// `Cache-Control` for the two compiled-in assets.
///
/// They are `include_str!`ed, so they change only when the binary does — the
/// same reasoning and the same hour as `explorer_app`'s `CACHE_JS`. Without it a
/// browser refetches the whole of cytoscape on every navigation, which on a
/// bundle whose pages are otherwise cheap is the largest thing on the wire.
///
/// Deliberately **not** applied to any bundle content. `/f/` serves files an
/// author is editing, and `/`, `/c/` and the graph are rendered from a bundle
/// that changes underneath the server — caching those in the browser would undo
/// the reload guarantee the server-side cache is careful to keep.
const CACHE_ASSET: &str = "public, max-age=3600";

fn page(title: &str, root: &str, base: &str, nav: &Nav, body: &str) -> Response {
    let mut up = String::new();
    if let Some(bundles) = &nav.bundles {
        let _ = write!(up, "<a href=\"{}\">All bundles</a>", escape(bundles));
    }
    if let Some(explorer) = &nav.explorer {
        let _ = write!(up, "<a href=\"{}\">Explorer</a>", escape(explorer));
    }
    let mut here = String::new();
    if let Some(bundle) = &nav.bundle {
        let _ = write!(
            here,
            "<a href=\"{}\">Concepts</a><a href=\"{}/graph\">Graph</a>",
            escape(index_href(bundle)),
            escape(bundle)
        );
    }
    let mut out = String::with_capacity(body.len() + 2048);
    let _ = write!(
        out,
        "<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\">\
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
         <link rel=\"stylesheet\" href=\"{base}/okf-viewer.css\">\
         <title>{} — OKF viewer</title></head><body>\
         <header><span class=\"name\">OKF viewer</span>\
         <span class=\"root\">{}</span>\
         <nav>{here}\
         {up}</nav></header>\
         <main>{body}</main>\
         <footer>Read-only. Nothing here is imported into the graph — \
         <code>roteiro import --from okf</code> is still the only path that does, \
         and it asks first.</footer></body></html>",
        escape(title),
        escape(root),
    );
    (
        [
            (header::CONTENT_TYPE, "text/html; charset=utf-8"),
            (header::CONTENT_SECURITY_POLICY, CSP),
        ],
        Html(out),
    )
        .into_response()
}

/// Every string this module interpolates goes through here.
///
/// The body HTML is the renderer's and is already safe; a title, an id, a
/// screener class and a path are all bundle-controlled text being put into
/// markup here, so they are escaped at the point of use rather than trusted to
/// have been escaped earlier.
fn escape(raw: &str) -> String {
    let mut out = String::with_capacity(raw.len());
    for c in raw.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

fn unreadable(err: &rto_render::okf::inspect::InspectError) -> Response {
    (
        StatusCode::NOT_FOUND,
        [(header::CONTENT_SECURITY_POLICY, CSP)],
        Html(format!(
            "<p>Not a readable OKF bundle: {}</p>",
            escape(&err.to_string())
        )),
    )
        .into_response()
}

/// A tier or status pill, which always carries its word as well as its colour.
fn pill(class: &str, text: &str) -> String {
    format!(
        "<span class=\"tier tier-{}\">{}</span>",
        escape(class),
        escape(text)
    )
}

async fn index(State(v): State<Viewer>) -> Response {
    let state = v.clone();
    let built = blocking(move || state.overview()).await;
    let view = match built {
        Some(Ok(view)) => view,
        Some(Err(e)) => return unreadable(&e),
        None => return spawn_failed(),
    };
    let base = v.base.as_str();

    let mut body = String::new();
    body.push_str("<aside>");
    let _ = write!(
        body,
        "<div class=\"group\">{} concept(s)</div><ol>",
        view.concepts.len()
    );
    for c in &view.concepts {
        let _ = write!(
            body,
            "<li><a href=\"{base}/c/{}\">{}</a></li>",
            escape(&c.id),
            escape(&c.title)
        );
    }
    body.push_str("</ol></aside><article>");

    let _ = write!(
        body,
        "<h1>Bundle</h1><ul class=\"counts\">\
         <li><span class=\"n\">{}</span> human-reviewed</li>\
         <li><span class=\"n\">{}</span> machine-confirmed</li>\
         <li><span class=\"n\">{}</span> unverified</li>\
         <li><span class=\"n\">{}</span> unresolved link(s)</li>\
         <li>okf_version {}</li></ul>",
        view.human_reviewed,
        view.machine_confirmed,
        view.unverified,
        view.broken_links,
        view.okf_version
            .as_deref()
            .map_or_else(|| "not declared".to_owned(), escape),
    );

    if !view.flagged.is_empty() {
        let _ = write!(
            body,
            "<div class=\"screened\"><strong>{} concept(s) tripped the content screener.</strong> \
             This is a bundle somebody else wrote, and the screener looks for text shaped to be \
             read as instructions rather than as content. Nothing has been imported.<ul>",
            view.flagged.len()
        );
        for f in &view.flagged {
            let _ = write!(
                body,
                "<li><a href=\"{base}/c/{}\">{}</a> — {} ({})</li>",
                escape(&f.id),
                escape(&f.id),
                escape(&f.verdict),
                f.classes
                    .iter()
                    .map(|c| format!("<code>{}</code>", escape(c)))
                    .collect::<Vec<_>>()
                    .join(", ")
            );
        }
        body.push_str("</ul></div>");
    }

    body.push_str("<table><tr><th>Concept</th><th>Type</th><th>Trust</th><th>Status</th></tr>");
    for c in &view.concepts {
        let status_class = if c.status == "deprecated" {
            " class=\"status-deprecated\""
        } else {
            ""
        };
        let _ = write!(
            body,
            "<tr><td><a href=\"{base}/c/{}\">{}</a></td><td>{}</td><td>{}</td><td{status_class}>{}</td></tr>",
            escape(&c.id),
            escape(&c.title),
            c.kind.as_deref().map_or_else(String::new, escape),
            pill(c.trust, c.trust),
            escape(&c.status),
        );
    }
    body.push_str("</table></article>");
    page("Bundle", &view.root, base, &v.nav, &body)
}

async fn concept(State(v): State<Viewer>, UrlPath(id): UrlPath<String>) -> Response {
    let state = v.clone();
    let wanted = id.clone();
    let built = blocking(move || {
        let bundle = state.bundle()?;
        Ok::<_, rto_render::okf::inspect::InspectError>(view::concept_in(
            &bundle,
            &wanted,
            &state.base,
        ))
    })
    .await;
    let base = v.base.as_str();
    let found = match built {
        Some(Ok(found)) => found,
        Some(Err(e)) => return unreadable(&e),
        None => return spawn_failed(),
    };
    let Some(c) = found else {
        return (
            StatusCode::NOT_FOUND,
            [(header::CONTENT_SECURITY_POLICY, CSP)],
            Html(format!(
                "<p>The bundle contains no concept <code>{}</code>. \
                 <a href=\"{}\">Back to the bundle</a>.</p>",
                escape(&id),
                index_href(base)
            )),
        )
            .into_response();
    };

    let mut body = String::from("<article>");
    if !c.screen.is_empty() {
        let _ = write!(
            body,
            "<div class=\"screened\"><strong>The content screener flagged this document.</strong> \
             It is somebody else's text and may be written to be read as instructions. \
             Classes: {}.</div>",
            c.screen
                .iter()
                .map(|s| format!("<code>{}</code>", escape(s)))
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
    let _ = write!(
        body,
        "<h1>{}</h1><p class=\"meta\">{}{}{}<code>{}</code></p>{}",
        escape(&c.title),
        pill(c.trust, c.trust),
        c.kind
            .as_deref()
            .map_or_else(String::new, |k| format!("<span>{}</span>", escape(k))),
        format_args!("<span>{}</span>", escape(&c.status)),
        escape(&c.path),
        c.body_html,
    );

    // The graph is reached *from* a concept rather than the other way round: a
    // neighbourhood needs a centre, and this is where the reader already is.
    let _ = write!(
        body,
        "<p class=\"scope\"><a href=\"{base}/graph?focus={}\">See this concept \
         in the graph</a></p>",
        urlencode(&c.id)
    );

    body.push_str("<div class=\"rel\">");
    if !c.links.is_empty() {
        body.push_str("<h2>Links out</h2><ul>");
        for l in &c.links {
            if l.exists {
                let _ = write!(
                    body,
                    "<li><a href=\"{base}/c/{}\">{}</a></li>",
                    escape(&l.target),
                    escape(&l.target)
                );
            } else {
                // §6 tells a consumer to tolerate a link whose target is not
                // here, so it is shown as absent rather than hidden or errored.
                let _ = write!(
                    body,
                    "<li class=\"absent\">{} — not in this bundle</li>",
                    escape(&l.target)
                );
            }
        }
        body.push_str("</ul>");
    }
    if !c.backlinks.is_empty() {
        body.push_str("<h2>Linked from</h2><ul>");
        for b in &c.backlinks {
            let _ = write!(
                body,
                "<li><a href=\"{base}/c/{}\">{}</a></li>",
                escape(b),
                escape(b)
            );
        }
        body.push_str("</ul>");
    }
    body.push_str("</div></article>");
    page(&c.title, &v.root.display().to_string(), base, &v.nav, &body)
}

/// What the graph routes accept, and the bounds they are held to.
///
/// **The bounds are the fix, so they are enforced here rather than trusted.**
/// This page was unusable because it drew every concept: 9,766 nodes and 41,980
/// edges of this repository's own bundle, 8.16 MB, handed to a force-directed
/// layout in one go. A caller-supplied `limit` taken at its word would simply
/// move that defect into a URL, so `depth` and `limit` are clamped and a request
/// for more is answered with the most this page will draw.
#[derive(Debug, serde::Deserialize)]
struct GraphQuery {
    /// The concept to centre on. Absent means the entry list.
    focus: Option<String>,
    /// Hops from the focus. Clamped to [`MAX_DEPTH`].
    depth: Option<usize>,
    /// Node budget. Clamped to [`MAX_NODES`].
    limit: Option<usize>,
}

/// The most hops from a focus this page will draw.
///
/// Three, because two is already enough to leave the neighbourhood behind on
/// this shape of graph: measured on this bundle, a *median* concept reaches 3
/// nodes at depth 1 and 436 at depth 2. Depth is the coarse control and the node
/// budget is the fine one.
const MAX_DEPTH: usize = 3;

/// The most nodes this page will draw at once.
///
/// A force-directed layout is O(n²) per tick in its repulsion step, so this is
/// the number that decides whether the page renders or hangs. 500 lays out in
/// well under a second; the 9,766 it used to attempt never finished.
const MAX_NODES: usize = 500;

/// Nodes drawn when the caller does not say.
const DEFAULT_NODES: usize = 150;

/// Concepts listed on the entry page.
const HUB_LIST: usize = 40;

impl GraphQuery {
    /// The concept to centre on, or `None` for the entry list.
    ///
    /// Empty and whitespace-only mean **absent**: taken literally they ask for a
    /// concept whose id is the empty string, which no bundle holds, so they would
    /// 404 every time for what is plainly a request for the entry list.
    ///
    /// An accessor rather than a check at each route, because the first fix for
    /// this normalised the HTML route and left the JSON one 404ing — two call
    /// sites that had already disagreed once. Raised twice in review of #782.
    fn focus(&self) -> Option<&str> {
        self.focus
            .as_deref()
            .map(str::trim)
            .filter(|f| !f.is_empty())
    }

    /// Hops to draw, within [`MAX_DEPTH`] and never zero — a depth-0 view is one
    /// node and no edges, which is a concept page with extra steps.
    fn depth(&self) -> usize {
        self.depth.unwrap_or(1).clamp(1, MAX_DEPTH)
    }

    /// Nodes to draw, within [`MAX_NODES`].
    fn limit(&self) -> usize {
        self.limit.unwrap_or(DEFAULT_NODES).clamp(1, MAX_NODES)
    }
}

async fn graph_page(State(v): State<Viewer>, Query(q): Query<GraphQuery>) -> Response {
    // The script is inline and fixed at compile time, so it is content of this
    // binary rather than of the bundle. `'unsafe-inline'` is scoped to
    // `script-src` on this one route and never widens `default-src`.
    // Placeholders and a `replace`, not `format!`: this is JavaScript, so it is
    // most of the way to being braces, and every one of them would have to be
    // doubled to survive a format string.
    //
    // `concentric`, not `cose`. A neighbourhood has a centre, so the layout that
    // draws one is the one that says what the picture means — and it is linear
    // where a force-directed layout is quadratic per tick, which is what made
    // this page hang.
    //
    // The focus ranks `Infinity`, not a large number. `concentric` puts the
    // highest rank innermost and every other node is ranked by its in-view
    // degree, so any finite constant is a threshold a neighbour can cross — and
    // then the picture is centred on something that is not the focus, silently.
    // Measured on this bundle the nearest neighbour reached **96** against a
    // constant of 100, with nothing bounding it: the node budget allows 500, so a
    // neighbour may in principle reach 499. Raised in review of #782, where it
    // had not yet fired.
    const SCRIPT: &str = "<article><h1>Concept graph</h1>\
        <p class=\"scope\" id=\"scope\">Loading…</p>\
        <div id=\"graph\"></div>\
        <script src=\"{BASE}/cytoscape.min.js\"></script>\
        <script>\
        var Q='focus={FOCUS}&depth={DEPTH}&limit={LIMIT}';\
        var n=document.getElementById('scope');\
        fetch('{BASE}/api/graph.json?'+Q).then(r=>r.json().then(g=>({ok:r.ok,g:g})))\
        .catch(e=>({ok:false,g:{error:String(e)}})).then(res=>{\
        if(!res.ok||!res.g.scope){\
        n.textContent=res.g.error||'The graph could not be read.';return;}\
        var g=res.g,s=g.scope;\
        n.textContent='Showing '+s.shown_nodes+' of '+s.total_nodes+\
        ' concepts and '+s.shown_edges+' of '+s.total_edges+' links, '+\
        s.depth+(s.depth==1?' hop':' hops')+' from '+s.focus+\
        (s.beyond?'. '+s.beyond+' more connected concepts are not drawn.':'.');\
        if(s.beyond&&{CAN_EXPAND}){var a=document.createElement('a');\
        a.href='{BASE}/graph?focus='+encodeURIComponent(s.focus)+\
        '&depth={NEXT_DEPTH}&limit={NEXT_LIMIT}';\
        a.textContent=' Show more.';n.appendChild(a);}\
        else if(s.beyond){n.textContent+=' This is the most this page draws.';}\
        var cy=cytoscape({container:document.getElementById('graph'),\
        elements:[...g.nodes.map(n=>({data:{id:n.id,label:n.label,trust:n.trust,\
        focus:n.id===s.focus?'yes':'no'}})),\
        ...g.edges.map(e=>({data:{source:e.source,target:e.target}}))],\
        layout:{name:'concentric',concentric:n=>n.data('focus')==='yes'?Infinity:n.degree(),\
        levelWidth:()=>1,minNodeSpacing:24},style:[\
        {selector:'node',style:{'label':'data(label)','font-size':'8px',\
        'background-color':'#6b7684','color':'#1a2733'}},\
        {selector:'node[trust=\"human-reviewed\"]',style:{'background-color':'#0e6e8c'}},\
        {selector:'node[focus=\"yes\"]',style:{'background-color':'#b4531f',\
        'font-size':'12px','font-weight':'bold'}},\
        {selector:'edge',style:{'width':1,'line-color':'#d8d2c4',\
        'target-arrow-shape':'triangle','target-arrow-color':'#d8d2c4',\
        'curve-style':'bezier'}}]});\
        cy.on('tap','node',e=>{location.href='{BASE}/graph?focus='+\
        encodeURIComponent(e.target.id())+'&depth={DEPTH}&limit={LIMIT}';});\
        });</script></article>";

    let Some(focus) = q.focus().map(ToOwned::to_owned) else {
        return graph_entry(&v).await;
    };

    let base = v.base.as_str();
    let depth = q.depth();
    let limit = q.limit();
    let body = SCRIPT
        .replace("{BASE}", base)
        .replace("{FOCUS}", &urlencode(&focus))
        .replace("{DEPTH}", &depth.to_string())
        .replace("{LIMIT}", &limit.to_string())
        // "Show more" widens the budget first and only then reaches further: a
        // deeper ring on this shape of graph multiplies, where a bigger budget
        // adds. Both are clamped by `GraphQuery`, so the link cannot ask for the
        // payload this page exists to avoid.
        // Offered only when it can actually widen something. At both maxima the
        // link would point at the view already on screen — an affordance that
        // does nothing is worse than none, because the reader concludes there is
        // nothing more rather than that this page will not draw it. The page says
        // which it is.
        .replace(
            "{CAN_EXPAND}",
            if limit < MAX_NODES || depth < MAX_DEPTH {
                "true"
            } else {
                "false"
            },
        )
        .replace("{NEXT_LIMIT}", &(limit * 2).min(MAX_NODES).to_string())
        .replace(
            "{NEXT_DEPTH}",
            &if limit >= MAX_NODES {
                (depth + 1).min(MAX_DEPTH)
            } else {
                depth
            }
            .to_string(),
        );
    let mut res = page(
        "Concept graph",
        &v.root.display().to_string(),
        base,
        &v.nav,
        &body,
    );
    res.headers_mut().insert(
        header::CONTENT_SECURITY_POLICY,
        header::HeaderValue::from_static(
            "default-src 'self'; script-src 'self' 'unsafe-inline'; \
             img-src 'self'; object-src 'none'; base-uri 'none'",
        ),
    );
    res
}

/// The graph's entry page: what to centre on, as a **list**.
///
/// Deliberately not a drawing. Measured on this repository's own bundle, the 100
/// highest-degree concepts share 157 edges out of 41,980 — the graph is
/// hub-and-spoke, so any "top N" tier is disconnected scatter whatever N is and
/// whatever it is ranked by. A reader choosing where to start is served by a
/// ranked list; there is no whole-graph picture worth drawing, and pretending
/// otherwise is what made this page unusable.
async fn graph_entry(v: &Viewer) -> Response {
    let built = blocking({
        let v = v.clone();
        move || v.graph()
    })
    .await;
    let graph = match built {
        Some(Ok(graph)) => graph,
        Some(Err(e)) => return unreadable(&e),
        None => return spawn_failed(),
    };
    let base = v.base.as_str();
    let hubs = view::hubs(&graph, HUB_LIST);

    let mut body = String::with_capacity(4096);
    let _ = write!(
        body,
        "<article><h1>Concept graph</h1><p class=\"scope\">This bundle holds \
         {} concepts and {} links between them — too many to draw at once, and \
         too sparsely connected between its hubs for any single picture to mean \
         much. Pick a concept to centre the graph on; its neighbourhood is drawn \
         from there.</p><ol class=\"hubs\">",
        graph.nodes.len(),
        graph.edges.len()
    );
    // "connected", not "links": `GraphHub::degree` counts **distinct** concepts
    // in either direction, so a concept naming the same target six times counts
    // once. Labelling that "6 links" would be a different number, and the wrong
    // one — a mismatch introduced by correcting the Rust doc and leaving the
    // markup. Raised in review of #782.
    for hub in &hubs {
        let _ = write!(
            body,
            "<li><a href=\"{base}/graph?focus={}\">{}</a> \
             <span class=\"deg\">{} connected</span></li>",
            urlencode(&hub.id),
            escape(&hub.label),
            hub.degree
        );
    }
    body.push_str("</ol></article>");
    page(
        "Concept graph",
        &v.root.display().to_string(),
        base,
        &v.nav,
        &body,
    )
}

/// Percent-encode a concept id for a query string.
///
/// Ids carry `/` and may carry anything a path segment can, so they are encoded
/// rather than interpolated: an id containing `&` would otherwise end the
/// parameter and silently change which concept was asked for.
fn urlencode(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 8);
    for b in s.bytes() {
        match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(char::from(b));
            }
            _ => {
                let _ = write!(out, "%{b:02X}");
            }
        }
    }
    out
}

/// The graph as data, always bounded.
///
/// With a `focus`, one concept's neighbourhood; without one, the entry list. It
/// **never** returns the whole graph, and that is the point rather than an
/// omission: the unbounded response this replaces was 8.16 MB on this
/// repository's own bundle, and every caller of it — there was one, this page —
/// then failed to draw it. A route that can still be asked for the payload that
/// broke the page has not fixed the page.
async fn graph_json(State(v): State<Viewer>, Query(q): Query<GraphQuery>) -> Response {
    let built = blocking({
        let v = v.clone();
        move || v.graph()
    })
    .await;
    let graph = match built {
        Some(Ok(graph)) => graph,
        Some(Err(e)) => return unreadable(&e),
        None => return spawn_failed(),
    };

    let payload = match q.focus() {
        Some(focus) => match view::neighbourhood(&graph, focus, q.depth(), q.limit()) {
            Some(scoped) => serde_json::to_string(&scoped),
            // A mistyped id is a 404, not an empty graph: an empty drawing reads
            // as a real concept with no links, which is a different answer and a
            // wrong one.
            None => {
                return (
                    StatusCode::NOT_FOUND,
                    [
                        (header::CONTENT_TYPE, "application/json"),
                        (header::CONTENT_SECURITY_POLICY, CSP),
                    ],
                    // Built rather than formatted: `Value::String` renders *with*
                    // its quotes, so interpolating it into a quoted field
                    // produced `"no concept "nonesuch""` — invalid JSON, from
                    // the very escaping that was there to make it safe. A
                    // concept id can hold a quote, so the escaping is needed;
                    // it just has to be done once.
                    serde_json::json!({ "error": format!("no concept {focus}") }).to_string(),
                )
                    .into_response();
            }
        },
        None => serde_json::to_string(&serde_json::json!({
            "hubs": view::hubs(&graph, HUB_LIST),
            "total_nodes": graph.nodes.len(),
            "total_edges": graph.edges.len(),
        })),
    };
    // Plain owned data, so this does not fail in practice — which is exactly why
    // it must not be swallowed. A `{}` under a 200 would render as a bundle with
    // no concepts: a client cannot tell that from a real empty graph, so the one
    // way this ever goes wrong is also the way that hides it.
    let Ok(body) = payload else {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            [
                (header::CONTENT_TYPE, "application/json"),
                (header::CONTENT_SECURITY_POLICY, CSP),
            ],
            r#"{"error":"the graph could not be serialised"}"#,
        )
            .into_response();
    };
    (
        [
            (header::CONTENT_TYPE, "application/json"),
            (header::CONTENT_SECURITY_POLICY, CSP),
        ],
        body,
    )
        .into_response()
}

/// A file from inside the bundle — an image a concept embeds, and nothing else.
///
/// The guard is `view::safe_bundle_file`, the same one the renderer applies when
/// it decides whether to emit a `/f/` href at all. Re-applied here because a
/// reader can type a URL: trusting that only our own hrefs arrive would put the
/// check on the wrong side of the boundary.
async fn file(State(v): State<Viewer>, UrlPath(path): UrlPath<String>) -> Response {
    // The refusals carry the policy too. "Every response" has to mean every
    // response, or it is not a rule but a description of the happy path — and a
    // reader cannot tell which from the sentence.
    let refused = || {
        (
            StatusCode::NOT_FOUND,
            [(header::CONTENT_SECURITY_POLICY, FILE_CSP)],
        )
            .into_response()
    };

    // Guard, size check and read happen together on the blocking pool rather
    // than as three hops: they are one decision about one file, and splitting
    // them would widen the window in which it can change underneath us.
    let root = Arc::clone(&v.root);
    let wanted = path.clone();
    let read = blocking(move || {
        let resolved = view::safe_bundle_file(&root, &wanted)?;
        // Checked before the read, not after: `std::fs::read` allocates to the
        // file's length, so a check on `bytes.len()` would already have paid
        // the cost it exists to avoid.
        let meta = std::fs::metadata(&resolved).ok()?;
        if meta.len() > MAX_FILE_BYTES {
            return None;
        }
        let bytes = std::fs::read(&resolved).ok()?;
        Some((resolved, bytes))
    })
    .await;
    let Some(Some((resolved, bytes))) = read else {
        // A file past the bound refuses as 404 like every other refusal here:
        // the size of a file this route declines to serve is not something a
        // stranger's client needs confirmed.
        return refused();
    };

    // Typed from the extension against a closed list. A bundle does not choose
    // the content type: echoing one back from the file would let a bundle serve
    // itself as `text/html` and undo the escaping.
    let mime = match resolved
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("svg") => "image/svg+xml",
        // Anything else is bytes to download rather than render.
        _ => "application/octet-stream",
    };

    let mut response = (
        [
            (header::CONTENT_TYPE, mime),
            (header::CONTENT_SECURITY_POLICY, FILE_CSP),
            (header::X_CONTENT_TYPE_OPTIONS, "nosniff"),
        ],
        bytes,
    )
        .into_response();

    // Anything outside the image allow-list is **asked** for as an attachment.
    //
    // The type is already chosen from a closed list, so a bundle does not get to
    // say what its bytes *are*; this says what they are *for*, which is the same
    // decision made once more. Without it the response relied on browsers
    // happening to download `application/octet-stream` — a convention they follow
    // rather than something the response requested. ADR-0024's first draft
    // described that as "served as an attachment", which no header said (#750),
    // and the fix for a document describing a header that does not exist is the
    // header.
    //
    // Images are excluded because the viewer embeds them with `<img>`: an
    // attachment disposition there would break every concept page that shows one,
    // and an image the browser renders inside a page is not a file the reader is
    // being handed.
    if mime == "application/octet-stream" {
        response.headers_mut().insert(
            header::CONTENT_DISPOSITION,
            header::HeaderValue::from_static("attachment"),
        );
    }
    response
}

async fn stylesheet() -> Response {
    (
        [
            (header::CONTENT_TYPE, "text/css; charset=utf-8"),
            (header::CONTENT_SECURITY_POLICY, CSP),
            (header::CACHE_CONTROL, CACHE_ASSET),
        ],
        STYLE,
    )
        .into_response()
}

async fn cytoscape() -> Response {
    (
        [
            (
                header::CONTENT_TYPE,
                "application/javascript; charset=utf-8",
            ),
            (header::CONTENT_SECURITY_POLICY, CSP),
            (header::CACHE_CONTROL, CACHE_ASSET),
        ],
        CYTOSCAPE,
    )
        .into_response()
}

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

    /// The palette is copied from the site, so it is asserted rather than
    /// remembered.
    ///
    /// `include_str!` would be the obvious way to have one copy, and it cannot be
    /// used: `roteiro` publishes to crates.io and `cargo package` takes only
    /// files under the crate directory, so a build-time include reaching up to
    /// `website/` would ship a crate that does not compile. A copy plus a test is
    /// the same trade the vendored OKF fixtures make.
    #[test]
    fn the_viewer_shares_the_sites_palette() {
        let site =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../website/public/style.css");
        let Ok(site_css) = std::fs::read_to_string(&site) else {
            // Not a repository checkout (a packaged crate has no `website/`), so
            // there is nothing to compare against. Returning is right here and
            // would not be in a repo — see the assertion below.
            return;
        };
        let palette = |css: &str| {
            css.lines()
                .find(|l| l.trim_start().starts_with(":root") && l.contains("--ink"))
                .map(|l| l.trim().to_owned())
        };
        let theirs = palette(&site_css).expect("the site declares a palette");
        let ours = palette(STYLE).expect("the viewer declares a palette");
        assert_eq!(
            ours, theirs,
            "the viewer's palette has drifted from the site's. Copy \
             `website/public/style.css`'s `:root` line into \
             `crates/roteiro/src/assets/okf-viewer.css`."
        );
    }

    /// Bundle-controlled text is escaped at the point it enters markup.
    #[test]
    fn interpolated_text_is_escaped() {
        let out = escape(r#"<img src=x onerror="alert(1)">&'"#);
        assert!(!out.contains('<'), "{out}");
        assert!(!out.contains('>'), "{out}");
        assert!(!out.contains('"'), "{out}");
        assert_eq!(
            out,
            "&lt;img src=x onerror=&quot;alert(1)&quot;&gt;&amp;&#39;"
        );
    }

    /// A title carrying markup cannot break out of the page shell.
    #[test]
    fn a_hostile_title_cannot_escape_the_shell() {
        let html = page(
            "</title><script>alert(1)</script>",
            "/tmp/b",
            "",
            &Nav::default(),
            "<article/>",
        );
        let body = format!("{html:?}");
        assert!(!body.contains("<script>alert"), "{body}");
    }

    // ---- routes ----------------------------------------------------------
    //
    // Driven in memory with `tower::ServiceExt::oneshot`, the same way
    // `graph_api`'s route tests run: no TCP bind, so they are as fast and as
    // deterministic as any other unit test.

    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt as _;

    fn fixture(tag: &str, files: &[(&str, &str)]) -> PathBuf {
        static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
        let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let root = std::env::temp_dir().join(format!(
            "roteiro-okf-view-{}-{seq}-{tag}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        for (rel, content) in files {
            let path = root.join(rel);
            std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
            std::fs::write(&path, content).expect("write");
        }
        root
    }

    /// `(status, body)` for one GET.
    async fn get_(root: &std::path::Path, base: &str, uri: &str) -> (StatusCode, String) {
        let nav = Nav {
            bundle: Some(base.to_owned()),
            ..Nav::default()
        };
        let response = router(root.to_path_buf(), base, nav)
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");
        let status = response.status();
        let bytes = axum::body::to_bytes(response.into_body(), 1 << 22)
            .await
            .expect("body");
        (status, String::from_utf8_lossy(&bytes).into_owned())
    }

    fn sample() -> PathBuf {
        fixture(
            "routes",
            &[
                ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n"),
                (
                    "metrics/revenue.md",
                    "---\ntype: Metric\ntitle: Revenue\nverified: { by: human:alice, \
                     at: 2026-08-01T10:00:00Z }\n---\n\n# Revenue\n\nSee \
                     [cost](/metrics/cost.md).\n",
                ),
                (
                    "metrics/cost.md",
                    "---\ntype: Metric\ntitle: Cost\n---\n\n# Cost\n",
                ),
            ],
        )
    }

    /// A bundle with more concepts than a small budget will draw: one hub and
    /// eight leaves. Small enough to read, big enough to be **truncated**, which
    /// is the whole property under test — `sample()`'s two concepts cannot show
    /// the difference between a budget that binds and one that is ignored.
    fn crowded() -> PathBuf {
        let hub = format!(
            "---\ntype: Metric\ntitle: Hub\n---\n\n# Hub\n\n{}\n",
            (0..8)
                .map(|i| format!("[leaf {i}](/leaf/leaf-{i}.md)"))
                .collect::<Vec<_>>()
                .join(" ")
        );
        let leaves: Vec<(String, String)> = (0..8)
            .map(|i| {
                (
                    format!("leaf/leaf-{i}.md"),
                    format!("---\ntype: Metric\ntitle: Leaf {i}\n---\n\n# Leaf {i}\n"),
                )
            })
            .collect();
        let mut files: Vec<(&str, &str)> = vec![
            ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n"),
            ("hub/hub.md", hub.as_str()),
        ];
        files.extend(leaves.iter().map(|(a, b)| (a.as_str(), b.as_str())));
        fixture("crowded", &files)
    }

    #[tokio::test]
    async fn the_index_lists_the_bundle_and_counts_its_tiers() {
        let root = sample();
        let (status, body) = get_(&root, "", "/").await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("Revenue"), "{body}");
        assert!(body.contains("href=\"/c/metrics/revenue\""), "{body}");
        assert!(body.contains("human-reviewed"), "{body}");
        let _ = std::fs::remove_dir_all(&root);
    }

    #[tokio::test]
    async fn a_concept_renders_with_its_links_and_backlinks() {
        let root = sample();
        let (status, body) = get_(&root, "", "/c/metrics/revenue").await;
        assert_eq!(status, StatusCode::OK);
        // The body link was rewritten to a viewer route by the renderer.
        assert!(body.contains("href=\"/c/metrics/cost\""), "{body}");

        let (_, cost) = get_(&root, "", "/c/metrics/cost").await;
        assert!(cost.contains("Linked from"), "{cost}");
        assert!(cost.contains("metrics/revenue"), "{cost}");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// An unknown concept is a 404 page, not a 500 and not a blank 200.
    /// The entry page must not carry the graph it exists to avoid drawing.
    #[tokio::test]
    async fn the_graph_entry_page_is_a_list_and_not_the_whole_graph() {
        let root = sample();
        let (status, body) = get_(&root, "", "/graph").await;

        assert_eq!(status, StatusCode::OK);
        assert!(
            body.contains("Pick a concept to centre the graph on"),
            "the entry page says how to start: {body}"
        );
        assert!(
            body.contains("/graph?focus="),
            "and offers concepts to start from"
        );
        assert!(
            !body.contains("cytoscape.min.js"),
            "and draws nothing, so it costs no layout at all"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A focused view has to *say* it is partial, or a reader cannot tell a small
    /// bundle from a truncated picture of a large one.
    #[tokio::test]
    async fn a_focused_view_states_what_it_is_showing_and_of_how_much() {
        let root = sample();
        let (status, body) = get_(&root, "", "/graph?focus=metrics/revenue").await;

        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("id=\"scope\""), "a scope line exists: {body}");
        assert!(
            body.contains("focus=metrics%2Frevenue"),
            "and the fetch is scoped to the focus rather than the whole graph"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The bounds are the fix, so they are tested where they live.
    ///
    /// Separate from the wiring test below because one fixture cannot hold both
    /// halves: proving `limit` is clamped to 500 needs a bundle of more than 500
    /// concepts, and proving the handler *honours* a limit needs only a handful.
    /// A single test over the two-concept bundle passed whatever the clamp did —
    /// which is what the first draft of this was, and what an injection caught.
    #[test]
    fn the_graph_query_clamps_what_a_caller_may_ask_for() {
        let asked = GraphQuery {
            focus: None,
            depth: Some(99),
            limit: Some(999_999),
        };
        assert_eq!(asked.depth(), MAX_DEPTH, "depth is clamped");
        assert_eq!(asked.limit(), MAX_NODES, "and so is the node budget");

        let silent = GraphQuery {
            focus: None,
            depth: None,
            limit: None,
        };
        assert_eq!(silent.depth(), 1, "a silent caller gets one hop");
        assert_eq!(silent.limit(), DEFAULT_NODES);

        let zero = GraphQuery {
            focus: None,
            depth: Some(0),
            limit: Some(0),
        };
        assert_eq!(
            zero.depth(),
            1,
            "depth 0 is a concept page with extra steps, so it is not offered"
        );
        assert_eq!(zero.limit(), 1, "and the focus is always drawn");
    }

    /// And the handler has to actually use them.
    ///
    /// Nine concepts against a budget of three: an endpoint that ignored `limit`
    /// would return all nine and fail here, which the two-concept bundle could
    /// never have shown.
    #[tokio::test]
    async fn the_graph_api_honours_the_budget_it_was_given() {
        let root = crowded();
        let (status, body) = get_(&root, "", "/api/graph.json?focus=hub/hub&limit=3&depth=1").await;

        assert_eq!(status, StatusCode::OK);
        let json: serde_json::Value = serde_json::from_str(&body).expect("json");
        assert_eq!(
            json["scope"]["shown_nodes"], 3,
            "the budget binds rather than being ignored: {body}"
        );
        assert_eq!(
            json["scope"]["total_nodes"], 9,
            "against a bundle that holds more"
        );
        assert_eq!(
            json["scope"]["beyond"], 6,
            "and the six it did not draw are counted, not dropped: {body}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// `concentric` draws the highest-ranked node innermost, and every other node
    /// is ranked by its degree — so a *finite* rank for the focus is a threshold
    /// a neighbour can cross, and the picture then centres on something that is
    /// not the focus without saying so.
    ///
    /// Pinned as a string because the layout runs in the browser and Rust cannot
    /// reach it. That makes this a weak test of a real property, which is the
    /// trade: it cannot prove the layout is right, and it does stop the one
    /// regression that had already happened once — measured at 96 against a
    /// constant of 100, four short of firing.
    #[tokio::test]
    async fn the_focus_outranks_every_neighbour_by_construction() {
        let root = sample();
        let (status, body) = get_(&root, "", "/graph?focus=metrics/revenue").await;

        assert_eq!(status, StatusCode::OK);
        assert!(
            body.contains("?Infinity:n.degree()"),
            "the focus must not be ranked by a constant a degree can exceed: {body}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The inline script must **parse**, which nothing else here checks.
    ///
    /// It is thirty lines of JavaScript inside a Rust string literal, with every
    /// quote escaped and every line continued — the exact place a syntax error
    /// hides, and one that would ship silently: the page would serve 200 OK with
    /// a dead script and sit on "Loading…" for ever. The assertions around this
    /// one match *text*, so they would all still pass.
    ///
    /// Self-skips without `node`, like the model instruments in `rto-llama`: a
    /// checkout without it loses this check rather than failing on it.
    #[tokio::test]
    async fn the_inline_script_is_javascript_that_parses() {
        let Ok(node) = std::process::Command::new("node").arg("--version").output() else {
            eprintln!("SKIP: no `node` to parse the script with");
            return;
        };
        if !node.status.success() {
            eprintln!("SKIP: `node --version` failed");
            return;
        }

        let root = sample();
        let (_, body) = get_(&root, "", "/graph?focus=metrics/revenue").await;
        let script = body
            .rsplit_once("<script>")
            .and_then(|(_, tail)| tail.split_once("</script>"))
            .map(|(js, _)| js.to_owned())
            .expect("the focused page carries an inline script");

        let dir = fixture("script-check", &[("check.js", &script)]);
        let out = std::process::Command::new("node")
            .arg("--check")
            .arg(dir.join("check.js"))
            .output()
            .expect("run node");
        assert!(
            out.status.success(),
            "the inline script does not parse:\n{}\n--- script ---\n{script}",
            String::from_utf8_lossy(&out.stderr)
        );
        let _ = std::fs::remove_dir_all(&dir);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// `?focus=` with nothing after it is a request for the entry list, not for a
    /// concept whose id is the empty string. Taken literally it 404s every time.
    ///
    /// **Both routes**, because the first fix normalised the HTML one and left
    /// the JSON one 404ing on the same input — two call sites that disagreed
    /// about one rule, which is why the rule now lives on `GraphQuery::focus`.
    #[tokio::test]
    async fn an_empty_focus_is_the_entry_list_on_both_routes() {
        let root = sample();
        for uri in ["/graph?focus=", "/graph?focus=%20", "/graph"] {
            let (status, body) = get_(&root, "", uri).await;
            assert_eq!(status, StatusCode::OK, "{uri}");
            assert!(
                body.contains("Pick a concept to centre the graph on"),
                "{uri} must reach the entry list: {body}"
            );
        }
        for uri in [
            "/api/graph.json?focus=",
            "/api/graph.json?focus=%20",
            "/api/graph.json",
        ] {
            let (status, body) = get_(&root, "", uri).await;
            assert_eq!(status, StatusCode::OK, "{uri}: {body}");
            let json: serde_json::Value =
                serde_json::from_str(&body).unwrap_or_else(|e| panic!("{uri}: {e}: {body}"));
            assert!(
                json.get("hubs").is_some(),
                "{uri} must answer with the entry list, not a 404: {body}"
            );
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// An affordance that cannot do anything is worse than none: the reader
    /// concludes there is nothing more, rather than that this page will not draw
    /// it. At both maxima the page says which it is.
    #[tokio::test]
    async fn show_more_is_offered_only_when_it_can_widen_something() {
        let root = sample();

        let (_, growable) = get_(&root, "", "/graph?focus=metrics/revenue&limit=10&depth=1").await;
        assert!(
            growable.contains("&&true)"),
            "with room to grow, expanding is offered: {growable}"
        );

        let (_, maxed) = get_(
            &root,
            "",
            &format!("/graph?focus=metrics/revenue&limit={MAX_NODES}&depth={MAX_DEPTH}"),
        )
        .await;
        assert!(
            maxed.contains("&&false)"),
            "at both maxima it is not: {maxed}"
        );
        assert!(
            maxed.contains("This is the most this page draws"),
            "and the page says so instead of going quiet: {maxed}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// The API answers a bad focus with a 404 carrying JSON. The page has to
    /// *read* that: a script that reaches straight for `scope` throws on the
    /// error body and leaves the reader looking at "Loading…" for ever, which is
    /// a worse outcome than the 404 it was given.
    #[tokio::test]
    async fn the_page_reads_an_error_response_rather_than_throwing_on_it() {
        let root = sample();
        let (status, body) = get_(&root, "", "/graph?focus=nonesuch").await;

        assert_eq!(status, StatusCode::OK, "the page itself renders");
        assert!(
            body.contains("if(!res.ok||!res.g.scope){"),
            "the script checks the response before reading it: {body}"
        );
        assert!(
            body.contains("The graph could not be read."),
            "and has something to say when it cannot: {body}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A mistyped id is a 404. An empty drawing would read as a real concept with
    /// no links, which is a different answer and a wrong one.
    ///
    /// The **body** is asserted as well as the status, and by parsing rather than
    /// by matching text. Checking the status alone let a malformed body through
    /// review: the id was interpolated as a `serde_json::Value`, which renders
    /// with its own quotes, so the error read `"no concept "nonesuch""` and no
    /// client could parse it.
    #[tokio::test]
    async fn an_unknown_focus_is_a_404_carrying_json_a_client_can_read() {
        let root = sample();
        let (status, body) = get_(&root, "", "/api/graph.json?focus=nonesuch").await;

        assert_eq!(status, StatusCode::NOT_FOUND);
        let json: serde_json::Value =
            serde_json::from_str(&body).unwrap_or_else(|e| panic!("{e}: {body}"));
        assert_eq!(json["error"], "no concept nonesuch");

        // An id may hold a quote, which is the case the escaping exists for and
        // the one a hand-built string gets wrong.
        let (status, body) = get_(&root, "", "/api/graph.json?focus=a%22b").await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        let json: serde_json::Value =
            serde_json::from_str(&body).unwrap_or_else(|e| panic!("{e}: {body}"));
        assert_eq!(json["error"], r#"no concept a"b"#);
        let _ = std::fs::remove_dir_all(&root);
    }

    #[tokio::test]
    async fn an_unknown_concept_is_a_404() {
        let root = sample();
        let (status, body) = get_(&root, "", "/c/metrics/nope").await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert!(body.contains("no concept"), "{body}");
        // Which concept, and where back to — asserted separately, because the two
        // are interchangeable at the type level. They were in fact swapped once
        // (#785 review): the page named the mount path as the missing concept and
        // linked to the concept id, and "no concept" alone could not see it.
        assert!(body.contains("<code>metrics/nope</code>"), "{body}");
        assert!(body.contains("<a href=\"/\">Back to the bundle"), "{body}");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// **A file the viewer will not render is asked for as an attachment.**
    ///
    /// The type already comes from a closed allow-list, so a bundle cannot say
    /// what its bytes *are*; this says what they are *for*. Without it the
    /// response relied on browsers happening to download
    /// `application/octet-stream` — their convention, not something the response
    /// requested, and ADR-0024's first draft described that as "served as an
    /// attachment" when no header said so.
    ///
    /// The image case is the half worth pinning: the viewer embeds those with
    /// `<img>`, so an attachment disposition there would break every concept page
    /// that shows one.
    #[tokio::test]
    async fn a_file_outside_the_image_allow_list_is_offered_as_an_attachment() {
        let root = fixture(
            "disposition",
            &[
                ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# B\n"),
                ("img/logo.svg", "<svg/>"),
                ("docs/policy.pdf", "%PDF-1.4 not really"),
            ],
        );
        let disposition = |uri: &'static str| {
            let root = root.clone();
            async move {
                let response = router(root, "", Nav::default())
                    .oneshot(
                        Request::builder()
                            .uri(uri)
                            .body(Body::empty())
                            .expect("req"),
                    )
                    .await
                    .expect("response");
                response
                    .headers()
                    .get(header::CONTENT_DISPOSITION)
                    .map(|v| v.to_str().expect("ascii").to_owned())
            }
        };

        assert_eq!(
            disposition("/f/docs/policy.pdf").await.as_deref(),
            Some("attachment"),
            "a type the viewer will not render is handed over, not shown"
        );
        assert_eq!(
            disposition("/f/img/logo.svg").await,
            None,
            "an image the viewer embeds is not an attachment"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// **A file out of the bundle is served under a policy of its own.**
    ///
    /// `/f/` serves bytes a peer wrote, and one of the types it will label is
    /// `image/svg+xml` — active content, unlike every other entry in the table.
    /// Under the page policy, `script-src` falls back to `default-src 'self'`, so
    /// an SVG opened directly could have referenced `/f/anything.js` from the same
    /// bundle. The mime table and `nosniff` did stop that, but by coincidence
    /// rather than by policy.
    ///
    /// Asserted as a *difference* from [`CSP`] rather than as a literal string:
    /// the point is that the two are not the same policy, and a future edit that
    /// unified them would be the regression.
    #[tokio::test]
    async fn a_bundle_file_is_served_under_a_stricter_policy_than_a_page() {
        let root = fixture(
            "file-csp",
            &[
                ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# B\n"),
                ("img/logo.svg", "<svg/>"),
            ],
        );
        let policy = |uri: &'static str| {
            let root = root.clone();
            async move {
                let response = router(root, "", Nav::default())
                    .oneshot(
                        Request::builder()
                            .uri(uri)
                            .body(Body::empty())
                            .expect("req"),
                    )
                    .await
                    .expect("response");
                response
                    .headers()
                    .get(header::CONTENT_SECURITY_POLICY)
                    .expect("every response carries a policy")
                    .to_str()
                    .expect("ascii")
                    .to_owned()
            }
        };

        let file = policy("/f/img/logo.svg").await;
        let page = policy("/").await;
        assert_ne!(file, page, "a peer's bytes do not get the page's policy");
        assert!(
            file.contains("sandbox"),
            "a directly-opened file is sandboxed: {file}"
        );
        assert!(
            file.contains("default-src 'none'"),
            "and fetches nothing: {file}"
        );
        assert!(
            !file.contains("'self'"),
            "`'self'` is what let an SVG reach the rest of the bundle: {file}"
        );

        // The refusal path carries it too — "every response" has to mean every.
        let missing = policy("/f/img/absent.png").await;
        assert_eq!(missing, file, "a refusal carries the same policy as a hit");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// **A symlinked directory does not send the stamp walk round in circles.**
    ///
    /// The stamp decides whether to re-read the bundle, so it runs on *every*
    /// request over a directory a peer controls, and `loop -> ..` inside one
    /// would send it round for ever.
    ///
    /// **A characterisation test, and it was nearly mislabelled a guard.**
    /// Reverting `file_type()` to `metadata()` leaves it green, because
    /// `DirEntry::metadata` is `lstat` on Unix and does not follow the link —
    /// checked directly, after a reproduction written in Python appeared to
    /// prove the opposite. Python's `DirEntry.stat()` follows; Rust's does not.
    /// The reproduction was measuring itself.
    ///
    /// The property is therefore upheld today by platform behaviour that the std
    /// documentation explicitly disclaims — it says `metadata` "will traverse
    /// symbolic links". `file_type()` makes it hold by contract instead, and
    /// this pins the property so a future walk that does follow gets caught.
    #[cfg(unix)]
    #[test]
    fn a_symlinked_directory_does_not_make_the_stamp_walk_forever() {
        use std::os::unix::fs::symlink;
        let root = fixture(
            "stamp-loop",
            &[("index.md", "---\nokf_version: \"0.2\"\n---\n\n# B\n")],
        );
        symlink("..", root.join("loop")).expect("symlink to the parent");
        symlink("/", root.join("everything")).expect("symlink to the root");

        let first = stamp(&root);
        // Two real entries — `index.md` and the two links, counted as the links
        // they are rather than followed.
        assert_eq!(first.files, 3, "the links count as files, not as trees");

        // Stable across calls, so it does not force a reload on every request.
        assert!(
            first == stamp(&root),
            "the stamp is stable when nothing changed"
        );

        // And it still notices a real edit.
        std::fs::write(root.join("second.md"), "---\ntype: Metric\n---\n\n# S\n").expect("write");
        let added = stamp(&root);
        assert!(first != added, "a new file changes the stamp");

        // Including the change no file's `mtime` records. A rename alters
        // neither the file count nor any file's timestamp, so a files-only stamp
        // was byte-identical across one and the cache never reloaded — the
        // viewer went on serving the old concept id and 404ing the new one. The
        // directory's own `mtime` is what moves, which is why the walk reads it.
        std::thread::sleep(std::time::Duration::from_millis(1100));
        std::fs::rename(root.join("second.md"), root.join("renamed.md")).expect("rename");
        assert!(
            added != stamp(&root),
            "a rename must change the stamp, or the viewer serves a concept that \
             no longer exists under that id"
        );

        // And the same holds when the *root itself* is a symlink, which is how
        // somebody points the viewer at a bundle without copying it. Reading the
        // link's own `mtime` rather than its target's would leave this stale
        // again: a rename inside the target never touches the link.
        let alias = root.with_extension("alias");
        let _ = std::fs::remove_file(&alias);
        symlink(&root, &alias).expect("symlink the root");
        let via_alias = stamp(&alias);
        std::thread::sleep(std::time::Duration::from_millis(1100));
        std::fs::rename(root.join("renamed.md"), root.join("again.md")).expect("rename");
        assert!(
            via_alias != stamp(&alias),
            "a rename must change the stamp seen through a symlinked root too"
        );
        let _ = std::fs::remove_file(&alias);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// **`/f/` will not read an unbounded file into memory.**
    ///
    /// The bundle is somebody else's, and the route reads a whole file before
    /// answering, so without a bound one large file is memory pressure a peer
    /// chooses for this process. Checked at `metadata().len()` rather than on
    /// the bytes, because `std::fs::read` allocates to the file's length and a
    /// check afterwards has already paid the cost.
    ///
    /// The fixture is written just over the bound, so it also pins the bound
    /// being *applied* rather than merely defined — a constant nothing consults
    /// reads exactly like this test passing.
    #[tokio::test]
    async fn the_file_route_refuses_a_file_too_large_to_hold() {
        let root = fixture(
            "big-file",
            &[
                ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# B\n"),
                ("img/logo.svg", "<svg/>"),
            ],
        );
        let big = root.join("img/huge.bin");
        // Sparse where the filesystem allows it, so this costs a few bytes on
        // disk rather than 32 MiB per test run.
        let handle = std::fs::File::create(&big).expect("create");
        handle
            .set_len(MAX_FILE_BYTES + 1)
            .expect("size the file past the bound");
        drop(handle);

        let (status, _) = get_(&root, "", "/f/img/huge.bin").await;
        assert_eq!(
            status,
            StatusCode::NOT_FOUND,
            "a file past the bound must not be served"
        );

        // And the bound is a bound, not a ban: the small file beside it is fine.
        let (ok, body) = get_(&root, "", "/f/img/logo.svg").await;
        assert_eq!(ok, StatusCode::OK);
        assert!(body.contains("svg"), "{body}");
        let _ = std::fs::remove_dir_all(&root);
    }

    /// **The file route re-applies the guard**, because a reader can type a URL.
    ///
    /// The renderer only ever emits a `/f/` href for a path it has already
    /// checked, so a route that trusted its input would be a guard on the wrong
    /// side of the boundary — and nothing would fail until someone tried.
    #[tokio::test]
    async fn the_file_route_serves_only_from_inside_the_bundle() {
        let root = fixture(
            "files",
            &[
                ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# B\n"),
                ("img/logo.svg", "<svg/>"),
            ],
        );
        // Outside the bundle entirely, and readable — so a route without the
        // guard would happily return it.
        let outside = root.parent().expect("parent").join("outside.txt");
        std::fs::write(&outside, "secret").expect("write");

        let (ok, body) = get_(&root, "", "/f/img/logo.svg").await;
        assert_eq!(ok, StatusCode::OK);
        assert!(body.contains("svg"), "{body}");

        for hostile in [
            "/f/../outside.txt",
            "/f/img/../../outside.txt",
            "/f/..%2Foutside.txt",
            "/f/img/absent.png",
        ] {
            let (status, body) = get_(&root, "", hostile).await;
            assert_ne!(
                status,
                StatusCode::OK,
                "`{hostile}` must not be served: {body}"
            );
            assert!(!body.contains("secret"), "`{hostile}` leaked: {body}");
        }
        let _ = std::fs::remove_file(&outside);
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Nested under `serve`, every generated href carries the mount prefix.
    ///
    /// Without this the viewer would look right standalone and 404 on every link
    /// the moment it was mounted beside the explorer — the failure the `base`
    /// field exists to prevent.
    #[tokio::test]
    async fn a_nested_mount_prefixes_every_href() {
        let root = sample();
        let (status, body) = get_(&root, "/okf", "/").await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("href=\"/okf/c/metrics/revenue\""), "{body}");
        assert!(body.contains("href=\"/okf/okf-viewer.css\""), "{body}");
        assert!(body.contains("href=\"/okf/graph\""), "{body}");
        assert!(
            !body.contains("href=\"/c/"),
            "an unprefixed href would 404 when nested: {body}"
        );

        // **And a concept page, whose body links the renderer builds.**
        //
        // This half is the one that mattered: the index carries no rendered
        // markdown, so checking only the chrome let unprefixed body links pass.
        // Nested, every link inside a concept's prose would have 404'd while the
        // page around it looked correct.
        let (status, page) = get_(&root, "/okf", "/c/metrics/revenue").await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            page.contains("href=\"/okf/c/metrics/cost\""),
            "a link in the body must carry the prefix: {page}"
        );
        assert!(
            !page.contains("href=\"/c/") && !page.contains("src=\"/f/"),
            "no unprefixed href anywhere on the page: {page}"
        );
        let _ = std::fs::remove_dir_all(&root);
    }

    /// Every page carries a policy that cannot reach the network.
    /// **Every** response carries the policy, not only the HTML ones.
    ///
    /// The module documentation says "every response". A test that checked only
    /// the two HTML routes would have let that sentence describe the happy path
    /// while the assets, the JSON and the refusals went bare — and a reader could
    /// not tell the difference from the sentence.
    #[tokio::test]
    async fn responses_carry_a_content_security_policy() {
        let root = sample();
        for uri in [
            "/",
            "/c/metrics/revenue",
            "/c/does/not/exist",
            "/graph",
            "/api/graph.json",
            "/okf-viewer.css",
            "/cytoscape.min.js",
            "/f/../escape",
        ] {
            let response = router(root.clone(), "", Nav::default())
                .oneshot(
                    Request::builder()
                        .uri(uri)
                        .body(Body::empty())
                        .expect("req"),
                )
                .await
                .expect("response");
            let csp = response
                .headers()
                .get(header::CONTENT_SECURITY_POLICY)
                .and_then(|v| v.to_str().ok())
                .unwrap_or_default()
                .to_owned();
            // Two policies, and which one applies is the point: the viewer's
            // own pages load their own stylesheet and script, so they need
            // `'self'`; bytes out of a peer's bundle need nothing at all. What
            // this asserts of every route is that *some* policy is present and
            // that nothing can execute.
            if uri.starts_with("/f/") {
                assert!(csp.contains("default-src 'none'"), "{uri}: {csp}");
                assert!(csp.contains("sandbox"), "{uri}: {csp}");
            } else {
                assert!(csp.contains("default-src 'self'"), "{uri}: {csp}");
                assert!(csp.contains("object-src 'none'"), "{uri}: {csp}");
            }
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    /// A path that is not a bundle is refused rather than served empty.
    #[tokio::test]
    async fn a_path_that_is_not_a_bundle_is_refused() {
        let root = std::env::temp_dir().join("roteiro-okf-view-not-a-bundle");
        let _ = std::fs::remove_dir_all(&root);
        let (status, body) = get_(&root, "", "/").await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert!(body.contains("Not a readable OKF bundle"), "{body}");
    }

    // ---- the mount layer -------------------------------------------------
    //
    // `mounts_router` is the only part of this module that does not serve a
    // bundle: it decides where bundles live and what the base itself does. Its
    // failures are route-table failures — a shadowed nest, a claimed `/`, an
    // href that 404s — none of which any type catches, so they are driven
    // through a whole merged router rather than asserted on the pieces.

    /// A bundle whose one concept names it, so two mounts can be told apart by
    /// what they serve rather than by the URL they were asked for.
    fn named_bundle(tag: &str, title: &str) -> PathBuf {
        let concept = format!("---\ntype: Metric\ntitle: {title}\n---\n\n# {title}\n");
        fixture(
            tag,
            &[
                ("index.md", "---\nokf_version: \"0.2\"\n---\n\n# Bundle\n"),
                ("metrics/only.md", &concept),
            ],
        )
    }

    fn mount_at(slug: &str, root: PathBuf) -> Mount {
        Mount {
            slug: slug.to_owned(),
            label: slug.to_owned(),
            origin: "test".to_owned(),
            root,
        }
    }

    /// A host that already owns `/`, which is what both callers are: `roteiro
    /// serve` and `roteiro explorer` merge the mount layer into a router that
    /// is already serving something at the root.
    fn host() -> Router {
        Router::new().route("/", get(|| async { "explorer" }))
    }

    async fn get_mounted(app: &Router, uri: &str) -> (StatusCode, String, Option<String>) {
        let response = app
            .clone()
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");
        let status = response.status();
        let location = response
            .headers()
            .get(axum::http::header::LOCATION)
            .map(|v| v.to_str().expect("location").to_owned());
        let bytes = axum::body::to_bytes(response.into_body(), 1 << 22)
            .await
            .expect("body");
        (
            status,
            String::from_utf8_lossy(&bytes).into_owned(),
            location,
        )
    }

    /// Every `href="…"` in a page, in order.
    fn hrefs(body: &str) -> Vec<String> {
        body.match_indices("href=\"")
            .filter_map(|(i, m)| {
                let rest = &body[i + m.len()..];
                rest.find('"').map(|end| rest[..end].to_owned())
            })
            .collect()
    }

    /// A slug is one readable path segment, whatever the label was.
    #[test]
    fn a_slug_is_one_readable_path_segment() {
        assert_eq!(slug("Roteiro/Roteiro"), "Roteiro-Roteiro");
        assert_eq!(slug("my repo"), "my-repo");
        assert_eq!(slug("a.b_c-d"), "a.b_c-d");
        // Runs fold to one separator and the ends are trimmed, so no slug is
        // ever empty at an end or doubled in the middle.
        assert_eq!(slug("  spaced  out  "), "spaced-out");
        // Nothing survivable left: a name is still needed for the route.
        assert_eq!(slug("日本語"), "bundle");
        assert_eq!(slug(""), "bundle");
    }

    /// Two labels that fold to one slug stay separately reachable.
    ///
    /// This is the defect `disambiguate` exists for: `nest` does not complain
    /// about a prefix it already holds, so without it the second mount takes
    /// the first's URL and one bundle is silently unreachable. The fixture has
    /// to *contain* the collision — asserted before disambiguating, or the test
    /// passes on labels that never collided.
    #[tokio::test]
    async fn two_labels_that_fold_alike_stay_separately_reachable() {
        let mut mounts = vec![
            Mount {
                slug: slug("my repo"),
                label: "my repo".to_owned(),
                origin: "a".to_owned(),
                root: named_bundle("fold-a", "Alpha"),
            },
            Mount {
                slug: slug("my/repo"),
                label: "my/repo".to_owned(),
                origin: "b".to_owned(),
                root: named_bundle("fold-b", "Beta"),
            },
        ];
        assert_eq!(
            mounts[0].slug, mounts[1].slug,
            "the fixture must contain the collision it is testing"
        );
        disambiguate(&mut mounts);
        let (first, second) = (mounts[0].slug.clone(), mounts[1].slug.clone());
        assert_eq!(first, "my-repo", "the first keeps the readable name");
        assert_eq!(second, "my-repo-2");

        let app = host().merge(mounts_router("/okf", mounts, None));
        let (status, body, _) = get_mounted(&app, &format!("/okf/{first}")).await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("Alpha") && !body.contains("Beta"), "{body}");
        let (status, body, _) = get_mounted(&app, &format!("/okf/{second}")).await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("Beta") && !body.contains("Alpha"), "{body}");
    }

    /// The mount layer merges into a host that already owns `/`.
    ///
    /// The chooser is registered at `base` as an absolute path for this reason.
    /// Registering it at `/` — the natural thing to write for a router that is
    /// about to be nested — makes axum panic at startup with `Overlapping
    /// method route`, which no compiler catches and no bundle test reaches.
    #[tokio::test]
    async fn the_mount_layer_merges_into_a_host_that_owns_the_root() {
        let mounts = vec![
            mount_at("one", named_bundle("merge-a", "Alpha")),
            mount_at("two", named_bundle("merge-b", "Beta")),
        ];
        let app = host().merge(mounts_router("/okf", mounts, Some("/".to_owned())));
        let (status, body, _) = get_mounted(&app, "/").await;
        assert_eq!(status, StatusCode::OK);
        assert_eq!(body, "explorer", "the host keeps its own root");
        assert_eq!(get_mounted(&app, "/okf").await.0, StatusCode::OK);
    }

    /// A lone bundle redirects rather than offering a one-row chooser.
    #[tokio::test]
    async fn a_lone_bundle_redirects_from_the_mount_base() {
        let mounts = vec![mount_at("only", sample())];
        let app = host().merge(mounts_router("/okf", mounts, None));
        let (status, _, location) = get_mounted(&app, "/okf").await;
        assert_eq!(status, StatusCode::TEMPORARY_REDIRECT);
        assert_eq!(location.as_deref(), Some("/okf/only"));
        assert_eq!(get_mounted(&app, "/okf/only").await.0, StatusCode::OK);
    }

    /// Every link the chooser writes resolves, and it is styled.
    ///
    /// The chooser is the one page that is *not* inside a bundle, so it is the
    /// one page whose stylesheet and whose base-relative hrefs no other test
    /// touches: `{base}/okf-viewer.css` resolves to a bundle's route on every
    /// other page and to nothing at all here.
    #[tokio::test]
    async fn every_link_the_chooser_writes_resolves() {
        let mounts = vec![
            mount_at("one", named_bundle("chooser-a", "Alpha")),
            mount_at("two", named_bundle("chooser-b", "Beta")),
        ];
        let app = host().merge(mounts_router("/okf", mounts, Some("/".to_owned())));
        let (status, body, _) = get_mounted(&app, "/okf").await;
        assert_eq!(status, StatusCode::OK);
        let links = hrefs(&body);
        for want in ["/okf/one", "/okf/two", "/okf/okf-viewer.css", "/"] {
            assert!(links.iter().any(|h| h == want), "{want} missing: {links:?}");
        }
        for link in &links {
            let (status, _, _) = get_mounted(&app, link).await;
            assert_eq!(status, StatusCode::OK, "{link}");
        }
        let (status, css, _) = get_mounted(&app, "/okf/okf-viewer.css").await;
        assert_eq!(status, StatusCode::OK);
        assert!(
            css.contains("--ink"),
            "the chooser's stylesheet is the viewer's"
        );
    }

    /// A nested bundle's own links resolve, index included.
    ///
    /// `nest("/okf/x")` serves `/okf/x` and **not** `/okf/x/`, so a page that
    /// writes `{base}/` for "this bundle's index" 404s on that one link while
    /// every other link on it works. `roteiro serve` has nested this viewer
    /// since ADR-0022 v1.0 and its "Concepts" link has 404'd throughout.
    #[tokio::test]
    async fn every_link_a_nested_bundle_writes_resolves() {
        let mounts = vec![
            mount_at("one", named_bundle("nested-a", "Alpha")),
            mount_at("two", named_bundle("nested-b", "Beta")),
        ];
        let app = host().merge(mounts_router("/okf", mounts, Some("/".to_owned())));
        let (status, body, _) = get_mounted(&app, "/okf/one").await;
        assert_eq!(status, StatusCode::OK);
        let links = hrefs(&body);
        assert!(
            links.iter().any(|h| h == "/okf/one"),
            "no index link: {links:?}"
        );
        assert!(
            !links.iter().any(|h| h == "/okf/one/"),
            "a trailing slash under `nest` is a 404: {links:?}"
        );
        for link in &links {
            let (status, _, _) = get_mounted(&app, link).await;
            assert_eq!(status, StatusCode::OK, "{link}");
        }
    }

    /// A bundle offers only the neighbours it actually has.
    ///
    /// The bare case — one bundle, no repository — is the whole reason the fold
    /// is allowed to replace `roteiro okf view <path>`: it must not link to an
    /// explorer that is not running, nor to a chooser that would redirect back.
    #[tokio::test]
    async fn a_lone_bundle_with_no_explorer_offers_neither_link() {
        let mounts = vec![mount_at("bare", sample())];
        let app = Router::new().merge(mounts_router("/okf", mounts, None));
        let (status, body, _) = get_mounted(&app, "/okf/bare").await;
        assert_eq!(status, StatusCode::OK);
        assert!(!body.contains("All bundles"), "{body}");
        assert!(!body.contains(">Explorer<"), "{body}");
        assert!(body.contains("Concepts"), "{body}");
    }

    /// A nested 404 links back to *its own* bundle, and that link resolves.
    ///
    /// `every_link_a_nested_bundle_writes_resolves` walks a page that exists; this
    /// is the other page the viewer can produce, and it is the one where the id
    /// and the href sit side by side as two `{}` of the same type.
    #[tokio::test]
    async fn a_nested_404_links_back_to_its_own_bundle() {
        let mounts = vec![mount_at("one", sample())];
        let app = host().merge(mounts_router("/okf", mounts, None));
        let (status, body, _) = get_mounted(&app, "/okf/one/c/metrics/nope").await;
        assert_eq!(status, StatusCode::NOT_FOUND);
        assert!(body.contains("<code>metrics/nope</code>"), "{body}");
        let links = hrefs(&body);
        assert!(
            links.iter().any(|h| h == "/okf/one"),
            "no way back: {links:?}"
        );
        for link in &links {
            let (status, _, _) = get_mounted(&app, link).await;
            assert_eq!(status, StatusCode::OK, "{link}");
        }
    }

    /// A bundle cannot be named over the mount base's own stylesheet.
    ///
    /// `disambiguate` resolving collisions *between bundles* is not enough: the
    /// base owns routes too, and axum does not shadow an overlapping one — it
    /// panics at startup. So this is not an unreachable bundle, it is a server
    /// that does not boot, reachable from an ordinary project name because
    /// [`slug`] folds `okf viewer.css` onto the reserved segment. Raised by
    /// review on #785.
    #[tokio::test]
    async fn a_bundle_cannot_be_named_over_the_mount_bases_stylesheet() {
        assert_eq!(
            slug("okf viewer.css"),
            "okf-viewer.css",
            "the fixture must contain the collision it is testing"
        );
        let mut mounts = vec![Mount {
            slug: slug("okf viewer.css"),
            label: "okf viewer.css".to_owned(),
            origin: "test".to_owned(),
            root: named_bundle("reserved", "Alpha"),
        }];
        disambiguate(&mut mounts);
        assert_eq!(
            mounts[0].slug, "okf-viewer.css-2",
            "moved off the reserved segment"
        );

        // Both survive: the base keeps its stylesheet, the bundle keeps a home.
        let app = host().merge(mounts_router("/okf", mounts, None));
        let (status, css, _) = get_mounted(&app, "/okf/okf-viewer.css").await;
        assert_eq!(status, StatusCode::OK);
        assert!(css.contains("--ink"), "not the stylesheet: {css:.80}");
        let (status, body, _) = get_mounted(&app, "/okf/okf-viewer.css-2").await;
        assert_eq!(status, StatusCode::OK);
        assert!(body.contains("Alpha"), "{body}");
    }

    /// A mount path that could leave an attribute is refused, not rendered.
    ///
    /// `base` is interpolated raw into `href`/`src` at a dozen call sites, which
    /// review on #785 read as a missing `escape`. It is not: escaping is for
    /// text, and the pages rely on `base` being slug-safe by construction. This
    /// turns that from an assumption into a checked one — the assertion is the
    /// contract, and these are the strings that violate it.
    #[test]
    fn a_mount_path_that_could_leave_an_attribute_is_refused() {
        // What the module actually builds, all accepted.
        for ok in ["", "/okf", "/okf/Roteiro-Roteiro", "/okf/a.b_c-d"] {
            assert_mountable(ok);
        }
        for bad in [
            "/okf/\"><script>alert(1)</script>",
            "/okf/a b",
            "/okf/a/",
            "okf",
            "/okf//x",
        ] {
            assert!(
                std::panic::catch_unwind(|| assert_mountable(bad)).is_err(),
                "accepted a mount path it cannot safely write: {bad:?}"
            );
        }
    }

    /// A hostile mount path stops the router being built at all.
    ///
    /// The assertion above is only worth having if the constructors run it, and
    /// both do — a page rendered from a bad `base` is the outcome this refuses.
    #[test]
    fn a_hostile_base_cannot_reach_a_page() {
        let root = sample();
        let hostile = "/okf/\"><script>alert(1)</script>";
        assert!(
            std::panic::catch_unwind(|| router(root.clone(), hostile, Nav::default())).is_err(),
            "a bundle router was built on a hostile base"
        );
        assert!(
            std::panic::catch_unwind(|| mounts_router(hostile, Vec::new(), None)).is_err(),
            "a mount layer was built on a hostile base"
        );
        let _ = std::fs::remove_dir_all(&root);
    }
}