zenkey-model 0.24.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
//! `link.v1`: what crosses a constrained face
//! (`spec/profiles/link/v1.md`, #769), and `link.v2`: the transport it runs
//! (`spec/profiles/link/v2.md`, #988 L1).
//!
//! The profile's session-free half: the exposure a contract gives a
//! resource (§2.2), the face policy a deployment writes and its lints
//! (§2.1), the plan a generator derives from both (§2.3–§2.12), every
//! revision of an interface read together, how a generator keeps every
//! other principal's subject off a face (§2.4), and the checks of a
//! router's block (§2.15), whether its access control is enabled among
//! them (0.7, F-124). A far principal two faces name carries both plans'
//! denies on each, which the linter warns of (§2.1, §2.4, 0.7, F-125).
//!
//! ```text
//! exposure(kind, annotations)       ─▶ host │ link │ invalid │ ignored
//! crossing(token, templated, …)     ─▶ downsampled │ whole │ denied │ none, + reason
//! parse(face policy TOML)           ─▶ the policy, or the findings that refuse it
//! plan(policy, deployment)          ─▶ per face: denies, downsampling, attachment,
//!                                      window floors, liveness evidence, warnings
//! narrowed(policy, is_far)          ─▶ the link protocols a principal's subject keeps
//! check_windows / check_block /
//!   check_subjects /
//!   check_narrowing                 ─▶ findings
//! ```
//!
//! There is no session here and no router: a generator writes the plan
//! into a router's configuration (`zenkey-fleet`'s `acl gen`), and a tool
//! reads a block somebody says the router runs. The deployment's services
//! and the contracts come in as values.
//!
//! **`link.v2`** (#988 L1) is read by the same [`parse`]: a policy whose
//! `profile` is `"link.v2"` adds the router's [`Transport`] (v2 §2.16), the
//! [`Binding`] it runs, which names its link protocols (v2 §2.4) and its
//! defaults (v2 §2.19), the catalog's id, and per face the loss, the ARQ
//! and the reply timeout (v2 §2.1); one without `profile` is a `link.v1`
//! policy, read as it was. A v2 face's `batch_bytes` and `lease_ms` are
//! its `[transport]`'s, so the plan and §2.10 read both profiles alike.
//!
//! **link.v2's contract side** (#988 L3, v2 0.3): a contract that lists
//! `link.v2` types every resource it exposes as packed ([`contract_findings`],
//! `packed_required`, v2 §2.17); a face's `frames` lists the frame resources
//! that cross it, each at its cadence, and its `horizon_s` is the shortest
//! horizon it affords (v2 §2.1, §2.7, §2.12); and under a link.v2 policy the
//! plan denies a timed stream rather than downsample it (v2 §2.8), refuses a
//! crossing revision the deployment's catalog lacks (v2 §2.18), and weighs
//! what crosses against the face (`not_packed`, `frame_unlisted`,
//! `horizon_under_face`, `block_over_batch`, `keep_alive_not_suppressed`,
//! `timed_downsampled`).
//!
//! **What fits one batch** (#1136, link.v1 0.22, v2 0.30): `frame_over_batch`
//! and `block_over_batch` weigh a put's payload with its [`allowance`], what
//! zenoh 1.10.1 writes beside it: the put's header and the payload's length,
//! the push's and the frame's QoS extensions where the resource's QoS
//! ([`PutQos`]) has them, the frame's header at the sequence width's widest
//! ([`Sequence::max_bytes`], 32 bits under a link.v1 policy), and the
//! batch's 2-byte length on a link that may be streamed. Measured at the
//! bound on zenoh-modem's RF face.
//!
//! **A device face** (#982 H1, v2 0.7): `attach = "device"` with `devices`,
//! the owners on a first hop by address (v2 §2.1, §2.5). Each device is a
//! listed owner on every face ([`FacePolicy::owners`]), but for
//! downsampling on its own face (v2 §2.8); the plan refuses one that
//! implements `archive.v1` or a governed interface (`presence_required`),
//! warns of its `epoch` templates (`epoch_on_device`), and carves `zk` into
//! three denies, so that an instance key crosses on core §11.2's Own row's
//! pairs alone ([`OWN_PAIRS`], v2 §2.6); [`check_block`] reads that carve
//! on a device face (v2 §2.15).
//!
//! ```text
//! crossing_v2(token, shape, …)      ─▶ link.v2's reading of one resource
//! contract_findings(contract)       ─▶ packed_required, per exposed resource
//! ```
//!
//! ```text
//! Transport::value(key)             ─▶ the value a generator writes at zenoh's key
//! StatedTransport::read(config)     ─▶ the keys a router's configuration states
//! check_transport(policy, router,
//!                 peer)             ─▶ transport_differs, wait_under_lease, peer_differs,
//!                                      face_timestamping
//! check_catalog(policy, held)       ─▶ catalog_mismatch
//! ```

use std::cmp::Ordering;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;

use serde::Serialize;
use serde_json::Value;
use zenoh_keyexpr::keyexpr;

use crate::authoring::Kind;
use crate::chunk::is_plain_chunk;
use crate::contract::{Contract, Resource};
use crate::freshness::{self, Horizon};
use crate::grammar::KindToken;
use crate::template::{Segment, Template};

/// The profile's id, as a contract lists it in `uses`.
pub const PROFILE: &str = "link.v1";

/// `archive.v1`'s interface id: a device implementing it is
/// `presence_required` (v2 §2.5).
const ARCHIVE: &str = "archive.v1";

/// The profile's name, as an annotation key's prefix carries it.
pub const NAME: &str = "link";

/// The one annotation key (§4).
pub const EXPOSURE: &str = "link.exposure";

/// The published vocabulary (§4): the keys under `link.`, which W105 reads
/// in place of core Appendix D's interim row (core 0.29).
pub const VOCABULARY: &[&str] = &["exposure"];

/// `link.v2`'s id, as a face policy's `profile` names it (v2 §2.1), and as
/// a contract lists it in `uses` (v2 §2.17).
pub const PROFILE_V2: &str = "link.v2";

/// Whether a contract lists `link.v2` in `uses`: it then types every
/// resource it exposes as packed (v2 §2.17).
#[must_use]
pub fn uses_v2(c: &Contract) -> bool {
    c.uses.iter().any(|u| u.to_string() == PROFILE_V2)
}

/// The bytes of the envelope a packed record or a frame travels in, with a
/// 32-bit run (core §7.5): CH, the run and the seq.
pub const ENVELOPE_BYTES: u64 = 8;

/// zenoh's transport lease, `transport.link.tx.lease`, when a face policy
/// gives none (§2.1).
pub const DEFAULT_LEASE_MS: u64 = 10_000;

/// The core's tombstone window when a deployment configures none (core S3).
pub const DEFAULT_WINDOW_S: u64 = 60;

/// Stock zenoh's link protocol names (`InterceptorLink`, kebab-case), the
/// values `select.link_protocols` takes (§2.1): 1.10.1's nine, and 1.10.2's,
/// the same (`zenoh-config`'s `lib.rs`, line 317 in 1.10.1 and 320 in
/// 1.10.2); `zm-1.10.2-r1` adds `unixsock-dgram` after `unixsock-stream`
/// (v2 §2.4).
const STOCK_PROTOCOLS: &[&str] = &[
    "tcp",
    "udp",
    "tls",
    "quic",
    "serial",
    "unixpipe",
    "unixsock-stream",
    "vsock",
    "ws",
];

/// The fork's `InterceptorLink` (`commons/zenoh-config/src/lib.rs` at
/// `zm-1.10.2-r1`, lines 320–331), in its order.
const ZM_1_10_2_R1_PROTOCOLS: &[&str] = &[
    "tcp",
    "udp",
    "tls",
    "quic",
    "serial",
    "unixpipe",
    "unixsock-stream",
    "unixsock-dgram",
    "vsock",
    "ws",
];

/// The nine access-control messages, in the order a plan lists them (§0).
pub const MESSAGES: [&str; 9] = [
    "put",
    "delete",
    "declare_subscriber",
    "query",
    "declare_queryable",
    "reply",
    "liveliness_token",
    "declare_liveliness_subscriber",
    "liveliness_query",
];

/// The push messages, which an exposure deny names (§0, §2.7).
pub const PUSH_MESSAGES: [&str; 3] = ["put", "delete", "declare_subscriber"];

/// Both flows, in the order a plan lists them (§0).
pub const FLOWS: [&str; 2] = ["egress", "ingress"];

/// The `@zk` deny's key expression, base-relative (§2.6).
pub const ZK_DENY: &str = "zk2/**/@zk/**";

/// The `@adv` deny's key expression, base-relative (§2.6).
pub const ADV_DENY: &str = "zk2/**/@adv/**";

/// The admin space's deny, never namespaced (§2.6).
pub const ADMIN_DENY: &str = "@/**";

/// The kind tokens whose pushes a plan denies, in its order (§2.7).
pub const PUSH_TOKENS: [KindToken; 5] = [
    KindToken::Stream,
    KindToken::ExplicitStream,
    KindToken::State,
    KindToken::ExplicitState,
    KindToken::Events,
];

const MAX_U32: u64 = u32::MAX as u64;
const MAX_BATCH: u64 = 65_535;
const MAX_REGION: usize = 32;
/// `keep_alive`'s bound (v2 §2.1): it keeps `keep_alive_flaps`'s exact
/// arithmetic small, and no medium runs more.
const MAX_KEEP_ALIVE: u64 = 255;
const MAX_LOSS_PPM: u64 = 1_000_000;

// ── link.v2: the profile, the binding, the transport (v2 §2.1, §2.4, §2.16) ─

/// Which text a face policy is read by (v2 §2.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Profile {
    /// No `profile`: `link.v1`, read as its §2.1 says.
    #[default]
    V1,
    /// `profile = "link.v2"`.
    V2,
}

impl Profile {
    /// The profile's id.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::V1 => PROFILE,
            Self::V2 => PROFILE_V2,
        }
    }
}

/// The prefix of a release of the fork on zenoh 1.10.2, `zm-1.10.2-r<n>`
/// (v2 §2.4).
const FORK_RELEASE: &str = "zm-1.10.2-r";

/// The zenoh a near router runs (v2 §2.4): it names the router's link
/// protocols, and the defaults a configuration that omits a transport key
/// runs with (v2 §2.19). A `link.v1` policy reads as `zenoh-1.10.1`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum Binding {
    /// Stock zenoh 1.10.1.
    #[default]
    Zenoh1_10_1,
    /// Stock zenoh 1.10.2 (#1165): 1.10.1's link protocols and defaults.
    Zenoh1_10_2,
    /// `zm-1.10.2-r1`, the fork zenoh-modem builds on, and each later
    /// release of the fork on zenoh 1.10.2, `zm-1.10.2-r<n>`, that changes
    /// none of what a plan reads (v2 §2.4).
    Zm1_10_2R1,
}

impl Binding {
    /// Every binding, in the order v2 §2.4 lists them.
    pub const ALL: [Binding; 3] = [
        Binding::Zenoh1_10_1,
        Binding::Zenoh1_10_2,
        Binding::Zm1_10_2R1,
    ];

    /// Every binding's name, in [`Binding::ALL`]'s order: the one list a
    /// refusal offers ([`UnknownBinding`], and `Deserialize`'s).
    pub const NAMES: [&'static str; Binding::ALL.len()] = {
        let mut names = [""; Binding::ALL.len()];
        let mut i = 0;
        while i < names.len() {
            names[i] = Binding::ALL[i].as_str();
            i += 1;
        }
        names
    };

    /// Its name in a policy.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Zenoh1_10_1 => "zenoh-1.10.1",
            Self::Zenoh1_10_2 => "zenoh-1.10.2",
            Self::Zm1_10_2R1 => "zm-1.10.2-r1",
        }
    }

    /// The binding a policy's `binding` names, if any: a binding's name, or
    /// `zm-1.10.2-r<n>`, `n` a decimal from 1 with no leading zero, which
    /// names `zm-1.10.2-r1`'s binding (v2 §2.4).
    #[must_use]
    pub fn parse(s: &str) -> Option<Binding> {
        Self::ALL.into_iter().find(|b| b.as_str() == s).or_else(|| {
            let n = s.strip_prefix(FORK_RELEASE)?;
            (!n.is_empty() && !n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()))
                .then_some(Binding::Zm1_10_2R1)
        })
    }

    /// The closed list of link protocols `select.link_protocols` takes and
    /// §2.4's narrowing reads, in its order (v2 §2.4).
    #[must_use]
    pub fn protocols(self) -> &'static [&'static str] {
        match self {
            Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => STOCK_PROTOCOLS,
            Self::Zm1_10_2R1 => ZM_1_10_2_R1_PROTOCOLS,
        }
    }

    /// What a router of this binding runs for a transport key its
    /// configuration omits (v2 §2.19; `zenoh-config`'s `defaults.rs`, the
    /// same in 1.10.1 and 1.10.2): the fork's `wait_before_close` is its
    /// lease, 10 s, its own change, where stock zenoh's is 5 s.
    #[must_use]
    pub fn defaults(self) -> Transport {
        Transport {
            lease_ms: 10_000,
            keep_alive: 4,
            wait_before_close_ms: match self {
                Self::Zenoh1_10_1 | Self::Zenoh1_10_2 => 5_000,
                Self::Zm1_10_2R1 => 10_000,
            },
            sequence: Sequence::Bit32,
            batch_bytes: MAX_BATCH,
            open_timeout_ms: DEFAULT_TIMEOUT_MS,
            accept_timeout_ms: DEFAULT_TIMEOUT_MS,
            interests_timeout_ms: DEFAULT_TIMEOUT_MS,
        }
    }
}

impl fmt::Display for Binding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for Binding {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

/// A name that is no binding (v2 §2.4): what [`Binding`]'s `FromStr`
/// refuses, said with the names it could have been.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownBinding(pub String);

impl fmt::Display for UnknownBinding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "not a binding; one of: {}, or {FORK_RELEASE}<n> for a later release of the fork",
            Binding::NAMES.join(", ")
        )
    }
}

impl std::error::Error for UnknownBinding {}

/// A binding by its name in a policy, for a tool's flag (`--binding`): any
/// other string is refused with the names it could have been.
impl std::str::FromStr for Binding {
    type Err = UnknownBinding;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Binding::parse(s).ok_or_else(|| UnknownBinding(s.to_owned()))
    }
}

/// A binding by its name in a policy, for a tool's own configuration (a
/// policy's `binding` is read by [`parse`], with its findings): any other
/// string is refused with the names it could have been.
impl<'de> serde::Deserialize<'de> for Binding {
    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let name = String::deserialize(d)?;
        Binding::parse(&name)
            .ok_or_else(|| serde::de::Error::unknown_variant(&name, &Binding::NAMES))
    }
}

/// zenoh 1.10.1's `open_timeout`, `accept_timeout` and interests timeout,
/// in ms: an optional `[transport]` key's default (v2 §2.1).
pub const DEFAULT_TIMEOUT_MS: u64 = 10_000;

/// The frame sequence number's resolution (v2 §2.16), as zenoh's `Bits`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Sequence {
    Bit8,
    Bit16,
    Bit32,
    Bit64,
}

impl Sequence {
    /// Every resolution.
    pub const ALL: [Sequence; 4] = [
        Sequence::Bit8,
        Sequence::Bit16,
        Sequence::Bit32,
        Sequence::Bit64,
    ];

    /// zenoh's spelling, `"16bit"`.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Bit8 => "8bit",
            Self::Bit16 => "16bit",
            Self::Bit32 => "32bit",
            Self::Bit64 => "64bit",
        }
    }

    /// The resolution a spelling names, if any.
    #[must_use]
    pub fn parse(s: &str) -> Option<Sequence> {
        Self::ALL.into_iter().find(|q| q.as_str() == s)
    }

    /// The window (v2 §2.16): a frame half the mask or more past the last
    /// one received is dropped as old. zenoh 1.10.1 masks a frame's sequence
    /// number to 7, 14, 28 and 32 bits (`common/seq_num.rs`, its
    /// `TransportSn` being 32 bits), so the window is 64, 8,192, 2^27 and
    /// 2^31 frames.
    #[must_use]
    pub fn window(self) -> u64 {
        match self {
            Self::Bit8 => 1 << 6,
            Self::Bit16 => 1 << 13,
            Self::Bit32 => 1 << 27,
            Self::Bit64 => 1 << 31,
        }
    }

    /// The most bytes a frame's sequence number takes (v2 §2.16, #1136):
    /// masked as [`window`](Self::window) says, and written 7 bits a byte,
    /// 1, 2, 4 and 5. Measured on rf0's face, a `16bit` number ran to
    /// 16,383 and then 0, and a `32bit` one to 268,435,455 and then 0.
    #[must_use]
    pub fn max_bytes(self) -> u64 {
        match self {
            Self::Bit8 => 1,
            Self::Bit16 => 2,
            Self::Bit32 => 4,
            Self::Bit64 => 5,
        }
    }
}

/// The link protocols on which zenoh 1.10.1 writes no batch length, a
/// datagram's: `serial`, `ws` and the fork's `unixsock-dgram` (link.v1
/// §2.8, v2 §2.16, #1136). Every other one may be streamed (`udp` where its
/// endpoint asks for a reliable link), and a streamed link spends 2 bytes of
/// its batch on the length.
pub const UNSTREAMED_PROTOCOLS: [&str; 3] = ["serial", "ws", "unixsock-dgram"];

/// What a put's QoS adds to its batch (link.v1 §2.8, core §2.4): the push's
/// QoS extension unless its priority is `data`, its congestion `drop` and
/// it is not express, and the frame's unless its priority is `data`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PutQos {
    /// Its congestion is `block`.
    pub block: bool,
    /// Its priority is `data`, zenoh's default.
    pub priority_data: bool,
    /// It is express.
    pub express: bool,
}

impl PutQos {
    /// zenoh's defaults: `data`, `drop`, not express. No extension.
    pub const DATA_DROP: PutQos = PutQos {
        block: false,
        priority_data: true,
        express: false,
    };
}

/// The most bytes zenoh 1.10.1 writes in a batch beside a put's payload of
/// `payload` bytes, on a key its far reader declared (link.v1 §2.8, #1136):
/// the put's 3 bytes and the payload's length, 7 bits a byte; the push's
/// and the frame's QoS extensions, 2 bytes each where `qos` has one; the
/// frame's header byte and its sequence number at `sequence`'s widest; and
/// the batch's 2-byte length unless no link of `protocols` is streamed
/// ([`UNSTREAMED_PROTOCOLS`]). Measured at the bound on zenoh-modem's RF
/// face (`docs/zk2/measurements/wire-baseline/`, "The batch's bound").
#[must_use]
pub fn allowance(payload: u64, qos: PutQos, sequence: Sequence, protocols: &[String]) -> u64 {
    let length = match payload {
        0..128 => 1,
        128..16_384 => 2,
        _ => 3,
    };
    let push_qos = if qos.priority_data && !qos.block && !qos.express {
        0
    } else {
        2
    };
    let frame_qos = if qos.priority_data { 0 } else { 2 };
    let batch_length = if protocols
        .iter()
        .all(|p| UNSTREAMED_PROTOCOLS.contains(&p.as_str()))
    {
        0
    } else {
        2
    };
    3 + length + push_qos + 1 + sequence.max_bytes() + frame_qos + batch_length
}

/// Whether a put of `payload` bytes fits one batch of `batch_bytes` with its
/// [`allowance`] (link.v1 §2.8): zenoh fragments one that does not.
#[must_use]
pub fn fits_batch(
    payload: u64,
    batch_bytes: u64,
    qos: PutQos,
    sequence: Sequence,
    protocols: &[String],
) -> bool {
    u128::from(payload) + u128::from(allowance(payload, qos, sequence, protocols))
        <= u128::from(batch_bytes)
}

impl Serialize for Sequence {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

/// A near router's transport, `[transport]` (v2 §2.16): zenoh 1.10.1 reads
/// it once per router, for every link. Every key resolved: an optional
/// one the policy omits is at its default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct Transport {
    pub lease_ms: u64,
    pub keep_alive: u64,
    pub wait_before_close_ms: u64,
    pub sequence: Sequence,
    pub batch_bytes: u64,
    pub open_timeout_ms: u64,
    pub accept_timeout_ms: u64,
    pub interests_timeout_ms: u64,
}

impl Transport {
    /// The value a generator writes at `key`'s zenoh key (v2 §2.18), in
    /// zenoh's units: `wait_before_close` in µs, the rest as the policy
    /// states them.
    #[must_use]
    pub fn value(&self, key: TransportKey) -> Value {
        match key {
            TransportKey::Lease => Value::from(self.lease_ms),
            TransportKey::KeepAlive => Value::from(self.keep_alive),
            TransportKey::WaitBeforeClose => Value::from(self.wait_before_close_ms * 1_000),
            TransportKey::Sequence => Value::from(self.sequence.as_str()),
            TransportKey::BatchBytes => Value::from(self.batch_bytes),
            TransportKey::OpenTimeout => Value::from(self.open_timeout_ms),
            TransportKey::AcceptTimeout => Value::from(self.accept_timeout_ms),
            TransportKey::InterestsTimeout => Value::from(self.interests_timeout_ms),
        }
    }

    /// The keep-alive interval, `lease_ms` / `keep_alive`, in whole ms,
    /// rounded down.
    #[must_use]
    pub fn keep_alive_interval_ms(&self) -> u64 {
        self.lease_ms / self.keep_alive.max(1)
    }

    /// The keep-alive interval in words: `"60000 ms"`, or `"about 666 ms"`
    /// where the lease is no multiple of `keep_alive`.
    #[must_use]
    pub fn keep_alive_interval_words(&self) -> String {
        let exact = self.lease_ms.is_multiple_of(self.keep_alive.max(1));
        format!(
            "{}{} ms",
            if exact { "" } else { "about " },
            self.keep_alive_interval_ms()
        )
    }
}

/// One key of `[transport]` (v2 §2.1), with zenoh 1.10.1's configuration
/// key it is written at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum TransportKey {
    Lease,
    KeepAlive,
    WaitBeforeClose,
    Sequence,
    BatchBytes,
    OpenTimeout,
    AcceptTimeout,
    InterestsTimeout,
}

impl TransportKey {
    /// Every key, in the policy's order (v2 §2.1).
    pub const ALL: [TransportKey; 8] = [
        TransportKey::Lease,
        TransportKey::KeepAlive,
        TransportKey::WaitBeforeClose,
        TransportKey::Sequence,
        TransportKey::BatchBytes,
        TransportKey::OpenTimeout,
        TransportKey::AcceptTimeout,
        TransportKey::InterestsTimeout,
    ];

    /// The key in `[transport]`.
    #[must_use]
    pub fn key(self) -> &'static str {
        match self {
            Self::Lease => "lease_ms",
            Self::KeepAlive => "keep_alive",
            Self::WaitBeforeClose => "wait_before_close_ms",
            Self::Sequence => "sequence",
            Self::BatchBytes => "batch_bytes",
            Self::OpenTimeout => "open_timeout_ms",
            Self::AcceptTimeout => "accept_timeout_ms",
            Self::InterestsTimeout => "interests_timeout_ms",
        }
    }

    /// A finding's `at` for it, `transport.<key>`.
    #[must_use]
    pub fn at(self) -> String {
        format!("transport.{}", self.key())
    }

    /// zenoh 1.10.1's configuration key, `/`-separated as
    /// `zenoh::Config::insert_json5` takes it (`zenoh-config`'s `lib.rs`).
    #[must_use]
    pub fn path(self) -> &'static str {
        match self {
            Self::Lease => "transport/link/tx/lease",
            Self::KeepAlive => "transport/link/tx/keep_alive",
            Self::WaitBeforeClose => {
                "transport/link/tx/queue/congestion_control/block/wait_before_close"
            }
            Self::Sequence => "transport/link/tx/sequence_number_resolution",
            Self::BatchBytes => "transport/link/tx/batch_size",
            Self::OpenTimeout => "transport/unicast/open_timeout",
            Self::AcceptTimeout => "transport/unicast/accept_timeout",
            Self::InterestsTimeout => "routing/interests/timeout",
        }
    }

    /// The key whose zenoh key is `path`, if any.
    #[must_use]
    pub fn of_path(path: &str) -> Option<TransportKey> {
        Self::ALL.into_iter().find(|k| k.path() == path)
    }
}

/// What a generator writes beside the transport, at zenoh 1.10.1's
/// configuration key (`zenoh-config`'s `TimestampingConf`, a
/// `ModeDependentValue<bool>`): timestamping off for a router and a peer,
/// so that the near router stamps no put it routes onto the face, whichever
/// mode it runs in (v2 §2.18, core §8.2).
pub const TIMESTAMPING_OFF: [(&str, bool); 2] = [
    ("timestamping/enabled/router", false),
    ("timestamping/enabled/peer", false),
];

/// The keys a router's timestamping is read from (v2 §2.19): its mode, and
/// `timestamping/enabled`, a boolean or a value per mode.
pub const POSTURE_PATHS: [&str; 2] = ["mode", "timestamping/enabled"];

/// zenoh's three modes, the only `mode` strings its loader accepts
/// (`zenoh-protocol`'s `WhatAmI`): any other is read as left out.
const MODES: [&str; 3] = ["router", "peer", "client"];

/// The transport keys a router's configuration states, by zenoh key, as
/// the file writes them (v2 §2.19): a key it omits is absent, and read at
/// the binding's default. Its mode and `timestamping/enabled`
/// ([`POSTURE_PATHS`]) beside them, where it states them.
///
/// The map holds what the file writes, a `null` included. What a `null`
/// means is read where the key is: [`StatedTransport::states`] and
/// [`StatedTransport::runs`] for the eight keys, [`StatedTransport::stamps`]
/// for the mode and the timestamping. So a value built from a map, as a
/// fixture's is, reads as one [`StatedTransport::read`] made.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct StatedTransport(pub BTreeMap<String, Value>);

impl StatedTransport {
    /// The keys `config`, a router's configuration as a JSON tree, writes:
    /// each of [`TransportKey::ALL`]'s and [`POSTURE_PATHS`]' whose path it
    /// holds, a `null` kept as written. Whether a `null` is a value stated
    /// is its key's to say ([`StatedTransport::states`]).
    #[must_use]
    pub fn read(config: &Value) -> StatedTransport {
        let mut out = BTreeMap::new();
        let paths = TransportKey::ALL
            .into_iter()
            .map(TransportKey::path)
            .chain(POSTURE_PATHS);
        for path in paths {
            let v = path
                .split('/')
                .try_fold(config, |node, part| node.get(part));
            if let Some(v) = v {
                out.insert(path.to_owned(), v.clone());
            }
        }
        StatedTransport(out)
    }

    /// Whether the router stamps the puts it routes (v2 §2.19, core §4.1):
    /// `timestamping/enabled` as a boolean, or its value for the mode the
    /// configuration runs, `router` where it states none, as zenohd runs; a
    /// mode the value leaves out, or no value, at zenoh 1.10.1's default,
    /// on for a router and off for a peer and a client.
    ///
    /// A `null` is read as zenoh 1.10.1 reads it, as left out: each value
    /// is an `Option` it fills with its default (`zenoh-config`'s
    /// `ModeValues`, `unwrap_or_default!`). So is a `mode` of `null`. Any
    /// other value that is no boolean, or a `mode` that is none of zenoh's
    /// three, is one zenoh refuses to load ("bool or mode dependent bool";
    /// "unknown variant", `WhatAmI`'s visitor): no router runs it, and it
    /// is read at the default too, a refused `mode` as `router` (link.v2
    /// 0.22 §2.19, "As data").
    #[must_use]
    pub fn stamps(&self) -> bool {
        let mode = match self.0.get("mode") {
            Some(Value::String(mode)) if MODES.contains(&mode.as_str()) => mode.as_str(),
            // Unstated or `null`, as zenohd runs, or a value zenoh refuses:
            // a string that is none of its three, or no string.
            _ => "router",
        };
        let default = mode == "router";
        let read = |value: Option<&Value>| match value {
            Some(Value::Bool(b)) => *b,
            // Left out, `null` (which zenoh reads as left out), or a value
            // zenoh refuses to load.
            _ => default,
        };
        match self.0.get("timestamping/enabled") {
            Some(Value::Object(per_mode)) => read(per_mode.get(mode)),
            value => read(value),
        }
    }

    /// Whether the configuration writes a `null` at `key` that zenoh
    /// 1.10.1 reads as left out (v2 §2.19): only at
    /// [`TransportKey::InterestsTimeout`], `routing/interests/timeout`, an
    /// `Option<u64>` the router fills with its default
    /// (`unwrap_or_default!`), as `zm-1.10.2-r1` types it too. Each of the
    /// seven other keys is no `Option`: zenoh refuses a `null` there at
    /// load, so it stays a value stated, and no value zenoh runs.
    #[must_use]
    pub fn null_left_out(&self, key: TransportKey) -> bool {
        key == TransportKey::InterestsTimeout && matches!(self.0.get(key.path()), Some(Value::Null))
    }

    /// The value the configuration states for `key`: what it writes there,
    /// but for a `null` zenoh reads as left out
    /// ([`StatedTransport::null_left_out`]).
    fn stated(&self, key: TransportKey) -> Option<&Value> {
        self.0.get(key.path()).filter(|_| !self.null_left_out(key))
    }

    /// Whether the configuration states `key`: it writes it, and not as a
    /// `null` zenoh reads as left out.
    #[must_use]
    pub fn states(&self, key: TransportKey) -> bool {
        self.stated(key).is_some()
    }

    /// What the configuration runs for `key`: the value it states, or
    /// `defaults`'s (a binding's, [`Binding::defaults`]) where it states
    /// none ([`StatedTransport::states`]).
    #[must_use]
    pub fn runs(&self, key: TransportKey, defaults: &Transport) -> Value {
        self.stated(key)
            .cloned()
            .unwrap_or_else(|| defaults.value(key))
    }
}

// ── Exposure (§2.2) ──────────────────────────────────────────────────────

/// A resource's exposure, read from its resolved annotations (§2.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Exposure {
    /// `"host"`, or no `link.exposure`: it never crosses a constrained face.
    Host,
    /// `"link"`: it may cross a face that exposes.
    Link,
    /// A value that is no exposure, as JSON text: read as `host`.
    Invalid(String),
    /// On an operation, whatever the value: a call crosses by grant.
    Ignored,
}

impl Exposure {
    /// The fixture's token (`exposure.json`).
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Host => "host",
            Self::Link => "link",
            Self::Invalid(_) => "invalid",
            Self::Ignored => "ignored",
        }
    }
}

/// Reads the exposure of a resource of `kind` from its resolved annotations
/// (§2.2): `[defaults]`, then `[defaults.<kind>]`, then its own (core §9.3).
#[must_use]
pub fn exposure(kind: Kind, annotations: &BTreeMap<String, Value>) -> Exposure {
    if kind == Kind::Operation {
        return Exposure::Ignored;
    }
    match annotations.get(EXPOSURE) {
        None => Exposure::Host,
        Some(Value::String(s)) if s == "host" => Exposure::Host,
        Some(Value::String(s)) if s == "link" => Exposure::Link,
        Some(v) => Exposure::Invalid(v.to_string()),
    }
}

/// [`exposure`] of a resource of a contract.
#[must_use]
pub fn exposure_of(r: &Resource) -> Exposure {
    exposure(r.kind, &r.annotations)
}

/// What a face's policy lets cross (§2.1 `expose`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Expose {
    /// Exposed resources cross.
    Link,
    /// No push crosses.
    None,
}

/// What happens to a resource's pushes on a face (§2.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Pushes {
    /// A stream that crosses, one put per key per interval (§2.8).
    Downsampled,
    /// A state or an event that crosses, every put and delete (§2.7, §2.9).
    Whole,
    /// Denied on the face.
    Denied,
    /// An operation, which has no pushes (§2.9).
    None,
}

impl Pushes {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Downsampled => "downsampled",
            Self::Whole => "whole",
            Self::Denied => "denied",
            Self::None => "none",
        }
    }
}

/// Why, the first of these that holds, in this order (`exposure.json`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Reason {
    /// An operation: its calls cross by grant (§2.9).
    RequestsOnly,
    /// A value that is no exposure, read as `host` (§2.2).
    Invalid,
    /// `host`, or no annotation (§2.2).
    Host,
    /// The face exposes none (§2.1).
    FaceClosed,
    /// A stream whose template has a parameter: no rule names its members
    /// (§2.8).
    Templated,
    /// link.v2's: a frame resource on a face whose `frames` does not list it
    /// (v2 §2.7).
    Unlisted,
    /// link.v2's: a stream that would be downsampled, and declares
    /// `timing.deadline_ms` (v2 §2.8).
    Timed,
    /// It crosses.
    Exposed,
}

impl Reason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::RequestsOnly => "requests_only",
            Self::Invalid => "invalid",
            Self::Host => "host",
            Self::FaceClosed => "face_closed",
            Self::Templated => "templated",
            Self::Unlisted => "unlisted",
            Self::Timed => "timed",
            Self::Exposed => "exposed",
        }
    }
}

/// Whether a resource's pushes cross a face, and why (§2.7).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Crossing {
    pub pushes: Pushes,
    pub reason: Reason,
}

impl Crossing {
    /// Whether its pushes cross (§0's "crossing").
    #[must_use]
    pub fn crosses(self) -> bool {
        matches!(self.pushes, Pushes::Downsampled | Pushes::Whole)
    }
}

/// Whether the pushes of a resource of `token` cross a face that exposes
/// `expose` (§2.7): `templated` when its template has a parameter.
#[must_use]
pub fn crossing(
    token: KindToken,
    templated: bool,
    exposure: &Exposure,
    expose: Expose,
) -> Crossing {
    let denied = |reason| Crossing {
        pushes: Pushes::Denied,
        reason,
    };
    if token == KindToken::Op {
        return Crossing {
            pushes: Pushes::None,
            reason: Reason::RequestsOnly,
        };
    }
    match exposure {
        Exposure::Ignored => Crossing {
            pushes: Pushes::None,
            reason: Reason::RequestsOnly,
        },
        Exposure::Invalid(_) => denied(Reason::Invalid),
        Exposure::Host => denied(Reason::Host),
        Exposure::Link if expose == Expose::None => denied(Reason::FaceClosed),
        Exposure::Link if is_stream(token) && templated => denied(Reason::Templated),
        Exposure::Link if is_stream(token) => Crossing {
            pushes: Pushes::Downsampled,
            reason: Reason::Exposed,
        },
        Exposure::Link => Crossing {
            pushes: Pushes::Whole,
            reason: Reason::Exposed,
        },
    }
}

/// What link.v2 reads of a resource's own declaration, beside its exposure,
/// to say whether it crosses (v2 §2.7, §2.8).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Shape {
    /// Its template has a parameter.
    pub templated: bool,
    /// It is a frame resource (core §7.7): never downsampled.
    pub frame: bool,
    /// Its resolved annotations hold `timing.deadline_ms`, whatever its
    /// value ([`timed`]).
    pub timed: bool,
}

impl Shape {
    /// The shape of a resource of `token`: `templated` when its template
    /// has a parameter, `frame` when it is a frame resource, and timed when
    /// it is a stream whose `annotations` hold `timing.deadline_ms`.
    #[must_use]
    pub fn of(
        token: KindToken,
        templated: bool,
        frame: bool,
        annotations: &BTreeMap<String, Value>,
    ) -> Self {
        Shape {
            templated,
            frame,
            timed: is_stream(token) && timed(annotations),
        }
    }
}

/// Whether resolved annotations hold `timing.deadline_ms` (v2 §2.8). Its
/// value is not read: an invalid one still says the contract meant a
/// deadline, and the plan fails closed.
#[must_use]
pub fn timed(annotations: &BTreeMap<String, Value>) -> bool {
    annotations.contains_key(crate::timing::DEADLINE_MS)
}

/// link.v2's reading of whether a resource's pushes cross a face (v2 §2.7,
/// §2.8): [`crossing`]'s, and then a frame resource crosses whole, never
/// downsampled, unless the face's `frames` leaves it out (`listed`
/// `Some(false)`; `None` for a face with no `frames`), an exposed event
/// crosses whole unless the face's `events` leaves it out (`listed` alike,
/// from `events`), and a stream that would be downsampled is denied when
/// it is timed.
#[must_use]
pub fn crossing_v2(
    token: KindToken,
    shape: Shape,
    exposure: &Exposure,
    expose: Expose,
    listed: Option<bool>,
) -> Crossing {
    let c = crossing(token, shape.templated, exposure, expose);
    let denied = |reason| Crossing {
        pushes: Pushes::Denied,
        reason,
    };
    if token == KindToken::Events && c.pushes == Pushes::Whole && listed == Some(false) {
        return denied(Reason::Unlisted);
    }
    if c.pushes != Pushes::Downsampled {
        return c;
    }
    if shape.frame {
        if listed == Some(false) {
            return denied(Reason::Unlisted);
        }
        return Crossing {
            pushes: Pushes::Whole,
            reason: Reason::Exposed,
        };
    }
    if shape.timed {
        return denied(Reason::Timed);
    }
    c
}

/// Whether a resource breaks link.v2's packed requirement (v2 §2.17): its
/// contract lists `link.v2`, it is a stream, a state or an event exposed
/// `link`, and its type is not packed.
#[must_use]
pub fn packed_required(uses_v2: bool, token: KindToken, exposure: &Exposure, packed: bool) -> bool {
    uses_v2 && token != KindToken::Op && *exposure == Exposure::Link && !packed
}

/// A contract's findings under link.v2's contract side (v2 §2.17): for a
/// contract that lists `link.v2`, `packed_required` at each resource it
/// exposes `link` whose type is not packed, `at` its name (§0), with no
/// face. None for any other contract.
#[must_use]
pub fn contract_findings(c: &Contract) -> Vec<Finding> {
    let v2 = uses_v2(c);
    let mut out: Vec<Finding> = c
        .resources
        .iter()
        .map(|r| Res::of(c, r))
        .filter(|r| {
            packed_required(
                v2,
                r.token,
                &exposure(kind_of(r.token), &r.annotations),
                r.packed,
            )
        })
        .map(|r| {
            Finding::new(
                Code::PackedRequired,
                None,
                res_name(&c.iface.to_string(), &r),
            )
        })
        .collect();
    sort_findings(&mut out);
    out
}

fn is_stream(token: KindToken) -> bool {
    matches!(token, KindToken::Stream | KindToken::ExplicitStream)
}

fn is_state(token: KindToken) -> bool {
    matches!(token, KindToken::State | KindToken::ExplicitState)
}

/// The kind a token carries (core §1.3).
#[must_use]
pub fn kind_of(token: KindToken) -> Kind {
    match token {
        KindToken::Stream | KindToken::ExplicitStream => Kind::Stream,
        KindToken::State | KindToken::ExplicitState => Kind::State,
        KindToken::Events => Kind::Event,
        KindToken::Op => Kind::Operation,
    }
}

// ── Findings (§2.1, §2.3, §2.11, §2.15) ───────────────────────────────────

/// The closed vocabulary of findings.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Code {
    /// The file is not TOML 1.0 (§2.1).
    Toml,
    /// A key the format does not define (§2.1).
    UnknownField,
    /// A required key absent (§2.1).
    MissingField,
    /// A value of the wrong type or outside its range (§2.1).
    BadValue,
    /// `attach = "router"` (§2.5).
    RouterAttach,
    /// `select.interfaces` (§2.14).
    SelectInterfaces,
    /// A link protocol zenoh 1.10.1 does not name (§2.1).
    UnknownProtocol,
    /// Two faces with a common link protocol (§2.14).
    SharedProtocol,
    /// A batch over a third of the lease (§2.10).
    BatchOverLease,
    /// Two or more faces naming one far principal, whose policy then
    /// carries every one of their plans' denies on each of them (§2.1,
    /// §2.4, 0.7, F-125).
    FarOfTwoFaces,
    /// A listed service the deployment names no interfaces for (§2.3).
    ServiceUnknown,
    /// An interface whose contract is not given (§2.3).
    ContractUnknown,
    /// An exposed stream with a parameter, denied (§2.8).
    TemplatedExposure,
    /// An exposed resource a deny must include (§2.7).
    CarveOutOverlap,
    /// A crossing stream whose horizon is below twice the interval
    /// (§2.12).
    IntervalOverHorizon,
    /// Revisions of a listed interface that disagree on a resource's
    /// exposure, one `link` and another not: it does not cross (§2.3, 0.3).
    ExposureDisagrees,
    /// A crossing frame resource whose interval is shorter than the
    /// face's `interval_s`: never downsampled, it crosses at its own
    /// cadence (§2.8).
    FrameOverInterval,
    /// A crossing frame resource whose largest frame, with its
    /// [`allowance`], does not fit the face's batch: it is fragmented, and
    /// lost whole (§2.8).
    FrameOverBatch,
    /// A crossing frame resource that declares `history`: every put pays
    /// the advanced publisher's source info across the face, and its
    /// history stays home (§2.8).
    HistoryOnFrame,
    /// A listed service whose owner heartbeats the deployment turns on,
    /// implementing an interface whose heartbeat crosses a `link.v1` face:
    /// no owner heartbeat crosses one, so its far readers may hear no
    /// confirmation (§2.3, §2.9; #1145).
    OwnerHeartbeatDenied,
    /// A listed owner's tombstone window below the outage (§2.11).
    WindowUnderOutage,
    /// A block whose denies leave a pair of `@zk` open (§2.15).
    ZkNotDenied,
    /// A downsampling rule that is not one concrete key (§2.15).
    WildcardDownsampling,
    /// Two downsampling rules that intersect (§2.15).
    IntersectingDownsampling,
    /// A block whose access control is not enabled: zenoh enforces none of
    /// its rules (§2.15, 0.7, F-124).
    BlockDisabled,
    /// A subject on the face bound to another principal than the face's
    /// far one, whatever else it names (§2.4, §2.15, 0.3; widened in 0.4,
    /// F-120).
    NearSubjectOnFace,
    /// Under `allow`, a link protocol of the face that no face subject
    /// naming no interface and no zid selects (§2.4, §2.15, 0.3).
    FaceSubjectMissing,
    /// A face subject that also selects sessions off the face (§2.4,
    /// §2.15, 0.4, F-120).
    FaceSubjectBeyondFace,
    /// A face subject not listed in exactly the far principal's policies
    /// (§2.4, §2.15, 0.4, F-120).
    FaceSubjectMisplaced,
    /// Under `allow`, a name the block binds whose session over a link
    /// protocol it is not kept off matches no subject (§2.4, §2.15, 0.4,
    /// F-120).
    NarrowedTooFar,
    /// A link.v2 policy with no `[transport]` (v2 §2.1).
    TransportMissing,
    /// A face's `lease_ms` or `batch_bytes` in a link.v2 policy: they are
    /// `[transport]`'s (v2 §2.1).
    MovedField,
    /// `wait_before_close` below the lease, in a policy or a router's
    /// configuration (v2 §2.16, §2.19).
    WaitUnderLease,
    /// A face's loss makes more than one false close a day likely (v2
    /// §2.16).
    KeepAliveFlaps,
    /// One lease can carry the sequence window in full batches (v2 §2.16).
    SequenceWindow,
    /// An open or accept timeout below twice the handshake's air (v2
    /// §2.16).
    OpenUnderHandshake,
    /// A face's reply timeout below 16 full batches' air (v2 §2.1).
    ReplyTimeoutShort,
    /// A face whose medium repairs no lost frame (v2 §2.1).
    NoArq,
    /// A router's configuration runs a transport key other than the
    /// policy's (v2 §2.19).
    TransportDiffers,
    /// The far end's lease or keep-alive is not the near router's (v2
    /// §2.19).
    PeerDiffers,
    /// A router's configuration stamps the puts it routes onto the face
    /// (v2 §2.18, §2.19; core §8.2).
    FaceTimestamping,
    /// The catalog the far side holds is not the policy's (v2 §2.19).
    CatalogMismatch,
    /// A contract that lists `link.v2` exposes a resource whose type is not
    /// packed (v2 §2.17).
    PackedRequired,
    /// A crossing resource of a contract that does not list `link.v2`,
    /// whose type is not packed (v2 §2.3, §2.17).
    NotPacked,
    /// A face's `frames` entry that names no frame resource of a listed
    /// interface (v2 §2.7).
    FrameUnknown,
    /// A face's `events` entry that names no event resource of a listed
    /// interface (v2 §2.7). An event that is listed but not exposed is
    /// denied, never this.
    EventUnknown,
    /// An exposed frame resource of a listed interface that a face's
    /// `frames` leaves out, and that crosses no face of the policy (v2
    /// §2.7).
    FrameUnlisted,
    /// A listed frame whose `keyframe_s` its contract's `keyframe_every`
    /// cannot reach at the face's `every_s` (v2 §2.7).
    KeyframeUnreachable,
    /// A crossing heartbeat, owner heartbeat or frame resource whose
    /// horizon is below the face's `horizon_s` (v2 §2.9, §2.12).
    HorizonUnderFace,
    /// A crossing `block` resource whose longest put, with its
    /// [`allowance`], does not fit the batch, or a crossing owner
    /// heartbeat's, `at` `freshness.v2/stream/heartbeats/link` (v2 §2.16).
    BlockOverBatch,
    /// A face whose shortest crossing cadence is the keep-alive interval
    /// or above it (v2 §2.16).
    KeepAliveNotSuppressed,
    /// A timed stream, denied rather than downsampled (v2 §2.8).
    TimedDownsampled,
    /// A revision of an interface that crosses the face, which the
    /// deployment's catalog does not list (v2 §2.18).
    CatalogMissing,
    /// A device the policy lists elsewhere: among `services`, or in
    /// another face's `devices` (v2 §2.1, §2.5).
    DeviceListed,
    /// A device that implements `archive.v1`, or an interface a revision
    /// given of which uses `redundancy.v1` or `redundancy.v2`: each needs
    /// presence on its peers' side of the face (v2 §2.5, 0.29; core §8.1,
    /// `redundancy.v2` §2.13).
    PresenceRequired,
    /// On a device face, a template of a device's interface that declares
    /// `epoch`: its member tokens cross the face at each transport, and the
    /// face denies them (v2 §2.5).
    EpochOnDevice,
    /// A face the near router opens (`opens = "near"`) whose far principal
    /// the deployment binds by a user name: zenoh's usrpwd binds a user
    /// name only to a link the router accepted (v2 §2.5).
    NearOpensUser,
    /// Under `allow`, a face the near router opens whose far principal is a
    /// user name: planned, and nobody across it is authenticated (v2 §2.5).
    NearOpensUnauthenticated,
}

impl Code {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Toml => "toml",
            Self::UnknownField => "unknown_field",
            Self::MissingField => "missing_field",
            Self::BadValue => "bad_value",
            Self::RouterAttach => "router_attach",
            Self::SelectInterfaces => "select_interfaces",
            Self::UnknownProtocol => "unknown_protocol",
            Self::SharedProtocol => "shared_protocol",
            Self::BatchOverLease => "batch_over_lease",
            Self::FarOfTwoFaces => "far_of_two_faces",
            Self::ServiceUnknown => "service_unknown",
            Self::ContractUnknown => "contract_unknown",
            Self::TemplatedExposure => "templated_exposure",
            Self::CarveOutOverlap => "carve_out_overlap",
            Self::IntervalOverHorizon => "interval_over_horizon",
            Self::ExposureDisagrees => "exposure_disagrees",
            Self::FrameOverInterval => "frame_over_interval",
            Self::FrameOverBatch => "frame_over_batch",
            Self::HistoryOnFrame => "history_on_frame",
            Self::OwnerHeartbeatDenied => "owner_heartbeat_denied",
            Self::WindowUnderOutage => "window_under_outage",
            Self::ZkNotDenied => "zk_not_denied",
            Self::WildcardDownsampling => "wildcard_downsampling",
            Self::IntersectingDownsampling => "intersecting_downsampling",
            Self::BlockDisabled => "block_disabled",
            Self::NearSubjectOnFace => "near_subject_on_face",
            Self::FaceSubjectMissing => "face_subject_missing",
            Self::FaceSubjectBeyondFace => "face_subject_beyond_face",
            Self::FaceSubjectMisplaced => "face_subject_misplaced",
            Self::NarrowedTooFar => "narrowed_too_far",
            Self::TransportMissing => "transport_missing",
            Self::MovedField => "moved_field",
            Self::WaitUnderLease => "wait_under_lease",
            Self::KeepAliveFlaps => "keep_alive_flaps",
            Self::SequenceWindow => "sequence_window",
            Self::OpenUnderHandshake => "open_under_handshake",
            Self::ReplyTimeoutShort => "reply_timeout_short",
            Self::NoArq => "no_arq",
            Self::TransportDiffers => "transport_differs",
            Self::PeerDiffers => "peer_differs",
            Self::FaceTimestamping => "face_timestamping",
            Self::CatalogMismatch => "catalog_mismatch",
            Self::PackedRequired => "packed_required",
            Self::NotPacked => "not_packed",
            Self::FrameUnknown => "frame_unknown",
            Self::EventUnknown => "event_unknown",
            Self::FrameUnlisted => "frame_unlisted",
            Self::KeyframeUnreachable => "keyframe_unreachable",
            Self::HorizonUnderFace => "horizon_under_face",
            Self::BlockOverBatch => "block_over_batch",
            Self::KeepAliveNotSuppressed => "keep_alive_not_suppressed",
            Self::TimedDownsampled => "timed_downsampled",
            Self::CatalogMissing => "catalog_missing",
            Self::DeviceListed => "device_listed",
            Self::PresenceRequired => "presence_required",
            Self::EpochOnDevice => "epoch_on_device",
            Self::NearOpensUser => "near_opens_user",
            Self::NearOpensUnauthenticated => "near_opens_unauthenticated",
        }
    }

    /// Its severity, fixed per code.
    #[must_use]
    pub fn severity(self) -> Severity {
        match self {
            Self::BatchOverLease
            | Self::FarOfTwoFaces
            | Self::TemplatedExposure
            | Self::CarveOutOverlap
            | Self::IntervalOverHorizon
            | Self::ExposureDisagrees
            | Self::FrameOverInterval
            | Self::FrameOverBatch
            | Self::HistoryOnFrame
            | Self::OwnerHeartbeatDenied
            | Self::KeepAliveFlaps
            | Self::SequenceWindow
            | Self::OpenUnderHandshake
            | Self::ReplyTimeoutShort
            | Self::NoArq
            | Self::PeerDiffers
            | Self::FaceTimestamping
            | Self::NotPacked
            | Self::FrameUnlisted
            | Self::HorizonUnderFace
            | Self::BlockOverBatch
            | Self::KeepAliveNotSuppressed
            | Self::TimedDownsampled
            | Self::EpochOnDevice
            | Self::NearOpensUnauthenticated => Severity::Warning,
            _ => Severity::Error,
        }
    }
}

impl fmt::Display for Code {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl Serialize for Code {
    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(self.as_str())
    }
}

/// An error refuses the policy, or the plan; a warning does not.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Severity {
    Error,
    Warning,
}

/// One finding: what, about which face, at which key (§2.1).
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct Finding {
    pub code: Code,
    pub severity: Severity,
    /// The face's name, or `None` for the top level and the deployment.
    pub face: Option<String>,
    /// The key it is about (§2.1), the service, the interface, the
    /// resource's name, or the rule's key expression.
    pub at: String,
}

impl Finding {
    /// A finding of `code`, with its fixed severity.
    #[must_use]
    pub fn new(code: Code, face: Option<&str>, at: impl Into<String>) -> Self {
        Finding {
            code,
            severity: code.severity(),
            face: face.map(str::to_owned),
            at: at.into(),
        }
    }

    /// Whether it refuses the policy or the plan.
    #[must_use]
    pub fn is_error(&self) -> bool {
        self.severity == Severity::Error
    }
}

impl fmt::Display for Finding {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sev = match self.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
        };
        match &self.face {
            Some(face) => write!(f, "{sev} {} [face {face}] {}", self.code, self.at),
            None => write!(f, "{sev} {} {}", self.code, self.at),
        }
    }
}

/// Sorts findings by face (none first), `at`, then code, each by its bytes,
/// and drops the repeated ones: findings are a set (§2.1).
pub fn sort_findings(findings: &mut Vec<Finding>) {
    findings.sort_by(|a, b| {
        a.face
            .cmp(&b.face)
            .then_with(|| a.at.cmp(&b.at))
            .then_with(|| a.code.as_str().cmp(b.code.as_str()))
    });
    findings.dedup();
}

// ── The face policy (§2.1) ───────────────────────────────────────────────

/// How the far side attaches (§2.5; v2 §2.5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Attach {
    /// One far-side session, or a gateway session, as a client.
    Client,
    /// A far router in a south region, named by its `region_name`.
    SouthRegion { region: String },
    /// link.v2's device face (v2 §2.5): the sessions of owners on a first
    /// hop (core §8.1), each a client of the near router, by address
    /// `<system>/<service>`, sorted by their bytes.
    Device { devices: Vec<String> },
}

impl Attach {
    /// The devices a device face attaches; none for any other face.
    #[must_use]
    pub fn devices(&self) -> &[String] {
        match self {
            Attach::Device { devices } => devices,
            _ => &[],
        }
    }

    /// Whether it is a device face (v2 §2.5).
    #[must_use]
    pub fn is_device(&self) -> bool {
        matches!(self, Attach::Device { .. })
    }
}

/// Which end of a face opens its links (v2 §2.1, §2.5): connects, where
/// the other accepts.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Opens {
    /// The far end: the far side's session, gateway or router connects to
    /// the near router. Every shape's default, and `client`'s and
    /// `device`'s only.
    #[default]
    Far,
    /// The near router connects to the far router: `south-region` only.
    Near,
}

/// One constrained face of a router (§2.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Face {
    /// The far principal: a user name or a certificate CN (core §11.1).
    pub far: String,
    pub attach: Attach,
    /// `select.link_protocols`, in the policy's order.
    pub link_protocols: Vec<String>,
    pub expose: Expose,
    /// Exactly when `expose` is [`Expose::Link`].
    pub interval_s: Option<u64>,
    pub max_outage_s: u64,
    /// The face's `batch_bytes` in a `link.v1` policy; `[transport]`'s in a
    /// link.v2 one (v2 §2.10).
    pub batch_bytes: u64,
    pub link_bps: u64,
    /// The face's `lease_ms` in a `link.v1` policy, [`DEFAULT_LEASE_MS`]
    /// when it gives none; `[transport]`'s in a link.v2 one.
    pub lease_ms: u64,
    /// link.v2's (v2 §2.1): the share of frames the medium loses, in parts
    /// per million. `None` in a `link.v1` policy, as the next two.
    pub loss_ppm: Option<u64>,
    /// link.v2's: whether the medium repairs a lost frame below zenoh.
    pub arq: Option<bool>,
    /// link.v2's: how long a caller across the face waits for a reply, the
    /// deployment's word to every caller.
    pub reply_timeout_ms: Option<u64>,
    /// link.v2's `frames` (v2 §2.7): the frame resources that cross the
    /// face, by their name (§0, `<iface>/stream/<template>`), each at its
    /// cadence. `None` when the face lists none: every exposed frame
    /// resource crosses, as `link.v1` §2.7 says.
    pub frames: Option<BTreeMap<String, FrameCadence>>,
    /// link.v2's `events` (v2 §2.7): the event resources that cross the
    /// face, by their name (§0, `<iface>/events/<template>`). `None` when
    /// the face lists none: every exposed event crosses, as `link.v1` §2.7
    /// says.
    pub events: Option<BTreeSet<String>>,
    /// link.v2's `horizon_s` (v2 §2.12): the shortest horizon the face
    /// affords a crossing heartbeat or frame resource.
    pub horizon_s: Option<u64>,
    /// link.v2's `opens` (v2 §2.1, §2.5): which end opens the face's links.
    /// [`Opens::Far`] in a `link.v1` policy, and where it states none.
    pub opens: Opens,
}

/// A listed frame's cadence on a face (v2 §2.7): the deployment's word to
/// the far side.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct FrameCadence {
    /// How often its owner puts a frame on this face, in seconds.
    pub every_s: u64,
    /// The longest the face accepts between two full records, in seconds.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub keyframe_s: Option<u64>,
}

impl Face {
    /// Whether a batch takes at most a third of the lease to cross (§2.10):
    /// `batch_bytes` × 24,000 ≤ `lease_ms` × `link_bps`, in integers.
    #[must_use]
    pub fn batch_within_lease(&self) -> bool {
        within_lease(self.batch_bytes, self.link_bps, self.lease_ms)
    }

    /// The downsampling frequency, 1/`interval_s` Hz, the quotient as an
    /// IEEE 754 double (§2.8). `interval_s` is at most 2^32−1, which a
    /// double holds exactly.
    #[must_use]
    pub fn freq(&self) -> Option<f64> {
        self.interval_s
            .map(|n| 1.0 / f64::from(u32::try_from(n).unwrap_or(u32::MAX)))
    }
}

fn within_lease(batch_bytes: u64, link_bps: u64, lease_ms: u64) -> bool {
    u128::from(batch_bytes) * 24_000 <= u128::from(lease_ms) * u128::from(link_bps)
}

/// Whether more than one false close a day is expected (v2 §2.16): 2 ×
/// 86,400 × 1,000 × `keep_alive` × `loss_ppm`^(`keep_alive` − 1) >
/// `lease_ms` × 10^(6 × (`keep_alive` − 1)), exactly.
fn flaps(lease_ms: u64, keep_alive: u64, loss_ppm: u64) -> bool {
    use num_bigint::BigUint;
    let n = u32::try_from(keep_alive.saturating_sub(1)).unwrap_or(u32::MAX);
    let lhs = BigUint::from(172_800_000u64) * keep_alive * BigUint::from(loss_ppm).pow(n);
    let rhs = BigUint::from(lease_ms) * BigUint::from(1_000_000u64).pow(n);
    lhs > rhs
}

/// Whether one lease can carry the sequence window in full batches (v2
/// §2.16): window × 8 × `batch_bytes` × 1,000 ≤ `lease_ms` × `link_bps`.
fn window_filled(sequence: Sequence, batch_bytes: u64, lease_ms: u64, link_bps: u64) -> bool {
    u128::from(sequence.window()) * 8 * u128::from(batch_bytes) * 1_000
        <= u128::from(lease_ms) * u128::from(link_bps)
}

/// Whether a timeout is below twice the 384-byte handshake's air at
/// `link_bps` (v2 §2.16): timeout × `link_bps` < 2 × 384 × 8 × 1,000.
fn under_handshake(timeout_ms: u64, link_bps: u64) -> bool {
    u128::from(timeout_ms) * u128::from(link_bps) < 6_144_000
}

/// Whether a reply timeout is below 16 full batches' air (v2 §2.1):
/// `reply_timeout_ms` × `link_bps` < 16 × 8 × 1,000 × `batch_bytes`.
fn reply_short(reply_timeout_ms: u64, link_bps: u64, batch_bytes: u64) -> bool {
    u128::from(reply_timeout_ms) * u128::from(link_bps) < 128_000 * u128::from(batch_bytes)
}

/// A router's face policy (§2.1; v2 §2.1).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FacePolicy {
    /// The text it is read by.
    pub profile: Profile,
    pub system: String,
    /// The listed services, on `system`.
    pub services: Vec<String>,
    /// The faces, by name.
    pub faces: BTreeMap<String, Face>,
    /// The zenoh the near router runs (v2 §2.4); a `link.v1` policy's is
    /// `zenoh-1.10.1`.
    pub binding: Binding,
    /// The near router's transport (v2 §2.16): a link.v2 policy's, `None`
    /// for a `link.v1` one.
    pub transport: Option<Transport>,
    /// The catalog's id the far side decodes with (v2 §2.1), when a
    /// link.v2 policy names one.
    pub catalog: Option<String>,
}

impl FacePolicy {
    /// A listed service's address, `<system>/<service>`.
    #[must_use]
    pub fn address(&self, service: &str) -> String {
        format!("{}/{service}", self.system)
    }

    /// Every device a face of the policy attaches, by address, with its
    /// face's name (v2 §2.5), in the faces' order and each face's.
    pub fn devices(&self) -> impl Iterator<Item = (&str, &str)> {
        self.faces.iter().flat_map(|(name, f)| {
            f.attach
                .devices()
                .iter()
                .map(move |d| (name.as_str(), d.as_str()))
        })
    }

    /// The face that attaches the device at `address`, when one does. A
    /// device sits on one face only (`device_listed`, v2 §2.1): a policy
    /// the linter accepted never lists it twice.
    #[must_use]
    pub fn device_face(&self, address: &str) -> Option<&str> {
        debug_assert!(
            self.devices().filter(|(_, d)| *d == address).count() <= 1,
            "{address} on more than one device face: the linter's device_listed refuses it"
        );
        self.devices()
            .find(|(_, d)| *d == address)
            .map(|(name, _)| name)
    }

    /// Every listed owner the plan reads (v2 §2.5): each listed service,
    /// then each device, sorted by address. Each is `(address, the key the
    /// deployment's `implements` names it by, the face that attaches it
    /// when it is a device)`.
    #[must_use]
    pub fn owners(&self) -> Vec<Owner<'_>> {
        let mut out: Vec<Owner<'_>> = self
            .services
            .iter()
            .map(|s| Owner {
                address: self.address(s),
                key: s.as_str(),
                device_face: None,
            })
            .chain(self.devices().map(|(face, d)| Owner {
                address: d.to_owned(),
                key: d,
                device_face: Some(face),
            }))
            .collect();
        out.sort_by(|a, b| a.address.cmp(&b.address));
        out
    }
}

/// One listed owner of a policy, as the plan reads it: a listed service,
/// or a device (v2 §2.5).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Owner<'a> {
    /// `<system>/<service>`.
    pub address: String,
    /// The key the deployment's `implements` names it by: a listed
    /// service by its bare name (`radio-a`, on the policy's `system`), a
    /// device by its address (`lab/radio-a`), since a device may sit on
    /// any system (v2 §2.5).
    pub key: &'a str,
    /// The face that attaches it, for a device.
    pub device_face: Option<&'a str>,
}

impl FacePolicy {
    /// What a reader or a caller across `face` reads of this policy (v2
    /// §2.20, §2.21): a link.v2 policy's face. A `link.v1` policy states
    /// no reply timeout and no transport, and is refused, as a face it
    /// does not name is.
    pub fn far_side(&self, face: &str) -> Result<FarSide, FarSideRefusal> {
        let (Profile::V2, Some(transport)) = (self.profile, self.transport) else {
            return Err(FarSideRefusal::NotV2);
        };
        let Some(f) = self.faces.get(face) else {
            return Err(FarSideRefusal::NoFace {
                face: face.to_owned(),
                faces: self.faces.keys().cloned().collect(),
            });
        };
        // A link.v2 face that parsed states both (v2 §2.1).
        let (Some(reply_timeout_ms), Some(arq)) = (f.reply_timeout_ms, f.arq) else {
            return Err(FarSideRefusal::NotV2);
        };
        Ok(FarSide {
            face: face.to_owned(),
            reply_timeout_ms,
            arq,
            transport,
        })
    }
}

// ── link.v2: the far side's readers and callers (v2 §2.20, §2.21) ────────

/// How many horizons of silence a subscription across a face waits before
/// it is declared again (core §8.5, v2 §2.21).
pub const SILENT_HORIZONS: u32 = 2;

/// What a reader or a caller on the far side of one face of a link.v2
/// policy takes from the policy (v2 §2.20, §2.21; core §8.1, §8.5): how
/// long a reply may take, whether the medium repairs a lost frame, and the
/// transport its own session runs (v2 §2.16).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FarSide {
    /// The face's name in the policy.
    pub face: String,
    /// `reply_timeout_ms`: the deployment's word to every caller across
    /// the face (v2 §2.1).
    pub reply_timeout_ms: u64,
    /// `arq`: whether the medium repairs a lost frame below zenoh.
    pub arq: bool,
    /// The router's `[transport]`, which both ends run (v2 §2.16).
    pub transport: Transport,
}

impl FarSide {
    /// How long a caller across the face waits at least (core §8.1).
    #[must_use]
    pub fn reply_timeout(&self) -> std::time::Duration {
        std::time::Duration::from_millis(self.reply_timeout_ms)
    }

    /// `timeout`, raised to the face's reply timeout when it is shorter
    /// (core §8.1: at least the face's).
    #[must_use]
    pub fn at_least(&self, timeout: std::time::Duration) -> std::time::Duration {
        timeout.max(self.reply_timeout())
    }

    /// Whether a reader across the face declares a silent subscription
    /// again (core §8.5): where the medium repairs no lost frame. With
    /// ARQ, a frame arrives or the transport closes, and a transport that
    /// opens again declares everything anew.
    #[must_use]
    pub fn redeclares(&self) -> bool {
        !self.arq
    }

    /// The configuration a session across the face runs (v2 §2.16, §2.18):
    /// each `[transport]` key at zenoh's key, in zenoh's units, as the far
    /// end's block writes it: a client of the near router is the gateway
    /// client's session.
    #[must_use]
    pub fn session_keys(&self) -> Vec<(TransportKey, Value)> {
        TransportKey::ALL
            .into_iter()
            .map(|k| (k, self.transport.value(k)))
            .collect()
    }

    /// The silence after which a subscription with `horizon` is declared
    /// again: [`SILENT_HORIZONS`] of it (core §8.5).
    #[must_use]
    pub fn silence(horizon: std::time::Duration) -> std::time::Duration {
        horizon.saturating_mul(SILENT_HORIZONS)
    }
}

/// Why [`FacePolicy::far_side`] gave no far side.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FarSideRefusal {
    /// A `link.v1` policy: no reply timeout, no ARQ, no transport.
    NotV2,
    /// The policy has no face of that name; its faces, in order.
    NoFace { face: String, faces: Vec<String> },
}

impl fmt::Display for FarSideRefusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotV2 => f.write_str(
                "a link.v1 policy states no reply timeout and no transport: a far side reads a \
                 link.v2 policy (link.v2 §2.20)",
            ),
            Self::NoFace { face, faces } => write!(
                f,
                "the policy has no face {face:?}; its faces are {}",
                faces.join(", ")
            ),
        }
    }
}

/// The most repair subscriptions one subscription declares (core §8.5).
pub const REPAIRS: u32 = 3;

/// The key expression of `selector`'s `n`-th repair subscription (core
/// §8.5), `n` from 1: `selector` with `$*` placed in the last chunk of its
/// literal prefix, the chunks before its first wildcard, at that chunk's
/// end for the first repair and one character further left for each
/// later one (`…/frames/fast$*`, then `…/frames/fas$*t`; an event's
/// `…/face/device_fault$*/*`; a template's `…/port$*/*/rx`).
///
/// `$*` matches no character too, so a repair matches every key `selector`
/// does, and it is canonical. No reader's own subscription declares it, so
/// its router declares it toward the far side, and with a key expression
/// of its own: its literal prefix ends a chunk earlier than `selector`'s.
/// The selector may carry a namespace in front of `zk2`.
///
/// `None` for `n` past [`REPAIRS`] or past the chunk's first character,
/// and for a selector that is no zk2 data selector or whose literal prefix
/// ends before its resource (a template whose first chunk is a parameter):
/// `$*` on its kind or its interface would leave the far side's grants
/// (core §11.1).
#[must_use]
pub fn repair_key(selector: &str, n: u32) -> Option<String> {
    if n == 0 || n > REPAIRS {
        return None;
    }
    let chunks: Vec<&str> = selector.split('/').collect();
    // The kind's chunk: `zk2`, the address, an interface, a kind token,
    // and a resource after it.
    let kind = (0..chunks.len()).find(|&z| {
        chunks[z] == crate::grammar::GRAMMAR
            && z + 5 < chunks.len()
            && chunks[z + 3].parse::<crate::grammar::IfaceId>().is_ok()
            && chunks[z + 4].parse::<KindToken>().is_ok()
    })? + 4;
    // The literal prefix's last chunk: a plain chunk is ASCII and holds no
    // wildcard (core §1.2).
    let literal = chunks
        .iter()
        .position(|c| c.contains(['*', '$']))
        .unwrap_or(chunks.len());
    let at = literal.checked_sub(1).filter(|&i| i > kind)?;
    if !is_plain_chunk(chunks[at]) {
        return None;
    }
    let split = chunks[at].len().checked_sub(usize::try_from(n - 1).ok()?)?;
    let chunk = format!("{}$*{}", &chunks[at][..split], &chunks[at][split..]);
    let mut out = chunks.clone();
    out[at] = &chunk;
    let repair = out.join("/");
    keyexpr::new(repair.as_str()).ok()?;
    Some(repair)
}

/// The horizon of a subscription to `r`, a resource of `c`, that a reader
/// across a face declares again after silence (core §8.5): its
/// `freshness.ttl_s` above 0, where its owner puts at least once a
/// horizon. A state of a contract that uses `freshness.v2` has none of its
/// own: its owner re-puts nothing, and its heartbeat's subscription speaks
/// for it ([`redeclare_heartbeat_horizon`]). `None`: never silent this way.
#[must_use]
pub fn redeclare_horizon(c: &Contract, r: &Resource) -> Option<std::time::Duration> {
    if matches!(r.kind, Kind::State) && freshness::uses_v2(c) {
        return None;
    }
    freshness::horizon_of(r).ttl()
}

/// The horizon of a subscription to `c`'s heartbeat (core §8.5,
/// `freshness.v2` §2.4): the shortest of the collections it covers, where
/// `c` uses `freshness.v2` and has one.
#[must_use]
pub fn redeclare_heartbeat_horizon(c: &Contract) -> Option<std::time::Duration> {
    if !freshness::uses_v2(c) {
        return None;
    }
    crate::heartbeat::Layout::of(c).horizon()
}

/// The horizon of a subscription to an owner heartbeat key of `class`,
/// as a reader holding `c` alone can tell it (core §8.5, `freshness.v2`
/// §2.4): the shortest of `c`'s collections of that class, where `c` uses
/// `freshness.v2` and has one. A reader holding several revisions of one
/// provider takes the shortest among them
/// ([`freshness::Views::class_horizon`]).
#[must_use]
pub fn redeclare_owner_heartbeat_horizon(
    c: &Contract,
    class: crate::heartbeat::Class,
) -> Option<std::time::Duration> {
    if !freshness::uses_v2(c) {
        return None;
    }
    crate::heartbeat::Layout::of(c).class_horizon(class)
}

/// What [`parse`] read: the policy when no error refused it, and every
/// finding, sorted.
#[derive(Debug, Clone)]
pub struct Parsed {
    pub policy: Option<FacePolicy>,
    pub findings: Vec<Finding>,
}

const TOP_KEYS_V1: &[&str] = &["system", "services", "face"];
const TOP_KEYS_V2: &[&str] = &[
    "profile",
    "system",
    "services",
    "binding",
    "catalog",
    "transport",
    "face",
];

/// Reads a face policy, and lints it (§2.1): a `link.v1` one when it has
/// no `profile`, a link.v2 one when its `profile` is `"link.v2"` (v2 §2.1).
#[must_use]
pub fn parse(text: &str) -> Parsed {
    let refuse = |f: Finding| Parsed {
        policy: None,
        findings: vec![f],
    };
    let table: toml::Table = match toml::from_str(text) {
        Ok(t) => t,
        Err(_) => return refuse(Finding::new(Code::Toml, None, "")),
    };
    if crate::toml10::first_beyond_toml10(text).is_some() {
        return refuse(Finding::new(Code::Toml, None, ""));
    }
    let mut out = Vec::new();
    // Any other `profile` is a wrong value, and the rest is read as a
    // link.v2 policy, whose key it is (v2 §2.1).
    let profile = match table.get("profile") {
        None => Profile::V1,
        Some(toml::Value::String(s)) if s == PROFILE_V2 => Profile::V2,
        Some(_) => {
            out.push(Finding::new(Code::BadValue, None, "profile"));
            Profile::V2
        }
    };
    let top = match profile {
        Profile::V1 => TOP_KEYS_V1,
        Profile::V2 => TOP_KEYS_V2,
    };
    for k in table.keys() {
        if !top.contains(&k.as_str()) {
            out.push(Finding::new(Code::UnknownField, None, k.clone()));
        }
    }
    let system = match table.get("system") {
        None => {
            out.push(Finding::new(Code::MissingField, None, "system"));
            None
        }
        Some(toml::Value::String(s)) if is_plain_chunk(s) => Some(s.clone()),
        Some(_) => {
            out.push(Finding::new(Code::BadValue, None, "system"));
            None
        }
    };
    let services = match table.get("services") {
        None => {
            out.push(Finding::new(Code::MissingField, None, "services"));
            None
        }
        Some(v) => match plain_list(v) {
            Some(l) => Some(l),
            None => {
                out.push(Finding::new(Code::BadValue, None, "services"));
                None
            }
        },
    };
    // link.v2's top level: the binding, the catalog, the transport.
    let (binding, catalog, transport) = match profile {
        Profile::V1 => (Some(Binding::Zenoh1_10_1), None, None),
        Profile::V2 => {
            let binding = match table.get("binding") {
                None => {
                    out.push(Finding::new(Code::MissingField, None, "binding"));
                    None
                }
                Some(toml::Value::String(s)) => {
                    let b = Binding::parse(s);
                    if b.is_none() {
                        out.push(Finding::new(Code::BadValue, None, "binding"));
                    }
                    b
                }
                Some(_) => {
                    out.push(Finding::new(Code::BadValue, None, "binding"));
                    None
                }
            };
            let catalog = match table.get("catalog") {
                None => None,
                Some(toml::Value::String(s)) if is_catalog_id(s) => Some(s.clone()),
                Some(_) => {
                    out.push(Finding::new(Code::BadValue, None, "catalog"));
                    None
                }
            };
            let transport = match table.get("transport") {
                None => {
                    out.push(Finding::new(Code::TransportMissing, None, "transport"));
                    None
                }
                Some(toml::Value::Table(t)) => Some(parse_transport(t, &mut out)),
                Some(_) => {
                    out.push(Finding::new(Code::BadValue, None, "transport"));
                    None
                }
            };
            (binding, catalog, transport)
        }
    };
    let ctx = FaceCtx {
        profile,
        protocols: binding.map(Binding::protocols),
        transport: transport.as_ref(),
    };
    let mut faces = BTreeMap::new();
    match table.get("face") {
        None => out.push(Finding::new(Code::MissingField, None, "face")),
        Some(toml::Value::Table(t)) if t.is_empty() => {
            out.push(Finding::new(Code::BadValue, None, "face"));
        }
        Some(toml::Value::Table(t)) => {
            for (name, v) in t {
                if !is_plain_chunk(name) {
                    out.push(Finding::new(Code::BadValue, Some(name), ""));
                }
                match v {
                    toml::Value::Table(ft) => {
                        if let Some(face) = parse_face(name, ft, &ctx, &mut out) {
                            faces.insert(name.clone(), face);
                        }
                    }
                    _ => out.push(Finding::new(Code::BadValue, Some(name), "")),
                }
            }
        }
        Some(_) => out.push(Finding::new(Code::BadValue, None, "face")),
    }
    if let Some(protocols) = ctx.protocols {
        shared_protocols(&table, protocols, &mut out);
    }
    shared_far(&table, &mut out);
    if profile == Profile::V2 {
        device_listed(&table, system.as_deref(), services.as_deref(), &mut out);
    }
    sort_findings(&mut out);
    let policy = if out.iter().any(Finding::is_error) {
        None
    } else {
        Some(FacePolicy {
            profile,
            system: system.unwrap_or_default(),
            services: services.unwrap_or_default(),
            faces,
            binding: binding.unwrap_or_default(),
            transport: transport.as_ref().and_then(TransportDraft::complete),
            catalog,
        })
    };
    Parsed {
        policy,
        findings: out,
    }
}

/// A catalog's id: 8 lowercase hex digits (v2 §2.1).
fn is_catalog_id(s: &str) -> bool {
    s.len() == 8 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
}

/// `[transport]` as read, each key valid or not (`None`), an optional one
/// the policy omits at its default (v2 §2.1).
#[derive(Debug, Clone, Default)]
struct TransportDraft {
    lease_ms: Option<u64>,
    keep_alive: Option<u64>,
    wait_before_close_ms: Option<u64>,
    sequence: Option<Sequence>,
    batch_bytes: Option<u64>,
    open_timeout_ms: Option<u64>,
    accept_timeout_ms: Option<u64>,
    interests_timeout_ms: Option<u64>,
}

impl TransportDraft {
    fn complete(&self) -> Option<Transport> {
        Some(Transport {
            lease_ms: self.lease_ms?,
            keep_alive: self.keep_alive?,
            wait_before_close_ms: self.wait_before_close_ms?,
            sequence: self.sequence?,
            batch_bytes: self.batch_bytes?,
            open_timeout_ms: self.open_timeout_ms?,
            accept_timeout_ms: self.accept_timeout_ms?,
            interests_timeout_ms: self.interests_timeout_ms?,
        })
    }
}

/// Reads `[transport]` (v2 §2.1), and checks `wait_under_lease` (v2 §2.16)
/// when both keys it reads are valid.
fn parse_transport(t: &toml::Table, out: &mut Vec<Finding>) -> TransportDraft {
    let keys: Vec<&str> = TransportKey::ALL.iter().map(|k| k.key()).collect();
    for k in t.keys() {
        if !keys.contains(&k.as_str()) {
            out.push(Finding::new(
                Code::UnknownField,
                None,
                format!("transport.{k}"),
            ));
        }
    }
    let mut int = |key: TransportKey, hi: u64, default: Option<u64>| match t.get(key.key()) {
        None => {
            if default.is_none() {
                out.push(Finding::new(Code::MissingField, None, key.at()));
            }
            default
        }
        Some(v) => {
            let n = int_in(v, 1, hi);
            if n.is_none() {
                out.push(Finding::new(Code::BadValue, None, key.at()));
            }
            n
        }
    };
    let mut d = TransportDraft {
        lease_ms: int(TransportKey::Lease, MAX_U32, None),
        keep_alive: int(TransportKey::KeepAlive, MAX_KEEP_ALIVE, None),
        wait_before_close_ms: int(TransportKey::WaitBeforeClose, MAX_U32, None),
        sequence: None,
        batch_bytes: int(TransportKey::BatchBytes, MAX_BATCH, Some(MAX_BATCH)),
        open_timeout_ms: int(TransportKey::OpenTimeout, MAX_U32, Some(DEFAULT_TIMEOUT_MS)),
        accept_timeout_ms: int(
            TransportKey::AcceptTimeout,
            MAX_U32,
            Some(DEFAULT_TIMEOUT_MS),
        ),
        interests_timeout_ms: int(
            TransportKey::InterestsTimeout,
            MAX_U32,
            Some(DEFAULT_TIMEOUT_MS),
        ),
    };
    d.sequence = match t.get(TransportKey::Sequence.key()) {
        None => {
            out.push(Finding::new(
                Code::MissingField,
                None,
                TransportKey::Sequence.at(),
            ));
            None
        }
        Some(toml::Value::String(s)) => {
            let q = Sequence::parse(s);
            if q.is_none() {
                out.push(Finding::new(
                    Code::BadValue,
                    None,
                    TransportKey::Sequence.at(),
                ));
            }
            q
        }
        Some(_) => {
            out.push(Finding::new(
                Code::BadValue,
                None,
                TransportKey::Sequence.at(),
            ));
            None
        }
    };
    if let (Some(lease), Some(wbc)) = (d.lease_ms, d.wait_before_close_ms)
        && wbc < lease
    {
        out.push(Finding::new(
            Code::WaitUnderLease,
            None,
            TransportKey::WaitBeforeClose.at(),
        ));
    }
    d
}

/// An array of plain chunks, none repeated.
fn plain_list(v: &toml::Value) -> Option<Vec<String>> {
    let a = v.as_array()?;
    let mut seen = BTreeSet::new();
    let mut out = Vec::with_capacity(a.len());
    for x in a {
        let s = x.as_str().filter(|s| is_plain_chunk(s))?;
        if !seen.insert(s) {
            return None;
        }
        out.push(s.to_owned());
    }
    Some(out)
}

/// An integer of `v` within `lo..=hi`.
fn int_in(v: &toml::Value, lo: u64, hi: u64) -> Option<u64> {
    let i = v.as_integer()?;
    u64::try_from(i).ok().filter(|n| (lo..=hi).contains(n))
}

/// A link protocol list: non-empty strings, none repeated. `None` when it
/// is not one.
fn protocol_list(v: &toml::Value) -> Option<Vec<String>> {
    let a = v.as_array()?;
    if a.is_empty() {
        return None;
    }
    let mut seen = BTreeSet::new();
    let mut out = Vec::with_capacity(a.len());
    for x in a {
        let s = x.as_str()?;
        if !seen.insert(s) {
            return None;
        }
        out.push(s.to_owned());
    }
    Some(out)
}

const FACE_KEYS: &[&str] = &[
    "far",
    "attach",
    "region",
    "select",
    "class",
    "expose",
    "interval_s",
    "max_outage_s",
    "batch_bytes",
    "link_bps",
    "lease_ms",
];

/// A link.v2 face's keys (v2 §2.1): `link.v1`'s less `batch_bytes` and
/// `lease_ms`, which are `moved_field`, and the medium's three.
const FACE_KEYS_V2: &[&str] = &[
    "far",
    "attach",
    "region",
    "select",
    "class",
    "expose",
    "interval_s",
    "max_outage_s",
    "link_bps",
    "loss_ppm",
    "arq",
    "reply_timeout_ms",
    "horizon_s",
    "frames",
    "events",
    "devices",
    "opens",
];

/// What a face's `attach` names, when it is valid (§2.1; v2 §2.1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AttachKind {
    Client,
    South,
    Device,
}

/// A device face's `devices` (v2 §2.1): a non-empty array of addresses
/// `<system>/<service>`, each two plain chunks (core §1.2), none repeated.
/// `None` when it is not one: `devices` is one value.
fn device_list(v: &toml::Value) -> Option<Vec<String>> {
    let a = v.as_array()?;
    if a.is_empty() {
        return None;
    }
    let mut seen = BTreeSet::new();
    for x in a {
        let s = x.as_str()?;
        let (system, service) = s.split_once('/')?;
        if !is_plain_chunk(system) || !is_plain_chunk(service) || !seen.insert(s) {
            return None;
        }
    }
    // Sorted by their bytes (v2 §2.3).
    Some(seen.into_iter().map(str::to_owned).collect())
}

/// A face's `frames` (v2 §2.1): a table of entries, each keyed
/// `<iface>/<template>`, an interface id and a template with no parameter,
/// and valued `{every_s, keyframe_s}`. Each wrong entry is reported once,
/// `at` `frames.<entry>` or a key within it; `None` when any is wrong.
fn parse_frames(
    face: &str,
    v: &toml::Value,
    out: &mut Vec<Finding>,
) -> Option<BTreeMap<String, FrameCadence>> {
    let at = Some(face);
    let toml::Value::Table(t) = v else {
        out.push(Finding::new(Code::BadValue, at, "frames"));
        return None;
    };
    let mut ok = true;
    let mut frames = BTreeMap::new();
    for (k, v) in t {
        let entry = format!("frames.{k}");
        let mut bad = |out: &mut Vec<Finding>, code: Code, key: String| {
            out.push(Finding::new(code, at, key));
            ok = false;
        };
        let name = k.split_once('/').and_then(|(i, rest)| {
            let iface: crate::grammar::IfaceId = i.parse().ok()?;
            let template = Template::parse(rest).ok().filter(|t| !t.has_params())?;
            Some(format!("{iface}/stream/{}", template.as_str()))
        });
        if name.is_none() {
            bad(out, Code::BadValue, entry.clone());
        }
        let toml::Value::Table(e) = v else {
            if name.is_some() {
                bad(out, Code::BadValue, entry);
            }
            continue;
        };
        for key in e.keys() {
            if key != "every_s" && key != "keyframe_s" {
                bad(out, Code::UnknownField, format!("{entry}.{key}"));
            }
        }
        let every_s = match e.get("every_s") {
            None => {
                bad(out, Code::MissingField, format!("{entry}.every_s"));
                None
            }
            Some(v) => {
                let n = int_in(v, 1, MAX_U32);
                if n.is_none() {
                    bad(out, Code::BadValue, format!("{entry}.every_s"));
                }
                n
            }
        };
        let keyframe_s = match e.get("keyframe_s") {
            None => Some(None),
            Some(v) => {
                let n = int_in(v, 1, MAX_U32);
                if n.is_none() {
                    bad(out, Code::BadValue, format!("{entry}.keyframe_s"));
                }
                n.map(Some)
            }
        };
        if let (Some(name), Some(every_s), Some(keyframe_s)) = (name, every_s, keyframe_s) {
            frames.insert(
                name,
                FrameCadence {
                    every_s,
                    keyframe_s,
                },
            );
        }
    }
    ok.then_some(frames)
}

/// A face's `events` (v2 §2.1, §2.7): an array of entries
/// `<iface>/<template>`, an interface id and a template, none repeated,
/// possibly empty; each kept as the event resource's name (§0,
/// `<iface>/events/<template>`). `None` when it is not one: `events` is
/// one value, reported once.
fn parse_events(face: &str, v: &toml::Value, out: &mut Vec<Finding>) -> Option<BTreeSet<String>> {
    let read = || {
        let mut names = BTreeSet::new();
        for x in v.as_array()? {
            let (i, rest) = x.as_str()?.split_once('/')?;
            let iface: crate::grammar::IfaceId = i.parse().ok()?;
            let template = Template::parse(rest).ok()?;
            if !names.insert(format!("{iface}/events/{}", template.as_str())) {
                return None;
            }
        }
        Some(names)
    };
    let events = read();
    if events.is_none() {
        out.push(Finding::new(Code::BadValue, Some(face), "events"));
    }
    events
}

/// What a face is read against: its profile, its binding's link protocols
/// (`None` when the binding is not one: the check is skipped), and a
/// link.v2 policy's `[transport]`.
struct FaceCtx<'a> {
    profile: Profile,
    protocols: Option<&'static [&'static str]>,
    transport: Option<&'a TransportDraft>,
}

fn parse_face(
    name: &str,
    t: &toml::Table,
    ctx: &FaceCtx<'_>,
    out: &mut Vec<Finding>,
) -> Option<Face> {
    let at = Some(name);
    let v2 = ctx.profile == Profile::V2;
    let mut ok = true;
    let mut bad = |out: &mut Vec<Finding>, code: Code, key: &str| {
        out.push(Finding::new(code, at, key));
        ok = false;
    };
    for k in t.keys() {
        if v2 && (k == "batch_bytes" || k == "lease_ms") {
            bad(out, Code::MovedField, k);
        } else if !(if v2 { FACE_KEYS_V2 } else { FACE_KEYS }).contains(&k.as_str()) {
            bad(out, Code::UnknownField, k);
        }
    }
    let far = match t.get("far") {
        None => {
            bad(out, Code::MissingField, "far");
            None
        }
        Some(toml::Value::String(s)) if !s.is_empty() => Some(s.clone()),
        Some(_) => {
            bad(out, Code::BadValue, "far");
            None
        }
    };
    // `attach`, when it is valid: `device` only in a link.v2 policy, which
    // a link.v1 one knows nothing of (v2 §2.1).
    let attach = match t.get("attach") {
        None => {
            bad(out, Code::MissingField, "attach");
            None
        }
        Some(toml::Value::String(s)) if s == "client" => Some(AttachKind::Client),
        Some(toml::Value::String(s)) if s == "south-region" => Some(AttachKind::South),
        Some(toml::Value::String(s)) if v2 && s == "device" => Some(AttachKind::Device),
        Some(toml::Value::String(s)) if s == "router" => {
            bad(out, Code::RouterAttach, "attach");
            None
        }
        Some(_) => {
            bad(out, Code::BadValue, "attach");
            None
        }
    };
    let region = match t.get("region") {
        None => None,
        Some(toml::Value::String(s)) if !s.is_empty() && s.len() <= MAX_REGION => Some(s.clone()),
        Some(_) => {
            bad(out, Code::BadValue, "region");
            None
        }
    };
    match (attach, t.contains_key("region")) {
        (Some(AttachKind::South), false) => bad(out, Code::MissingField, "region"),
        (Some(AttachKind::Client | AttachKind::Device), true) => {
            bad(out, Code::BadValue, "region");
        }
        _ => {}
    }
    // `devices` (v2 §2.1): one value, required with `device` and refused
    // with any other `attach`, each checked against `attach` only when
    // `attach` is valid. A link.v1 face's is `unknown_field`, above.
    let devices = match t.get("devices") {
        Some(v) if v2 => {
            let l = device_list(v);
            if l.is_none() || matches!(attach, Some(AttachKind::Client | AttachKind::South)) {
                bad(out, Code::BadValue, "devices");
            }
            l
        }
        _ => None,
    };
    if attach == Some(AttachKind::Device) && !t.contains_key("devices") {
        bad(out, Code::MissingField, "devices");
    }
    // `opens` (v2 §2.1, §2.5): `"near"` only with `south-region`, checked
    // against `attach` only when `attach` is valid. A link.v1 face's is
    // `unknown_field`, above.
    let opens = match t.get("opens") {
        Some(v) if v2 => match v.as_str() {
            Some("far") => Some(Opens::Far),
            Some("near") if !matches!(attach, Some(AttachKind::Client | AttachKind::Device)) => {
                Some(Opens::Near)
            }
            _ => {
                bad(out, Code::BadValue, "opens");
                None
            }
        },
        _ => Some(Opens::Far),
    };
    let link_protocols = match t.get("select") {
        None => {
            bad(out, Code::MissingField, "select");
            None
        }
        Some(toml::Value::Table(s)) => {
            for k in s.keys() {
                if k == "interfaces" {
                    bad(out, Code::SelectInterfaces, "select.interfaces");
                } else if k != "link_protocols" {
                    bad(out, Code::UnknownField, &format!("select.{k}"));
                }
            }
            match s.get("link_protocols") {
                None => {
                    bad(out, Code::MissingField, "select.link_protocols");
                    None
                }
                Some(v) => match protocol_list(v) {
                    None => {
                        bad(out, Code::BadValue, "select.link_protocols");
                        None
                    }
                    // Against the binding's list, when the binding is one
                    // (v2 §2.4): each key is checked alone.
                    Some(l)
                        if ctx.protocols.is_some_and(|known| {
                            l.iter().any(|p| !known.contains(&p.as_str()))
                        }) =>
                    {
                        bad(out, Code::UnknownProtocol, "select.link_protocols");
                        None
                    }
                    Some(l) => Some(l),
                },
            }
        }
        Some(_) => {
            bad(out, Code::BadValue, "select");
            None
        }
    };
    match t.get("class") {
        None => bad(out, Code::MissingField, "class"),
        Some(toml::Value::String(s)) if s == "constrained" => {}
        Some(_) => bad(out, Code::BadValue, "class"),
    }
    let expose = match t.get("expose") {
        None => {
            bad(out, Code::MissingField, "expose");
            None
        }
        Some(toml::Value::String(s)) if s == "link" => Some(Expose::Link),
        Some(toml::Value::String(s)) if s == "none" => Some(Expose::None),
        Some(_) => {
            bad(out, Code::BadValue, "expose");
            None
        }
    };
    let interval_s = match t.get("interval_s") {
        None => None,
        Some(v) => match int_in(v, 1, MAX_U32) {
            Some(n) => Some(n),
            None => {
                bad(out, Code::BadValue, "interval_s");
                None
            }
        },
    };
    match (expose, t.contains_key("interval_s")) {
        (Some(Expose::Link), false) => bad(out, Code::MissingField, "interval_s"),
        (Some(Expose::None), true) => bad(out, Code::BadValue, "interval_s"),
        _ => {}
    }
    let mut int = |key: &str, lo: u64, hi: u64, required: bool| match t.get(key) {
        None => {
            if required {
                bad(out, Code::MissingField, key);
            }
            None
        }
        Some(v) => {
            let n = int_in(v, lo, hi);
            if n.is_none() {
                bad(out, Code::BadValue, key);
            }
            n
        }
    };
    let max_outage_s = int("max_outage_s", 1, MAX_U32, true);
    let link_bps = int("link_bps", 1, MAX_U32, true);
    if v2 {
        let loss_ppm = int("loss_ppm", 0, MAX_LOSS_PPM, true);
        let reply_timeout_ms = int("reply_timeout_ms", 1, MAX_U32, true);
        let horizon_s = int("horizon_s", 1, MAX_U32, false);
        let arq = match t.get("arq") {
            None => {
                bad(out, Code::MissingField, "arq");
                None
            }
            Some(toml::Value::Boolean(b)) => Some(*b),
            Some(_) => {
                bad(out, Code::BadValue, "arq");
                None
            }
        };
        let frames = match t.get("frames") {
            None => Some(None),
            Some(v) => {
                let f = parse_frames(name, v, out);
                if f.is_none() {
                    ok = false;
                }
                f.map(Some)
            }
        };
        let events = match t.get("events") {
            None => Some(None),
            Some(v) => {
                let e = parse_events(name, v, out);
                if e.is_none() {
                    ok = false;
                }
                e.map(Some)
            }
        };
        // Like `interval_s`, a face that exposes none lets nothing cross,
        // so it lists no frame and no event, and affords no horizon (v2
        // §2.1).
        if expose == Some(Expose::None) {
            for key in ["frames", "events", "horizon_s"] {
                if t.contains_key(key) {
                    out.push(Finding::new(Code::BadValue, at, key));
                    ok = false;
                }
            }
        }
        face_lints_v2(
            name,
            ctx.transport,
            link_bps,
            loss_ppm,
            reply_timeout_ms,
            arq,
            out,
        );
        if !ok {
            return None;
        }
        // The face is built only with its transport's batch and lease. When
        // either is missing, the policy is refused anyway, by the error that
        // `[transport]` itself pushed (`transport_missing`, or `bad_value` or
        // `missing_field` at its key, in `parse` and `parse_transport`), so
        // no policy is made of this face (`a_bad_transport_refuses_a_good_
        // face` holds it).
        let tr = ctx.transport?;
        return Some(Face {
            far: far?,
            attach: match attach? {
                AttachKind::Client => Attach::Client,
                AttachKind::South => Attach::SouthRegion { region: region? },
                AttachKind::Device => Attach::Device { devices: devices? },
            },
            link_protocols: link_protocols?,
            expose: expose?,
            interval_s,
            max_outage_s: max_outage_s?,
            batch_bytes: tr.batch_bytes?,
            link_bps: link_bps?,
            lease_ms: tr.lease_ms?,
            loss_ppm,
            arq,
            reply_timeout_ms,
            frames: frames?,
            events: events?,
            horizon_s,
            opens: opens?,
        });
    }
    let batch_bytes = int("batch_bytes", 1, MAX_BATCH, true);
    let lease_ms = int("lease_ms", 1, MAX_U32, false);
    // `batch_over_lease` needs these three keys alone, so it is checked
    // whatever else the face holds (§2.1: each key is checked alone).
    let lease = if t.contains_key("lease_ms") {
        lease_ms
    } else {
        Some(DEFAULT_LEASE_MS)
    };
    if let (Some(b), Some(bps), Some(l)) = (batch_bytes, link_bps, lease)
        && !within_lease(b, bps, l)
    {
        out.push(Finding::new(Code::BatchOverLease, at, "batch_bytes"));
    }
    if !ok {
        return None;
    }
    Some(Face {
        far: far?,
        attach: match attach? {
            AttachKind::Client => Attach::Client,
            AttachKind::South => Attach::SouthRegion { region: region? },
            // A link.v1 policy has no device face: `attach = "device"` is
            // its `bad_value`, above.
            AttachKind::Device => return None,
        },
        link_protocols: link_protocols?,
        expose: expose?,
        interval_s,
        max_outage_s: max_outage_s?,
        batch_bytes: batch_bytes?,
        link_bps: link_bps?,
        lease_ms: if t.contains_key("lease_ms") {
            lease_ms?
        } else {
            DEFAULT_LEASE_MS
        },
        loss_ppm: None,
        arq: None,
        reply_timeout_ms: None,
        frames: None,
        events: None,
        horizon_s: None,
        opens: Opens::Far,
    })
}

/// A link.v2 face's checks that read `[transport]` (v2 §2.1, §2.10,
/// §2.16), each made when the keys it reads are valid, whatever else the
/// policy holds.
fn face_lints_v2(
    name: &str,
    tr: Option<&TransportDraft>,
    link_bps: Option<u64>,
    loss_ppm: Option<u64>,
    reply_timeout_ms: Option<u64>,
    arq: Option<bool>,
    out: &mut Vec<Finding>,
) {
    let at = Some(name);
    let tr = tr.cloned().unwrap_or_default();
    let mut warn = |code: Code, key: String| out.push(Finding::new(code, at, key));
    if let (Some(b), Some(bps), Some(l)) = (tr.batch_bytes, link_bps, tr.lease_ms)
        && !within_lease(b, bps, l)
    {
        warn(Code::BatchOverLease, TransportKey::BatchBytes.at());
    }
    if let (Some(l), Some(k), Some(p)) = (tr.lease_ms, tr.keep_alive, loss_ppm)
        && flaps(l, k, p)
    {
        warn(Code::KeepAliveFlaps, TransportKey::KeepAlive.at());
    }
    if let (Some(q), Some(b), Some(l), Some(bps)) =
        (tr.sequence, tr.batch_bytes, tr.lease_ms, link_bps)
        && window_filled(q, b, l, bps)
    {
        warn(Code::SequenceWindow, TransportKey::Sequence.at());
    }
    for (key, timeout) in [
        (TransportKey::OpenTimeout, tr.open_timeout_ms),
        (TransportKey::AcceptTimeout, tr.accept_timeout_ms),
    ] {
        if let (Some(t), Some(bps)) = (timeout, link_bps)
            && under_handshake(t, bps)
        {
            warn(Code::OpenUnderHandshake, key.at());
        }
    }
    if let (Some(r), Some(bps), Some(b)) = (reply_timeout_ms, link_bps, tr.batch_bytes)
        && reply_short(r, bps, b)
    {
        warn(Code::ReplyTimeoutShort, "reply_timeout_ms".to_owned());
    }
    if arq == Some(false) {
        warn(Code::NoArq, "arq".to_owned());
    }
}

/// `shared_protocol` (§2.14), over every face whose protocol list is one
/// and names only link protocols of the binding's list: one naming another
/// is `unknown_protocol`, a wrong value, and checks that need it are
/// skipped (§2.1).
fn shared_protocols(table: &toml::Table, known: &[&str], out: &mut Vec<Finding>) {
    let Some(toml::Value::Table(faces)) = table.get("face") else {
        return;
    };
    let lists: Vec<(&String, Vec<String>)> = faces
        .iter()
        .filter_map(|(name, v)| {
            let l = protocol_list(v.get("select")?.get("link_protocols")?)?;
            l.iter()
                .all(|p| known.contains(&p.as_str()))
                .then_some((name, l))
        })
        .collect();
    for (i, (name, l)) in lists.iter().enumerate() {
        let shared = lists
            .iter()
            .enumerate()
            .any(|(j, (_, m))| i != j && l.iter().any(|p| m.contains(p)));
        if shared {
            out.push(Finding::new(
                Code::SharedProtocol,
                Some(name),
                "select.link_protocols",
            ));
        }
    }
}

/// `far_of_two_faces` (§2.1, §2.4, 0.7, F-125), over every face whose `far`
/// is one, whatever else the policy holds: one warning per far principal
/// two or more faces name, with no face, `at` its name. Its policy carries
/// every one of their plans' denies, and no zenoh rule is limited to a link
/// protocol, so each of its faces carries them all.
fn shared_far(table: &toml::Table, out: &mut Vec<Finding>) {
    let Some(toml::Value::Table(faces)) = table.get("face") else {
        return;
    };
    let mut named: BTreeMap<&str, usize> = BTreeMap::new();
    for v in faces.values() {
        if let Some(toml::Value::String(far)) = v.get("far")
            && !far.is_empty()
        {
            *named.entry(far.as_str()).or_default() += 1;
        }
    }
    for (far, n) in named {
        if n > 1 {
            out.push(Finding::new(Code::FarOfTwoFaces, None, far));
        }
    }
}

/// `device_listed` (v2 §2.1, §2.5), over every device face whose
/// `devices` is one, whatever else the policy holds: a device listed among
/// `services`, as `<system>/<service>`, or on another face. Each face
/// listing it has the finding, at `devices`.
fn device_listed(
    table: &toml::Table,
    system: Option<&str>,
    services: Option<&[String]>,
    out: &mut Vec<Finding>,
) {
    let Some(toml::Value::Table(faces)) = table.get("face") else {
        return;
    };
    let lists: Vec<(&String, Vec<String>)> = faces
        .iter()
        .filter(|(_, v)| v.get("attach").and_then(toml::Value::as_str) == Some("device"))
        .filter_map(|(name, v)| Some((name, device_list(v.get("devices")?)?)))
        .collect();
    let listed: BTreeSet<String> = match (system, services) {
        (Some(sys), Some(services)) => services.iter().map(|s| format!("{sys}/{s}")).collect(),
        _ => BTreeSet::new(),
    };
    for (i, (name, l)) in lists.iter().enumerate() {
        let elsewhere = l.iter().any(|d| {
            listed.contains(d)
                || lists
                    .iter()
                    .enumerate()
                    .any(|(j, (_, m))| i != j && m.contains(d))
        });
        if elsewhere {
            out.push(Finding::new(Code::DeviceListed, Some(name), "devices"));
        }
    }
}

// ── A router's transport (v2 §2.19) ───────────────────────────────────────

/// A transport value read as an integer: any u64, or a negative i64; `None`
/// for a value of another type.
fn integer(v: &Value) -> Option<i128> {
    v.as_u64()
        .map(i128::from)
        .or_else(|| v.as_i64().map(i128::from))
}

/// Whether two transport values say the same (v2 §2.19): integers by
/// value, anything else as JSON.
#[must_use]
pub fn same_value(a: &Value, b: &Value) -> bool {
    match (a.as_u64(), b.as_u64()) {
        (Some(x), Some(y)) => x == y,
        _ => a == b,
    }
}

/// Checks a router's configuration against a link.v2 policy's transport,
/// and the far end's against it (v2 §2.19): `router` and `peer` are the
/// keys each configuration states, a key it omits read at the binding's
/// default, and a `null` as zenoh reads one
/// ([`StatedTransport::null_left_out`]).
/// - `transport_differs`, each key whose router value is not the policy's;
/// - `wait_under_lease`, the router's `wait_before_close` below its lease,
///   whatever the policy says;
/// - `peer_differs`, the far end's lease or `keep_alive` not the router's;
/// - `face_timestamping`, the router stamping the puts it routes, read at
///   its mode ([`StatedTransport::stamps`]).
///
/// A `link.v1` policy states no transport: nothing to report.
#[must_use]
pub fn check_transport(
    policy: &FacePolicy,
    router: &StatedTransport,
    peer: Option<&StatedTransport>,
) -> Vec<Finding> {
    let mut out = Vec::new();
    let Some(planned) = &policy.transport else {
        return out;
    };
    let defaults = policy.binding.defaults();
    for key in TransportKey::ALL {
        if !same_value(&planned.value(key), &router.runs(key, &defaults)) {
            out.push(Finding::new(Code::TransportDiffers, None, key.at()));
        }
    }
    // Both read as integers, a u64's whole range among them; a negative
    // `wait_before_close`, which zenoh's i64 admits, is below any lease. A
    // value of another type (a string, a fraction) is no setting zenoh runs:
    // `transport_differs` has reported it above, since what the policy
    // plans is always an integer there, and this check has nothing to read.
    let lease_us = integer(&router.runs(TransportKey::Lease, &defaults)).map(|ms| ms * 1_000);
    let wbc_us = integer(&router.runs(TransportKey::WaitBeforeClose, &defaults));
    if let (Some(lease), Some(wbc)) = (lease_us, wbc_us)
        && wbc < lease
    {
        out.push(Finding::new(
            Code::WaitUnderLease,
            None,
            TransportKey::WaitBeforeClose.at(),
        ));
    }
    if let Some(peer) = peer {
        for key in [TransportKey::Lease, TransportKey::KeepAlive] {
            if !same_value(&router.runs(key, &defaults), &peer.runs(key, &defaults)) {
                out.push(Finding::new(Code::PeerDiffers, None, key.at()));
            }
        }
    }
    if router.stamps() {
        out.push(Finding::new(Code::FaceTimestamping, None, "timestamping"));
    }
    sort_findings(&mut out);
    out
}

/// The id of the deployment catalog the far side holds (v2 §2.19): the
/// catalog read as core §8.6 reads one, and its id §8.6's, as 8 lowercase
/// hex digits.
///
/// # Errors
/// The first refusal of §8.6's reading: such a file is no catalog, and
/// holds no id to compare.
pub fn catalog_id(text: &str) -> Result<String, crate::catalog::Refusal> {
    crate::catalog::Catalog::parse(text).map(|c| c.id().hex())
}

/// `catalog_mismatch` (v2 §2.19): the id of the catalog the far side holds,
/// `held`, is not the policy's, or the policy names none.
#[must_use]
pub fn check_catalog(policy: &FacePolicy, held: &str) -> Vec<Finding> {
    if policy.catalog.as_deref() == Some(held) {
        Vec::new()
    } else {
        vec![Finding::new(Code::CatalogMismatch, None, "catalog")]
    }
}

// ── The deployment ───────────────────────────────────────────────────────

/// One resource as the plan reads it: its template, its kind token, its
/// resolved annotations, whether it declares `history` (core §2.5), and,
/// for a frame resource (core §7.7), what the plan weighs of its frames;
/// and what link.v2 reads of it (v2 §2.16, §2.17): whether its type is
/// packed, whether its congestion is `block`, its longest put, and whether
/// its contract lists `link.v2`.
#[derive(Debug, Clone)]
pub struct Res {
    pub template: Template,
    pub token: KindToken,
    pub annotations: BTreeMap<String, Value>,
    pub history: bool,
    pub frame: Option<FrameFacts>,
    /// Its type is packed (core §7.6); a frame resource's always is. Read
    /// across revisions, packed only where every one types it packed (v2
    /// §2.3).
    pub packed: bool,
    /// Its congestion is `block` (core §2.4); across revisions, where any
    /// one declares it so.
    pub block: bool,
    /// Its priority is `data` (core §2.4); across revisions, where every
    /// one declares it so. Another priority adds a QoS extension to the
    /// push and the frame (link.v1 §2.8).
    pub priority_data: bool,
    /// It is express (core §2.4); across revisions, where any one is.
    pub express: bool,
    /// Its longest put's payload, in bytes: a packed record's longest
    /// (every optional field present) after an [`ENVELOPE_BYTES`] envelope,
    /// or a frame resource's largest frame. `None` for any other type.
    /// Across revisions, the longest of those that declare it `block`, or
    /// of every one where none does.
    pub longest_bytes: Option<u64>,
    /// The revision that declares it lists `link.v2` (v2 §2.17).
    pub link_v2: bool,
    /// The parameter its template declares as its epoch (core §4.3), whose
    /// members hold member tokens: on a device face, `epoch_on_device` (v2
    /// §2.5). Across revisions, any one's.
    pub epoch: Option<String>,
    /// A state whose deletes only a tombstone proves (v2 §2.11, 0.9; core
    /// S3): a per-key resource (core §4.2), or a template whose first chunk
    /// is a parameter, which has no snapshot key. [`tombstone_only`] reads
    /// it; across revisions, where any one is.
    pub tombstone_only: bool,
    /// A templated resource's cardinality (core §2.2), which an owner
    /// heartbeat's longest put reads of a collection (v2 §2.16): `None`
    /// for a template with no parameter, and for a templated one that
    /// states none, read there as no ceiling. Across revisions, the
    /// largest any one states.
    pub cardinality: Option<u64>,
}

impl Res {
    /// A resource of `token` at `template`, with resolved `annotations`, and
    /// nothing else stated: no history, no frame, a type that is not packed,
    /// `drop` at priority `data` and not express, no cardinality, in a
    /// revision that does not list `link.v2` and uses no profile
    /// ([`tombstone_only`]).
    #[must_use]
    pub fn new(template: Template, token: KindToken, annotations: BTreeMap<String, Value>) -> Self {
        Res {
            history: false,
            frame: None,
            packed: false,
            block: false,
            priority_data: true,
            express: false,
            longest_bytes: None,
            link_v2: false,
            epoch: None,
            tombstone_only: tombstone_only(token, &template, &annotations, |_| false),
            cardinality: None,
            template,
            token,
            annotations,
        }
    }

    /// Its shape, as [`crossing_v2`] reads it.
    #[must_use]
    pub fn shape(&self) -> Shape {
        Shape::of(
            self.token,
            self.template.has_params(),
            self.frame.is_some(),
            &self.annotations,
        )
    }
}

/// What the plan reads of a frame resource (§2.8): never downsampled, it
/// crosses at its own cadence.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FrameFacts {
    /// Its interval (core §7.7): its span, else its `timing.period_ms`,
    /// else unstated.
    pub interval_ms: Option<u64>,
    /// The payload of the largest frame its owner writes, in bytes
    /// ([`crate::frame::Layout::largest_payload_bytes`]); `None` when its
    /// record type's layout does not read.
    pub largest_bytes: Option<u64>,
    /// Its `keyframe_every` (core §7.7): a full record at least once every
    /// this many records. Across revisions, the least (v2 §2.7).
    pub keyframe_every: u32,
}

impl Res {
    /// What its QoS adds to its batch (link.v1 §2.8).
    #[must_use]
    pub fn qos(&self) -> PutQos {
        PutQos {
            block: self.block,
            priority_data: self.priority_data,
            express: self.express,
        }
    }

    /// `r` of contract `c`, as the plan reads it.
    #[must_use]
    pub fn of(c: &Contract, r: &Resource) -> Self {
        let data = match &r.body {
            crate::contract::Body::Data(d) => Some(d),
            crate::contract::Body::Operation(_) => None,
        };
        let frame = data.and_then(|d| d.frame.as_ref()).map(|p| FrameFacts {
            interval_ms: p.interval_ms(&r.annotations),
            largest_bytes: crate::frame::Layout::of_resource(c, r)
                .ok()
                .flatten()
                .map(|l| l.largest_payload_bytes()),
            keyframe_every: p.keyframe_every,
        });
        let packed = data.is_some_and(|d| d.type_.is_packed());
        let longest_bytes = match (&frame, data) {
            (Some(f), _) => f.largest_bytes,
            (None, Some(d)) if packed => c
                .packed_layout(&d.type_)
                .ok()
                .flatten()
                .map(|l| ENVELOPE_BYTES + l.max_bits().div_ceil(8)),
            _ => None,
        };
        Res {
            template: r.template.clone(),
            token: r.token,
            annotations: r.annotations.clone(),
            history: data.is_some_and(|d| d.history.is_some()),
            frame,
            packed,
            block: data.is_some_and(|d| d.congestion == crate::authoring::Congestion::Block),
            priority_data: data.is_none_or(|d| d.priority == crate::authoring::Priority::Data),
            express: data.is_some_and(|d| d.express),
            longest_bytes,
            link_v2: uses_v2(c),
            epoch: r.epoch.clone(),
            tombstone_only: tombstone_only(r.token, &r.template, &r.annotations, |p| {
                c.uses.iter().any(|u| u.to_string() == p)
            }),
            cardinality: r.cardinality.filter(|_| r.template.has_params()),
        }
    }
}

/// Whether a resource of `token` at `template`, with resolved
/// `annotations`, in a revision whose `uses` lists the profiles `uses`
/// says, is a state whose deletes only a tombstone proves (v2 §2.11, 0.9):
///
/// - a per-key resource (core §4.2,
///   [`crate::collection::per_key_in`]): a state that declares
///   `freshness.ttl_s` above 0, of a revision that does not use
///   `freshness.v2`; one whose annotations hold `desired.target_param`,
///   of a revision that does not use `desired.v2` (0.23); a metric
///   resource of `telemetry.v1` or `telemetry.v2` (a key of its
///   vocabulary), of a revision that uses one; any state of a revision
///   that uses `redundancy.v1`;
/// - a template whose first chunk is a parameter, which has no snapshot
///   key (core §4.2). A `desired.v2` desired resource at such a template
///   keeps its floor so, as 0.23's "unless its template's first chunk is
///   a parameter" says (`v2/plan.json`'s case 50, beside case 49's no
///   floor).
///
/// Every other state is read by snapshot, whose complete answer omits a
/// member deleted beyond the window.
#[must_use]
pub fn tombstone_only(
    token: KindToken,
    template: &Template,
    annotations: &BTreeMap<String, Value>,
    uses: impl Fn(&str) -> bool,
) -> bool {
    is_state(token)
        && (crate::collection::per_key_in(token, annotations, uses)
            || crate::collection::snapshot_prefix(template).is_none())
}

/// What the plan needs of the deployment (§2.3): the interfaces each listed
/// service implements, and the revisions given of each interface.
#[derive(Debug, Clone, Default)]
pub struct Deployment {
    /// A service's name → the interface ids it implements.
    pub implements: BTreeMap<String, Vec<String>>,
    /// An interface id → each revision given of it, as its resources. Two
    /// minors of one major are two revisions of one id: an annotation
    /// changed between them is a review (core §9.8), and two services of
    /// one deployment may run either (core §3.3). The plan reads them
    /// together, failing closed where they disagree (§2.3).
    pub interfaces: BTreeMap<String, Vec<Vec<Res>>>,
    /// The interface ids a revision given of which uses `freshness.v2`:
    /// their owners send a heartbeat covering them (`freshness.v2` §2.4),
    /// which crosses where a collection it covers does (§2.9).
    pub heartbeats: BTreeSet<String>,
    /// An interface id → the fingerprints of the revisions given of it as
    /// contracts, which link.v2's catalog check reads (v2 §2.18). A
    /// revision given as its resources alone has none.
    pub fingerprints: BTreeMap<String, BTreeSet<crate::canonical::Fingerprint>>,
    /// The catalog the far side decodes with (core §8.6), when the
    /// deployment gives it: a link.v2 plan then refuses a crossing revision
    /// it does not list (v2 §2.18).
    pub catalog: Option<crate::catalog::Catalog>,
    /// The interface ids a revision given of which uses either major of
    /// `redundancy` ([`crate::redundancy::is_governed`]): a device
    /// implementing one is `presence_required` (v2 §2.5, 0.29).
    pub governed: BTreeSet<String>,
    /// The principals the deployment binds by a usrpwd user name (core
    /// §11.1): a face the near router opens binds none of them, so a
    /// link.v2 plan refuses one whose far principal is (v2 §2.5).
    pub users: BTreeSet<String>,
    /// Whether the routers' `default_permission` is `allow` (core §11.2):
    /// a face the near router opens is then planned where its far principal
    /// is a user name, and warned of, since the face's subject, bound by its
    /// link protocols, carries the principal's denies whoever opened (v2
    /// §2.5). Under `deny`, the default, it is refused.
    pub default_allow: bool,
    /// The listed services, by name, whose owner heartbeats the deployment
    /// turns on (`freshness.v2` §2.4; §2.3, #1145). A `link.v1` plan warns
    /// of each that implements an interface whose heartbeat crosses a face
    /// (`owner_heartbeat_denied`, §2.9); a link.v2 plan reads none of it,
    /// its `link` owner heartbeat crossing where a heartbeat does.
    pub owner_heartbeats: BTreeSet<String>,
}

impl Deployment {
    /// Adds a contract's resources as a revision of its interface id, its
    /// heartbeat when it uses `freshness.v2`, and its fingerprint.
    pub fn add_contract(&mut self, c: &Contract) {
        if freshness::uses_v2(c) {
            self.heartbeats.insert(c.iface.to_string());
        }
        if crate::redundancy::is_governed(c) {
            self.governed.insert(c.iface.to_string());
        }
        self.fingerprints
            .entry(c.iface.to_string())
            .or_default()
            .insert(crate::canonical::Fingerprint::of(c));
        self.add_revision(
            c.iface.to_string(),
            c.resources.iter().map(|r| Res::of(c, r)).collect(),
        );
    }

    /// Adds one revision of `iface`, as its resources.
    pub fn add_revision(&mut self, iface: impl Into<String>, resources: Vec<Res>) {
        self.interfaces
            .entry(iface.into())
            .or_default()
            .push(resources);
    }
}

/// An interface's resources as the plan reads them across its revisions
/// (§2.3): each resource any revision declares, paired by kind token and
/// template, first revision first. A resource several revisions declare is
/// exposed only where every one of them reads `link` (§2.2 fails closed),
/// and has a horizon only where every one gives it a horizon above 0, the
/// least of them (§2.12). What link.v2 weighs is judged revision by
/// revision (v2 §2.3, 0.6, F-469), and so never hangs on their order: a
/// resource is packed only where every revision types it packed, timed
/// where any declares a deadline, and its longest put, for
/// `block_over_batch`, the longest a revision that declares it `block`
/// writes. A frame's largest frame is the largest any revision writes
/// (§2.3). The set holds the indices of the resources the revisions
/// disagree on: one reads `link`, another does not.
fn merge(revisions: &[Vec<Res>]) -> (Vec<Res>, BTreeSet<usize>) {
    let mut out: Vec<Res> = Vec::new();
    let mut readings: Vec<Vec<&Res>> = Vec::new();
    for rev in revisions {
        for r in rev {
            match out
                .iter()
                .position(|x| x.token == r.token && x.template == r.template)
            {
                Some(i) => readings[i].push(r),
                None => {
                    out.push(r.clone());
                    readings.push(vec![r]);
                }
            }
        }
    }
    let mut disagree = BTreeSet::new();
    for (i, rs) in readings.iter().enumerate() {
        let links = rs
            .iter()
            .filter(|r| exposure(kind_of(r.token), &r.annotations) == Exposure::Link)
            .count();
        // A frame's `history` is warned of where any revision declares it
        // (§2.8); its `frame` table is one in every revision of a major,
        // since a change to it is breaking (core §9.8), but for
        // `keyframe_every`, a review, of which the least binds (v2 §2.7).
        out[i].history = rs.iter().any(|r| r.history);
        if out[i].epoch.is_none() {
            out[i].epoch = rs.iter().find_map(|r| r.epoch.clone());
        }
        if let Some(f) = &mut out[i].frame {
            f.keyframe_every = rs
                .iter()
                .filter_map(|r| r.frame.map(|f| f.keyframe_every))
                .min()
                .unwrap_or(f.keyframe_every);
            // Each revision's largest frame, with its own record type and
            // `keyframe_every`: the largest of them.
            f.largest_bytes = rs
                .iter()
                .filter_map(|r| r.frame.and_then(|f| f.largest_bytes))
                .max();
        }
        // Each revision judged alone (v2 §2.3): a raw type in one draws
        // `not_packed`, a deadline in one makes it timed, and a `block`
        // one's longest put draws `block_over_batch`. A packed type grows
        // by a minor (core §7.6), so the longest is any revision's where
        // none is `block`.
        out[i].packed = rs.iter().all(|r| r.packed);
        if !timed(&out[i].annotations)
            && let Some(d) = rs
                .iter()
                .find_map(|r| r.annotations.get(crate::timing::DEADLINE_MS))
        {
            out[i]
                .annotations
                .insert(crate::timing::DEADLINE_MS.to_owned(), d.clone());
        }
        let block = rs.iter().any(|r| r.block);
        out[i].block = block;
        // The widest QoS any revision puts with (link.v1 §2.8): an owner
        // of either minor may run.
        out[i].priority_data = rs.iter().all(|r| r.priority_data);
        out[i].express = rs.iter().any(|r| r.express);
        out[i].tombstone_only = rs.iter().any(|r| r.tombstone_only);
        // An owner heartbeat's longest put (v2 §2.16) is the longest any
        // revision writes: no ceiling where one states none.
        out[i].cardinality = if rs.iter().any(|r| r.cardinality.is_none()) {
            None
        } else {
            rs.iter().filter_map(|r| r.cardinality).max()
        };
        out[i].longest_bytes = rs
            .iter()
            .filter(|r| r.block || !block)
            .filter_map(|r| r.longest_bytes)
            .max();
        if links > 0 && links < rs.len() {
            disagree.insert(i);
            out[i]
                .annotations
                .insert(EXPOSURE.to_owned(), Value::String("host".to_owned()));
        }
        let ttls: Vec<Option<std::time::Duration>> = rs.iter().map(|r| horizon(r).ttl()).collect();
        if ttls.windows(2).any(|w| w[0] != w[1]) {
            match ttls.into_iter().collect::<Option<Vec<_>>>() {
                Some(all) => {
                    let least = all.into_iter().min().unwrap_or_default();
                    out[i]
                        .annotations
                        .insert(freshness::TTL_S.to_owned(), Value::from(least.as_secs()));
                }
                None => {
                    out[i].annotations.remove(freshness::TTL_S);
                }
            }
        }
    }
    (out, disagree)
}

// ── The plan (§2.3–§2.12) ────────────────────────────────────────────────

/// One deny (§2.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Deny {
    pub id: String,
    pub flows: Vec<&'static str>,
    pub messages: Vec<&'static str>,
    pub key_exprs: Vec<String>,
}

/// One downsampling rule (§2.8).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Rule {
    pub key_expr: String,
    pub freq: f64,
}

/// A face's downsampling block (§2.8).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Downsampling {
    pub id: String,
    pub link_protocols: Vec<String>,
    pub flows: Vec<&'static str>,
    pub messages: Vec<&'static str>,
    pub rules: Vec<Rule>,
}

/// One `gateway.south` filter (§2.5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Filter {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub modes: Vec<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub region_names: Vec<String>,
}

/// One south subregion (§2.5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct South {
    pub filters: Vec<Filter>,
}

/// The near router's `gateway` block (§2.5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Gateway {
    pub south: Vec<South>,
}

/// The attachment, as the plan carries it (§2.5; v2 §2.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "shape")]
pub enum AttachPlan {
    #[serde(rename = "client")]
    Client,
    #[serde(rename = "south-region")]
    SouthRegion { region: String, gateway: Gateway },
    /// A device face's (v2 §2.3): its devices, sorted by their bytes.
    #[serde(rename = "device")]
    Device { devices: Vec<String> },
}

/// A listed owner of state's tombstone window floor (§2.11): under a
/// link.v2 policy, an owner of state whose deletes only a tombstone proves
/// ([`Res::tombstone_only`], v2 §2.11).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Window {
    pub service: String,
    pub min_s: u64,
}

/// A listed service's liveness evidence across the face (§2.12).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Liveness {
    pub service: String,
    pub evidence: Vec<String>,
}

/// One face's plan (§2.3).
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct FacePlan {
    pub name: String,
    pub far: String,
    pub attach: AttachPlan,
    pub deny: Vec<Deny>,
    pub downsampling: Option<Downsampling>,
    pub windows: Vec<Window>,
    pub liveness: Vec<Liveness>,
    /// A link.v2 face's reply timeout, the deployment's word to every
    /// caller across it (v2 §2.18); absent for a `link.v1` face.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reply_timeout_ms: Option<u64>,
    /// A link.v2 face's listed frames that cross it, each at its cadence,
    /// sorted by name: the deployment's word to the far side (v2 §2.7,
    /// §2.18). Absent for a face with no `frames`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frames: Option<Vec<ListedFrame>>,
    pub findings: Vec<Finding>,
    /// What crosses the face, by name (§0): each resource of a listed
    /// interface whose pushes cross, overlapped ones set aside, each
    /// crossing heartbeat as `freshness.v2/stream/heartbeat/<iface>`
    /// (§2.9), and, on a link.v2 face, the `link` class's owner heartbeat
    /// key as `freshness.v2/stream/heartbeats/link` where it crosses (v2
    /// §2.9). A tool's scope across the face is read from it (observer
    /// §7.5). No router block carries it, so it is never serialized.
    #[serde(skip)]
    pub crossing: BTreeSet<String>,
}

impl FacePlan {
    /// Whether resource `token`/`template` of `iface` crosses the face.
    #[must_use]
    pub fn crosses(&self, iface: &str, token: KindToken, template: &Template) -> bool {
        self.crossing
            .contains(&format!("{iface}/{}/{}", token.as_str(), template.as_str()))
    }

    /// Whether the heartbeat covering `iface` crosses the face (§2.9).
    #[must_use]
    pub fn heartbeat_crosses(&self, iface: &str) -> bool {
        self.crossing.contains(&heartbeat_name(iface))
    }

    /// Whether the owner heartbeat key of `class` crosses the face: the
    /// `link` class's on a link.v2 face a listed interface's heartbeat
    /// crosses (v2 §2.9), the `host` class's never, and neither on a
    /// `link.v1` face (§2.9).
    #[must_use]
    pub fn owner_heartbeat_crosses(&self, class: crate::heartbeat::Class) -> bool {
        self.crossing.contains(&owner_heartbeat_name(class))
    }
}

/// A heartbeat's name in a plan, `freshness.v2/stream/heartbeat/<iface>`.
fn heartbeat_name(iface: &str) -> String {
    format!("{}/stream/heartbeat/{iface}", freshness::PROFILE_V2)
}

/// An owner heartbeat key's name in a plan,
/// `freshness.v2/stream/heartbeats/<class>` (v2 §2.9).
#[must_use]
pub fn owner_heartbeat_name(class: crate::heartbeat::Class) -> String {
    format!("{}/stream/heartbeats/{class}", freshness::PROFILE_V2)
}

/// A listed frame that crosses, as the plan carries it (v2 §2.18).
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ListedFrame {
    /// Its name (§0).
    pub resource: String,
    #[serde(flatten)]
    pub cadence: FrameCadence,
}

/// What [`plan_face`] found that the policy's other faces need: the
/// resources crossing it, the exposed frames it leaves unlisted, and the
/// interfaces with something crossing it (v2 §2.7, §2.18).
#[derive(Debug, Default)]
struct FaceFacts {
    crossing: BTreeSet<String>,
    unlisted: BTreeSet<String>,
    ifaces: BTreeSet<String>,
}

/// A resource's name in a plan, `<iface>/<token>/<template>` (§0).
fn res_name(iface: &str, r: &Res) -> String {
    format!("{iface}/{}/{}", r.token.as_str(), r.template.as_str())
}

/// Derives each face's plan (§2.3), faces sorted by name; or the
/// deployment's errors, which refuse it.
pub fn plan(policy: &FacePolicy, deployment: &Deployment) -> Result<Vec<FacePlan>, Vec<Finding>> {
    let mut errors = Vec::new();
    let mut listed: BTreeSet<&str> = BTreeSet::new();
    // The listed services and the devices, each read alike (v2 §2.5): a
    // device is named in the deployment by its address, and a device the
    // deployment names none for is `service_unknown` there (v2 §2.3).
    let services = policy.owners();
    for s in &services {
        match deployment.implements.get(s.key) {
            None => errors.push(Finding::new(Code::ServiceUnknown, None, s.key)),
            Some(ifaces) => {
                for i in ifaces {
                    if deployment
                        .interfaces
                        .get(i)
                        .is_some_and(|revs| !revs.is_empty())
                    {
                        listed.insert(i);
                    } else {
                        errors.push(Finding::new(Code::ContractUnknown, None, i.clone()));
                    }
                    // An owner on a first hop implements neither (v2 §2.5,
                    // core §8.1).
                    if let Some(face) = s.device_face
                        && (i == ARCHIVE || deployment.governed.contains(i))
                    {
                        errors.push(Finding::new(Code::PresenceRequired, Some(face), i.clone()));
                    }
                }
            }
        }
    }
    // A face the near router opens binds no user name (v2 §2.5): refused
    // under `deny`, where the far principal's grants would bind nothing, and
    // warned of under `allow`, where its denies hold through the face's
    // subject and nobody across the face is authenticated.
    let mut unauthenticated: BTreeSet<&str> = BTreeSet::new();
    for (name, face) in &policy.faces {
        if face.opens == Opens::Near && deployment.users.contains(&face.far) {
            if deployment.default_allow {
                unauthenticated.insert(name.as_str());
            } else {
                errors.push(Finding::new(Code::NearOpensUser, Some(name), "opens"));
            }
        }
    }
    if !errors.is_empty() {
        sort_findings(&mut errors);
        return Err(errors);
    }
    // Each listed interface read once across its revisions (§2.3).
    let view: View = listed
        .iter()
        .map(|i| ((*i).to_owned(), merge(&deployment.interfaces[*i])))
        .collect();
    let v2 = policy.profile == Profile::V2;
    // link.v2's contract side, read per revision given (v2 §2.17).
    if v2 {
        for i in &listed {
            for r in deployment.interfaces[*i].iter().flatten() {
                let e = exposure(kind_of(r.token), &r.annotations);
                if packed_required(r.link_v2, r.token, &e, r.packed) {
                    errors.push(Finding::new(Code::PackedRequired, None, res_name(i, r)));
                }
            }
        }
    }
    let mut faces: Vec<(FacePlan, FaceFacts)> = policy
        .faces
        .iter()
        .map(|(name, face)| {
            plan_face(
                policy,
                deployment,
                &view,
                &services,
                &listed,
                name,
                face,
                &mut errors,
            )
        })
        .collect();
    for (p, _) in &mut faces {
        if unauthenticated.contains(p.name.as_str()) {
            p.findings.push(Finding::new(
                Code::NearOpensUnauthenticated,
                Some(&p.name),
                "opens",
            ));
            sort_findings(&mut p.findings);
        }
    }
    if v2 {
        // An exposed frame no face lets across (v2 §2.7).
        let crossing: BTreeSet<String> = faces
            .iter()
            .flat_map(|(_, f)| f.crossing.iter().cloned())
            .collect();
        for (p, f) in &mut faces {
            for n in f.unlisted.iter().filter(|n| !crossing.contains(*n)) {
                p.findings
                    .push(Finding::new(Code::FrameUnlisted, Some(&p.name), n.clone()));
            }
            sort_findings(&mut p.findings);
        }
        // Every crossing revision is one the far side can decode (v2 §2.18).
        if let Some(cat) = &deployment.catalog {
            let ifaces: BTreeSet<&String> = faces.iter().flat_map(|(_, f)| &f.ifaces).collect();
            for i in ifaces {
                let Ok(id) = i.parse::<crate::grammar::IfaceId>() else {
                    continue;
                };
                for fp in deployment.fingerprints.get(i).into_iter().flatten() {
                    if cat.index_of(&id, fp).is_none() {
                        errors.push(Finding::new(
                            Code::CatalogMissing,
                            None,
                            format!("{i}@{fp}"),
                        ));
                    }
                }
            }
        }
    }
    if !errors.is_empty() {
        sort_findings(&mut errors);
        return Err(errors);
    }
    Ok(faces.into_iter().map(|(p, _)| p).collect())
}

/// Each listed interface's resources across its revisions, and the ones
/// they disagree on ([`merge`]).
type View = BTreeMap<String, (Vec<Res>, BTreeSet<usize>)>;

#[allow(clippy::too_many_arguments)]
fn plan_face(
    policy: &FacePolicy,
    deployment: &Deployment,
    view: &View,
    services: &[Owner<'_>],
    listed: &BTreeSet<&str>,
    name: &str,
    face: &Face,
    errors: &mut Vec<Finding>,
) -> (FacePlan, FaceFacts) {
    let mut findings = Vec::new();
    let mut facts = FaceFacts::default();
    let v2 = policy.profile == Profile::V2;
    let resources_of = |iface: &str| -> &[Res] { &view[iface].0 };
    // A put of a payload in one batch, with its allowance (§2.8, #1136): at
    // the transport's sequence width, or zenoh's default, 32 bits, for a
    // link.v1 policy, which states none.
    let sequence = policy.transport.map_or(Sequence::Bit32, |t| t.sequence);
    let fits = |payload: u64, qos: PutQos| {
        fits_batch(
            payload,
            face.batch_bytes,
            qos,
            sequence,
            &face.link_protocols,
        )
    };
    // Whether each resource of each listed interface crosses (§2.7; v2
    // §2.7, §2.8).
    let crossing_of = |iface: &str, r: &Res| {
        let e = exposure(kind_of(r.token), &r.annotations);
        if v2 {
            let name = res_name(iface, r);
            let listed = if r.token == KindToken::Events {
                face.events.as_ref().map(|l| l.contains(&name))
            } else {
                face.frames.as_ref().map(|f| f.contains_key(&name))
            };
            crossing_v2(r.token, r.shape(), &e, face.expose, listed)
        } else {
            crossing(r.token, r.template.has_params(), &e, face.expose)
        }
    };
    // A listed frame's entry names a frame resource of a listed interface
    // (v2 §2.7).
    for entry in face.frames.iter().flat_map(BTreeMap::keys) {
        let known = listed.iter().any(|i| {
            resources_of(i)
                .iter()
                .any(|r| r.frame.is_some() && &res_name(i, r) == entry)
        });
        if !known {
            errors.push(Finding::new(Code::FrameUnknown, Some(name), entry.clone()));
        }
    }
    // A listed event's entry names an event resource of a listed
    // interface (v2 §2.7).
    for entry in face.events.iter().flatten() {
        let known = listed.iter().any(|i| {
            resources_of(i)
                .iter()
                .any(|r| r.token == KindToken::Events && &res_name(i, r) == entry)
        });
        if !known {
            errors.push(Finding::new(Code::EventUnknown, Some(name), entry.clone()));
        }
    }
    for iface in listed {
        let (resources, disagree) = &view[*iface];
        for (i, r) in resources.iter().enumerate() {
            match crossing_of(iface, r).reason {
                Reason::Templated => findings.push(Finding::new(
                    Code::TemplatedExposure,
                    Some(name),
                    res_name(iface, r),
                )),
                Reason::Timed => findings.push(Finding::new(
                    Code::TimedDownsampled,
                    Some(name),
                    res_name(iface, r),
                )),
                // An unlisted frame is warned of (v2 §2.7); an unlisted
                // event is not.
                Reason::Unlisted if r.frame.is_some() => {
                    facts.unlisted.insert(res_name(iface, r));
                }
                _ => {}
            }
            if face.expose == Expose::Link && disagree.contains(&i) {
                findings.push(Finding::new(
                    Code::ExposureDisagrees,
                    Some(name),
                    res_name(iface, r),
                ));
            }
        }
    }

    // `zk` whole, or a device face's carve (v2 §2.6), then `adv` and
    // `admin`.
    let mut deny = if face.attach.is_device() {
        zk_carve()
    } else {
        vec![plane("zk", ZK_DENY)]
    };
    deny.extend([plane("adv", ADV_DENY), plane("admin", ADMIN_DENY)]);
    // Each template of a device's interface that declares `epoch`, on the
    // device's own face (v2 §2.5).
    for s in services.iter().filter(|s| s.device_face == Some(name)) {
        for iface in &deployment.implements[s.key] {
            for r in resources_of(iface).iter().filter(|r| r.epoch.is_some()) {
                findings.push(Finding::new(
                    Code::EpochOnDevice,
                    Some(name),
                    res_name(iface, r),
                ));
            }
        }
    }
    // The name (§0) of every overlapped resource.
    let mut overlapped: BTreeSet<String> = BTreeSet::new();
    // Each token's denies, computed with every stream last: a heartbeat
    // crosses where a collection it covers crosses, overlapped ones set
    // aside (§2.9), so the state tokens are carved first.
    let mut by_token: BTreeMap<usize, Vec<Deny>> = BTreeMap::new();
    let mut heartbeat_crosses: BTreeMap<String, bool> = BTreeMap::new();
    let order = [2usize, 3, 4, 0, 1];
    for t in order {
        let token = PUSH_TOKENS[t];
        if token == KindToken::Stream {
            heartbeat_crosses = heartbeats_of(deployment, listed, view, &|i: &str, r: &Res| {
                crossing_of(i, r).crosses() && !overlapped.contains(&res_name(i, r))
            });
        }
        // The listed interfaces' templates of the token, and, for
        // streams, each covered interface's heartbeat as a template of
        // `freshness.v2` of its own, in place of the profile's own
        // templated one (§2.9).
        // Each template with its own heartbeat's crossing, paired as one:
        // an interface id is a plain chunk, so every one parses, and one
        // that did not would drop out whole, never shift a pairing.
        let mut pseudo: Vec<(Template, bool)> = if token == KindToken::Stream {
            heartbeat_crosses
                .iter()
                .filter_map(|(i, crosses)| {
                    Template::parse(&format!("heartbeat/{i}"))
                        .ok()
                        .map(|t| (t, *crosses))
                })
                .collect()
        } else {
            Vec::new()
        };
        // The owner heartbeat keys with them (§2.9, v2 §2.9), whichever
        // revision of `freshness.v2`'s contract is given, and where none
        // is. A `link.v1` face lets neither class's cross, so the carve
        // holds the template `heartbeats/{class}`. A link.v2 face holds
        // the two keys: the `link` class's crosses exactly when a listed
        // interface's heartbeat does, the `host` class's never.
        if !pseudo.is_empty() {
            let link = heartbeat_crosses.values().any(|c| *c);
            let owner: Vec<(String, bool)> = if v2 {
                crate::heartbeat::Class::ALL
                    .into_iter()
                    .map(|c| {
                        (
                            format!("heartbeats/{c}"),
                            link && c == crate::heartbeat::Class::Link,
                        )
                    })
                    .collect()
            } else {
                vec![(crate::heartbeat::OWNER_RESOURCE.to_owned(), false)]
            };
            pseudo.extend(
                owner
                    .into_iter()
                    .filter_map(|(t, crosses)| Template::parse(&t).ok().map(|t| (t, crosses))),
            );
        }
        let mut groups: BTreeMap<String, Vec<Item<'_>>> = BTreeMap::new();
        for iface in listed {
            if !pseudo.is_empty() && *iface == freshness::PROFILE_V2 {
                continue;
            }
            groups.insert(
                (*iface).to_owned(),
                resources_of(iface)
                    .iter()
                    .filter(|r| r.token == token)
                    .map(|r| Item {
                        template: &r.template,
                        crosses: crossing_of(iface, r).crosses(),
                    })
                    .collect(),
            );
        }
        if !pseudo.is_empty() {
            groups.insert(
                freshness::PROFILE_V2.to_owned(),
                pseudo
                    .iter()
                    .map(|(template, crosses)| Item {
                        template,
                        crosses: *crosses,
                    })
                    .collect(),
            );
        }
        let any = groups.values().flatten().any(|i| i.crosses);
        if !any {
            by_token.insert(
                t,
                vec![push_deny(
                    token.as_str().to_owned(),
                    vec![format!("zk2/*/*/*/{}/**", token.as_str())],
                )],
            );
            continue;
        }
        let mut denies = Vec::new();
        for (iface, items) in &groups {
            let root = format!("zk2/*/*/{iface}/{}", token.as_str());
            let keys = if items.iter().any(|i| i.crosses) {
                let (keys, exact) = carve(&root, items);
                for c in items.iter().filter(|i| i.crosses) {
                    let hit = exact.iter().any(|&t| {
                        let t = items[t].template;
                        t.overlaps(c.template) && c.template.precedence(t) == Ordering::Greater
                    });
                    if hit {
                        let at = format!("{iface}/{}/{}", token.as_str(), c.template.as_str());
                        overlapped.insert(at.clone());
                        findings.push(Finding::new(Code::CarveOutOverlap, Some(name), at));
                    }
                }
                keys
            } else {
                vec![format!("{root}/**")]
            };
            if !keys.is_empty() {
                denies.push(push_deny(format!("{}:{iface}", token.as_str()), keys));
            }
        }
        by_token.insert(t, denies);
    }
    deny.extend(by_token.into_values().flatten());

    // The resources that cross, overlapped ones set aside.
    let crosses = |iface: &str, r: &Res| {
        crossing_of(iface, r).crosses() && !overlapped.contains(&res_name(iface, r))
    };

    // Downsampling (§2.8), the interval against the horizon (§2.12). A
    // device's stream is never downsampled on its own face, where its puts
    // arrive (v2 §2.8).
    let mut rules = Vec::new();
    if let Some(freq) = face.freq() {
        for s in services.iter().filter(|s| s.device_face != Some(name)) {
            for iface in &deployment.implements[s.key] {
                for r in resources_of(iface) {
                    // A frame is never downsampled (§2.8).
                    if is_stream(r.token) && r.frame.is_none() && crosses(iface, r) {
                        rules.push(Rule {
                            key_expr: format!(
                                "zk2/{}/{iface}/{}/{}",
                                s.address,
                                r.token.as_str(),
                                r.template.as_str()
                            ),
                            freq,
                        });
                    }
                }
            }
        }
        rules.sort_by(|a, b| a.key_expr.cmp(&b.key_expr));
        rules.dedup_by(|a, b| a.key_expr == b.key_expr);
        for iface in listed {
            for r in resources_of(iface) {
                if r.frame.is_some() {
                    continue;
                }
                if let (true, Some(ttl), Some(n)) = (
                    is_stream(r.token) && crosses(iface, r),
                    horizon(r).ttl(),
                    face.interval_s,
                ) && u128::from(n) * 2 > u128::from(ttl.as_secs())
                {
                    findings.push(Finding::new(
                        Code::IntervalOverHorizon,
                        Some(name),
                        res_name(iface, r),
                    ));
                }
            }
        }
    }
    // A crossing frame resource (§2.8, §2.12): its own cadence, against
    // the face's interval, its batch and its horizon, and its history. A
    // listed frame's cadence is its entry's `every_s` (v2 §2.8).
    let mut listed_frames = Vec::new();
    let mut cadences: Vec<u64> = Vec::new();
    for iface in listed {
        for r in resources_of(iface) {
            let Some(f) = r.frame.filter(|_| crosses(iface, r)) else {
                continue;
            };
            let at = || res_name(iface, r);
            let entry = face.frames.as_ref().and_then(|l| l.get(&at())).copied();
            let cadence_ms = entry.map_or(f.interval_ms, |e| Some(e.every_s * 1000));
            cadences.extend(cadence_ms);
            if let Some(e) = entry {
                listed_frames.push(ListedFrame {
                    resource: at(),
                    cadence: e,
                });
                // The owner may write full records more often than its contract says,
                // never less (v2 §2.7).
                if let Some(k) = e.keyframe_s
                    && u128::from(k) > u128::from(f.keyframe_every) * u128::from(e.every_s)
                {
                    errors.push(Finding::new(Code::KeyframeUnreachable, Some(name), at()));
                }
            }
            if let (Some(i), Some(n)) = (cadence_ms, face.interval_s)
                && u128::from(i) < u128::from(n) * 1000
            {
                findings.push(Finding::new(Code::FrameOverInterval, Some(name), at()));
            }
            // Its largest frame, with what zenoh writes beside it, in one
            // batch (§2.8, #1136).
            if f.largest_bytes.is_some_and(|b| !fits(b, r.qos())) {
                findings.push(Finding::new(Code::FrameOverBatch, Some(name), at()));
            }
            if r.history {
                findings.push(Finding::new(Code::HistoryOnFrame, Some(name), at()));
            }
            if let (Some(ttl), Some(i)) = (horizon(r).ttl(), cadence_ms)
                && u128::from(i) * 2 > ttl.as_millis()
            {
                findings.push(Finding::new(Code::IntervalOverHorizon, Some(name), at()));
            }
            if let (true, Some(ttl), Some(h)) = (v2, horizon(r).ttl(), face.horizon_s)
                && ttl.as_secs() < h
            {
                findings.push(Finding::new(Code::HorizonUnderFace, Some(name), at()));
            }
        }
    }
    // What crosses, by name: a tool's scope across the face (observer
    // §7.5).
    let mut crossing: BTreeSet<String> = listed
        .iter()
        .flat_map(|iface| {
            resources_of(iface)
                .iter()
                .filter(|r| crosses(iface, r))
                .map(|r| res_name(iface, r))
        })
        .collect();
    crossing.extend(
        heartbeat_crosses
            .iter()
            .filter(|(_, c)| **c)
            .map(|(i, _)| heartbeat_name(i)),
    );
    // The `link` class's owner heartbeat key crosses a link.v2 face exactly
    // when a listed interface's heartbeat does (v2 §2.9).
    let owner_link = v2 && heartbeat_crosses.values().any(|c| *c);
    let owner_at = || owner_heartbeat_name(crate::heartbeat::Class::Link);
    if owner_link {
        crossing.insert(owner_at());
    }
    // What else link.v2 weighs of each crossing resource (v2 §2.3, §2.16).
    if v2 {
        for iface in listed {
            for r in resources_of(iface).iter().filter(|r| crosses(iface, r)) {
                facts.crossing.insert(res_name(iface, r));
                facts.ifaces.insert((*iface).to_owned());
                if !r.packed {
                    findings.push(Finding::new(
                        Code::NotPacked,
                        Some(name),
                        res_name(iface, r),
                    ));
                }
                if r.block && r.longest_bytes.is_some_and(|b| !fits(b, r.qos())) {
                    findings.push(Finding::new(
                        Code::BlockOverBatch,
                        Some(name),
                        res_name(iface, r),
                    ));
                }
            }
        }
        // A crossing heartbeat: its horizon, the shortest of its
        // collections', and its period, half that (`freshness.v2` §2.4).
        for (iface, crosses) in &heartbeat_crosses {
            if !crosses {
                continue;
            }
            facts.ifaces.insert(iface.clone());
            let Some(ttl) = heartbeat_horizon(view, iface) else {
                continue;
            };
            cadences.push(ttl.as_secs() * 500);
            if face.horizon_s.is_some_and(|h| ttl.as_secs() < h) {
                findings.push(Finding::new(
                    Code::HorizonUnderFace,
                    Some(name),
                    heartbeat_name(iface),
                ));
            }
        }
        // The `link` owner heartbeat, where it crosses (v2 §2.9, §2.16):
        // one finding of each code for the face, whichever service draws
        // it, since every service's rides the one key.
        if owner_link {
            let (mut under, mut over) = (false, false);
            for s in services {
                let ifaces = &deployment.implements[s.key];
                // A heartbeat of each listed service that implements an
                // interface whose heartbeat crosses: its horizon, the
                // shortest of the service's `link` collections, and its
                // period, half that.
                if ifaces
                    .iter()
                    .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
                    && let Some(ttl) = owner_heartbeat_horizon(view, &heartbeat_crosses, ifaces)
                {
                    cadences.push(ttl.as_secs() * 500);
                    under |= face.horizon_s.is_some_and(|h| ttl.as_secs() < h);
                }
                // Its put is `drop`, and fragments the same: any listed
                // service's longest one against the batch.
                // At its key's QoS, `data` and `drop` (`freshness.v2`).
                over |=
                    owner_heartbeat_longest(view, &heartbeat_crosses, ifaces).is_some_and(|b| {
                        u64::try_from(b)
                            .ok()
                            .is_none_or(|b| !fits(b, PutQos::DATA_DROP))
                    });
            }
            if under {
                findings.push(Finding::new(Code::HorizonUnderFace, Some(name), owner_at()));
            }
            if over {
                findings.push(Finding::new(Code::BlockOverBatch, Some(name), owner_at()));
            }
        }
        // Data more often than the keep-alive interval spares the uplink
        // its keep-alives; at the interval itself each keep-alive races
        // the next batch, and goes first when that batch is late (v2
        // §2.16, #1108).
        if let (Some(t), Some(c)) = (&policy.transport, cadences.iter().min())
            && u128::from(*c) * u128::from(t.keep_alive) >= u128::from(t.lease_ms)
        {
            findings.push(Finding::new(
                Code::KeepAliveNotSuppressed,
                Some(name),
                TransportKey::KeepAlive.at(),
            ));
        }
    }
    listed_frames.sort_by(|a, b| a.resource.cmp(&b.resource));
    let downsampling = (!rules.is_empty()).then(|| Downsampling {
        id: name.to_owned(),
        link_protocols: face.link_protocols.clone(),
        flows: vec!["egress"],
        messages: vec!["put"],
        rules,
    });

    // Windows (§2.11) and liveness (§2.12).
    let mut windows = Vec::new();
    let mut liveness = Vec::new();
    for s in services {
        let ifaces = &deployment.implements[s.key];
        let resources = || {
            ifaces
                .iter()
                .flat_map(|i| resources_of(i).iter().map(move |r| (i, r)))
        };
        // v2 §2.11 (0.9): a link.v2 policy floors only an owner of state
        // whose deletes only a tombstone proves; link.v1 every owner of
        // state.
        if resources().any(|(_, r)| is_state(r.token) && (!v2 || r.tombstone_only)) {
            windows.push(Window {
                service: s.address.clone(),
                min_s: face.max_outage_s,
            });
        }
        let mut evidence: Vec<String> = resources()
            .filter(|(i, r)| crosses(i, r) && horizon(r).ttl().is_some())
            .map(|(i, r)| res_name(i, r))
            .collect();
        // An owner that turns its owner heartbeats on behind a `link.v1`
        // face: none crosses, and an interface they cover sends no
        // heartbeat of its own, so its far readers may hear no confirmation
        // (§2.9, #1145). Once for the service: the plan cannot tell which
        // interfaces its catalog lets them cover.
        if !v2
            && deployment.owner_heartbeats.contains(s.key)
            && ifaces
                .iter()
                .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
        {
            findings.push(Finding::new(Code::OwnerHeartbeatDenied, Some(name), s.key));
        }
        // A crossing heartbeat is evidence too (§2.12): its horizon is the
        // shortest of the collections it covers (`freshness.v2` §2.4).
        evidence.extend(
            ifaces
                .iter()
                .filter(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
                .map(|i| heartbeat_name(i)),
        );
        // Whichever form the service sends (v2 §2.9): where the `link`
        // key crosses, it is evidence of each service that implements an
        // interface whose heartbeat crosses.
        if owner_link
            && ifaces
                .iter()
                .any(|i| heartbeat_crosses.get(i.as_str()) == Some(&true))
        {
            evidence.push(owner_at());
        }
        evidence.sort();
        evidence.dedup();
        liveness.push(Liveness {
            service: s.address.clone(),
            evidence,
        });
    }

    sort_findings(&mut findings);
    let plan = FacePlan {
        name: name.to_owned(),
        far: face.far.clone(),
        attach: match &face.attach {
            Attach::Client => AttachPlan::Client,
            Attach::SouthRegion { region } => AttachPlan::SouthRegion {
                region: region.clone(),
                gateway: gateway(region),
            },
            Attach::Device { devices } => AttachPlan::Device {
                devices: devices.clone(),
            },
        },
        deny,
        downsampling,
        windows,
        liveness,
        reply_timeout_ms: face.reply_timeout_ms,
        frames: face.frames.as_ref().map(|_| listed_frames),
        findings,
        crossing,
    };
    (plan, facts)
}

fn horizon(r: &Res) -> Horizon {
    freshness::horizon(kind_of(r.token), &r.annotations)
}

/// A heartbeat's horizon: the shortest of the collections of `iface` it
/// covers (`freshness.v2` §2.9).
fn heartbeat_horizon(view: &View, iface: &str) -> Option<std::time::Duration> {
    view.get(iface)?
        .0
        .iter()
        .filter(|r| is_state(r.token))
        .filter_map(|r| horizon(r).ttl())
        .min()
}

/// A resource the plan reads as a collection (core §7.5): a state with a
/// horizon above 0, the revisions read together (§2.3).
fn is_collection(r: &Res) -> bool {
    is_state(r.token) && horizon(r).ttl().is_some()
}

/// Whether the plan reads a collection's class as `link` (`freshness.v2`
/// §2.4): its exposure, the revisions read together (§2.3), so one they
/// disagree on is `host`.
fn is_link(r: &Res) -> bool {
    exposure(kind_of(r.token), &r.annotations) == Exposure::Link
}

/// The interfaces among `ifaces`, one service's, that a `link` owner
/// heartbeat of that service holds a group for (v2 §2.9, §2.16): each one
/// with a heartbeat (`heartbeats`, [`heartbeats_of`]'s) that has a `link`
/// collection, whether or not that collection crosses the face. An owner
/// covers an interface in place of its heartbeat (`freshness.v2` §2.4), so
/// one with no heartbeat has no group.
fn owner_heartbeat_groups<'a>(
    view: &'a View,
    heartbeats: &'a BTreeMap<String, bool>,
    ifaces: &'a [String],
) -> impl Iterator<Item = &'a [Res]> {
    let mut seen = BTreeSet::new();
    ifaces
        .iter()
        .filter(move |i| heartbeats.contains_key(i.as_str()) && seen.insert(i.as_str()))
        .filter_map(|i| view.get(i.as_str()))
        .map(|(resources, _)| resources.as_slice())
        .filter(|rs| rs.iter().any(|r| is_collection(r) && is_link(r)))
}

/// A service's `link` owner heartbeat's horizon (v2 §2.9): the shortest
/// among the `link` collections of its listed interfaces.
fn owner_heartbeat_horizon(
    view: &View,
    heartbeats: &BTreeMap<String, bool>,
    ifaces: &[String],
) -> Option<std::time::Duration> {
    owner_heartbeat_groups(view, heartbeats, ifaces)
        .flatten()
        .filter(|r| is_collection(r) && is_link(r))
        .filter_map(|r| horizon(r).ttl())
        .min()
}

/// A service's longest `link` owner heartbeat, a put's payload in bytes
/// (v2 §2.16): [`ENVELOPE_BYTES`] of envelope, then its body's bits
/// rounded up to whole bytes. `None` for a service with no group.
///
/// ```text
/// body      46 bits (the time, the count of groups), then each group
/// group     14 bits (index, tag) · size · a map bit per collection of the
///           interface · each `link` collection's longest section
/// section   one member: 33 bits; templated, of cardinality c:
///           33 + ⌈log₂(c + 1)⌉ + c, every member live, and the bitmap
/// size      core §7.5's integer over the bits after it: 8 bits below
///           128, 16 below 16,384, and so on
/// ```
fn owner_heartbeat_longest(
    view: &View,
    heartbeats: &BTreeMap<String, bool>,
    ifaces: &[String],
) -> Option<u128> {
    use crate::heartbeat::{GROUPS_BITS, INDEX_BITS, TIME_BITS};
    let mut body = u128::from(TIME_BITS + GROUPS_BITS);
    let mut groups = 0;
    for resources in owner_heartbeat_groups(view, heartbeats, ifaces) {
        let collections = || resources.iter().filter(|r| is_collection(r));
        let sections: u128 = collections().count() as u128
            + collections()
                .filter(|r| is_link(r))
                .map(|r| {
                    crate::heartbeat::longest_section_bits(
                        r.template
                            .has_params()
                            .then(|| r.cardinality.unwrap_or(u64::from(u32::MAX))),
                    )
                })
                .sum::<u128>();
        body += u128::from(INDEX_BITS + 4) + crate::heartbeat::size_bits(sections) + sections;
        groups += 1;
    }
    (groups > 0).then(|| u128::from(ENVELOPE_BYTES) + body.div_ceil(8))
}

/// Each listed interface whose owners send a heartbeat covering it
/// (`freshness.v2` §2.4: a revision uses the profile, and it has a
/// collection, a state with a horizon above 0), and whether that heartbeat
/// crosses the face: where a collection it covers crosses (§2.9). Never
/// downsampled (§2.8): no rule is derived for it.
fn heartbeats_of(
    deployment: &Deployment,
    listed: &BTreeSet<&str>,
    view: &View,
    crosses: &dyn Fn(&str, &Res) -> bool,
) -> BTreeMap<String, bool> {
    let mut out = BTreeMap::new();
    for iface in listed {
        if !deployment.heartbeats.contains(*iface) {
            continue;
        }
        let collections: Vec<&Res> = view[*iface]
            .0
            .iter()
            .filter(|r| is_state(r.token) && horizon(r).ttl().is_some())
            .collect();
        if collections.is_empty() {
            continue;
        }
        out.insert(
            (*iface).to_owned(),
            collections.iter().any(|r| crosses(iface, r)),
        );
    }
    out
}

fn plane(id: &str, key: &str) -> Deny {
    Deny {
        id: id.to_owned(),
        flows: FLOWS.to_vec(),
        messages: MESSAGES.to_vec(),
        key_exprs: vec![key.to_owned()],
    }
}

/// The pairs of core §11.2's Own row, `(flow, message)`: what a far
/// principal's Own grant lets cross a device face on an instance key (v2
/// §2.6). Ingress `put`, `delete`, `declare_queryable`, `reply` and
/// `liveliness_token`; egress `query` and `declare_subscriber`.
pub const OWN_PAIRS: [(&str, &str); 7] = [
    ("ingress", "put"),
    ("ingress", "delete"),
    ("ingress", "declare_queryable"),
    ("ingress", "reply"),
    ("ingress", "liveliness_token"),
    ("egress", "query"),
    ("egress", "declare_subscriber"),
];

/// A device face's `zk` keys (v2 §2.6): every `@zk` form of core §1.1 but
/// the instance subtree, denied on every pair.
pub const ZK_CARVED: [&str; 3] = [
    "zk2/*/*/@zk/alive/**",
    "zk2/*/*/@zk/member/**",
    "zk2/@zk/**",
];

/// The instance subtree a device face lets cross on [`OWN_PAIRS`] alone
/// (v2 §2.6).
pub const ZK_INSTANCE: &str = "zk2/*/*/@zk/instance/**";

/// The messages of `flow` outside core §11.2's Own row, in [`MESSAGES`]'
/// order.
fn outside_own(flow: &str) -> Vec<&'static str> {
    MESSAGES
        .iter()
        .copied()
        .filter(|m| !OWN_PAIRS.contains(&(flow, *m)))
        .collect()
}

/// A device face's three denies in place of `zk` (v2 §2.6): `zk` on the
/// interface tokens, member tokens and contract keys, every pair; and the
/// instance subtree on the eleven pairs outside the Own row, one deny per
/// flow. So an instance key crosses on the Own row's seven pairs alone,
/// and whose instance keys is the far principal's grants' to decide.
#[must_use]
pub fn zk_carve() -> Vec<Deny> {
    let mut out = vec![Deny {
        id: "zk".to_owned(),
        flows: FLOWS.to_vec(),
        messages: MESSAGES.to_vec(),
        key_exprs: ZK_CARVED.iter().map(|k| (*k).to_owned()).collect(),
    }];
    for flow in FLOWS {
        out.push(Deny {
            id: format!("zk:instance:{flow}"),
            flows: vec![flow],
            messages: outside_own(flow),
            key_exprs: vec![ZK_INSTANCE.to_owned()],
        });
    }
    out
}

fn push_deny(id: String, mut key_exprs: Vec<String>) -> Deny {
    key_exprs.sort();
    key_exprs.dedup();
    Deny {
        id,
        flows: FLOWS.to_vec(),
        messages: PUSH_MESSAGES.to_vec(),
        key_exprs,
    }
}

/// The near router's `gateway` block for a far router in `region` (§2.5):
/// its own peers and clients south first, then the region.
#[must_use]
pub fn gateway(region: &str) -> Gateway {
    Gateway {
        south: vec![
            South {
                filters: vec![Filter {
                    modes: vec!["peer".to_owned(), "client".to_owned()],
                    region_names: Vec::new(),
                }],
            },
            South {
                filters: vec![Filter {
                    modes: Vec::new(),
                    region_names: vec![region.to_owned()],
                }],
            },
        ],
    }
}

// ── The carve-out (§2.7) ─────────────────────────────────────────────────

struct Item<'a> {
    template: &'a Template,
    crosses: bool,
}

/// A segment's place in a pattern, and its group.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Seg {
    Lit(String),
    Param,
    Rest,
}

impl Seg {
    fn of(s: &Segment) -> Self {
        match s {
            Segment::Literal(l) => Seg::Lit(l.clone()),
            Segment::Param(_) => Seg::Param,
            Segment::Rest(_) => Seg::Rest,
        }
    }

    fn kind(&self) -> u8 {
        match self {
            Seg::Lit(_) => 0,
            Seg::Param => 1,
            Seg::Rest => 2,
        }
    }

    /// A segment's pattern (§0): `{p}` is `*`, `{p...}` is `*/**`.
    fn pattern(&self) -> &str {
        match self {
            Seg::Lit(l) => l,
            Seg::Param => "*",
            Seg::Rest => "*/**",
        }
    }
}

/// `root`, the prefix's pattern, and `suffix`, with a `**` written once
/// before a `/**` that follows it.
fn key(root: &str, prefix: &[Seg], suffix: &str) -> String {
    let mut k = root.to_owned();
    for s in prefix {
        k.push('/');
        k.push_str(s.pattern());
    }
    k.push_str(suffix);
    while k.contains("/**/**") {
        k = k.replace("/**/**", "/**");
    }
    k
}

/// The carve-out of one interface's templates of one token (§2.7): the
/// denies, and the indices of the templates denied by their own pattern in
/// step 3.3.
fn carve(root: &str, items: &[Item<'_>]) -> (Vec<String>, Vec<usize>) {
    let mut keys = Vec::new();
    let mut exact = Vec::new();
    let all: Vec<usize> = (0..items.len()).collect();
    carve_at(root, items, &[], &all, &mut keys, &mut exact);
    keys.sort();
    keys.dedup();
    (keys, exact)
}

fn carve_at(
    root: &str,
    items: &[Item<'_>],
    prefix: &[Seg],
    here: &[usize],
    keys: &mut Vec<String>,
    exact: &mut Vec<usize>,
) {
    let d = prefix.len();
    let crosses = |i: &usize| items[*i].crosses;
    // 1. Nothing crosses: the subtree.
    if !here.iter().any(crosses) {
        keys.push(key(root, prefix, "/**"));
        return;
    }
    // 2. Everything crosses.
    if here.iter().all(crosses) {
        return;
    }
    let segs = |i: usize| items[i].template.segments();
    let (equal, longer): (Vec<usize>, Vec<usize>) = here.iter().partition(|&&i| segs(i).len() == d);
    // 3.1 The template equal to the prefix.
    if equal.iter().any(|i| !crosses(i)) {
        keys.push(key(root, prefix, ""));
    }
    // 3.2 Nothing longer crosses.
    if !longer.iter().any(crosses) {
        keys.push(key(root, prefix, "/*/**"));
        return;
    }
    // 3.3 More than one kind of next segment: template by template.
    let kinds: BTreeSet<u8> = longer
        .iter()
        .map(|&i| Seg::of(&segs(i)[d]).kind())
        .collect();
    if kinds.len() > 1 {
        for &i in &longer {
            if !items[i].crosses {
                let pattern: Vec<Seg> = segs(i).iter().map(Seg::of).collect();
                keys.push(key(root, &pattern, ""));
                exact.push(i);
            }
        }
        return;
    }
    // 3.4 Group by the next segment.
    let mut groups: BTreeMap<Seg, Vec<usize>> = BTreeMap::new();
    for &i in &longer {
        groups.entry(Seg::of(&segs(i)[d])).or_default().push(i);
    }
    for (seg, group) in groups {
        let mut p = prefix.to_vec();
        p.push(seg);
        carve_at(root, items, &p, &group, keys, exact);
    }
}

// ── Windows (§2.11) ──────────────────────────────────────────────────────

/// Each listed owner of state whose configured window (`windows`, by
/// address; [`DEFAULT_WINDOW_S`] when absent) is below a face's outage
/// (§2.11). Under a link.v2 policy, only an owner of state whose deletes
/// only a tombstone proves (v2 §2.11, [`Res::tombstone_only`]).
#[must_use]
pub fn check_windows(
    policy: &FacePolicy,
    deployment: &Deployment,
    windows: &BTreeMap<String, u64>,
) -> Vec<Finding> {
    let mut out = Vec::new();
    // The listed services and the devices (v2 §2.5).
    for s in policy.owners() {
        let Some(ifaces) = deployment.implements.get(s.key) else {
            continue;
        };
        // v2 §2.11 (0.9): under link.v2, only state whose deletes only a
        // tombstone proves, in any revision given.
        let v2 = policy.profile == Profile::V2;
        let owns_state = ifaces.iter().any(|i| {
            deployment.interfaces.get(i).is_some_and(|revs| {
                revs.iter()
                    .flatten()
                    .any(|r| is_state(r.token) && (!v2 || r.tombstone_only))
            })
        });
        if !owns_state {
            continue;
        }
        let addr = s.address;
        let w = windows.get(&addr).copied().unwrap_or(DEFAULT_WINDOW_S);
        for (name, face) in &policy.faces {
            if w < face.max_outage_s {
                out.push(Finding::new(
                    Code::WindowUnderOutage,
                    Some(name),
                    addr.clone(),
                ));
            }
        }
    }
    sort_findings(&mut out);
    out
}

// ── A router's block (§2.15) ─────────────────────────────────────────────

/// One deny of a router's block, as read.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlockDeny {
    pub flows: Vec<String>,
    pub messages: Vec<String>,
    pub key_exprs: Vec<String>,
}

/// One downsampling rule of a router's block, as read.
#[derive(Debug, Clone, PartialEq)]
pub struct BlockRule {
    pub key_expr: String,
    pub freq: f64,
}

/// zenoh's `default_permission`, as a router's block runs it (core §11.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Posture {
    Deny,
    Allow,
}

/// One subject of a router's block, as read (§2.4, §2.15): zenoh 1.10.1's
/// `AclConfigSubjects`. A session matches it when it matches every property
/// the subject names, and one value of each.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlockSubject {
    pub id: String,
    pub usernames: Vec<String>,
    pub cert_common_names: Vec<String>,
    /// `None` when the subject names no link protocol: it selects every one.
    /// An empty list, which zenoh 1.10.1 refuses to load (§2.15, 0.4), is
    /// read as `None`.
    pub link_protocols: Option<Vec<String>>,
    pub interfaces: Vec<String>,
    pub zids: Vec<String>,
}

impl BlockSubject {
    /// Whether it is bound to a principal: a user name or a CN.
    fn bound(&self) -> bool {
        !self.usernames.is_empty() || !self.cert_common_names.is_empty()
    }

    /// The link protocols it names; `None` for every one, an empty list
    /// included.
    fn protocols(&self) -> Option<&[String]> {
        self.link_protocols.as_deref().filter(|p| !p.is_empty())
    }

    /// Whether it selects the link protocol `p`.
    fn selects(&self, p: &str) -> bool {
        self.protocols().is_none_or(|l| l.iter().any(|x| x == p))
    }

    /// Whether it can match a session over `face` (§2.15): its link
    /// protocols are absent or name one of the face's. Interfaces and zids
    /// keep no session off a face: a zid is unauthenticated (core §11.3),
    /// and a face's link may report an interface.
    fn on_face(&self, face: &Face) -> bool {
        self.protocols()
            .is_none_or(|l| l.iter().any(|x| face.link_protocols.contains(x)))
    }

    /// Whether it is the far principal's (§2.15, 0.4, 0.5): it names `far`
    /// alone in one of its two lists, and nothing in the other. zenoh
    /// matches one value of each property a subject names, so a subject
    /// naming user names and CNs matches only a session presenting one of
    /// each (measured, 0.5, F-121), which the block cannot attribute to one
    /// principal.
    fn far_alone(&self, far: &str) -> bool {
        let only = |v: &[String]| !v.is_empty() && v.iter().all(|x| x == far);
        match (self.usernames.is_empty(), self.cert_common_names.is_empty()) {
            (false, true) => only(&self.usernames),
            (true, false) => only(&self.cert_common_names),
            _ => false,
        }
    }

    /// Whether it answers for the name `name` of the kind `kind` (§2.15,
    /// `narrowed_too_far`, 0.5): it names no interface and no zid, and
    /// either names no user name and no CN, or names `name` in the list of
    /// that kind and nothing in the other. A name no subject binds answers
    /// only to a subject bound to no principal.
    fn answers(&self, name: &str, kind: NameKind) -> bool {
        if !self.interfaces.is_empty() || !self.zids.is_empty() {
            return false;
        }
        if !self.bound() {
            return true;
        }
        let has = |v: &[String]| v.iter().any(|x| x == name);
        match kind {
            NameKind::User => self.cert_common_names.is_empty() && has(&self.usernames),
            NameKind::Cn => self.usernames.is_empty() && has(&self.cert_common_names),
            NameKind::Unbound => false,
        }
    }
}

/// The kind of a name `narrowed_too_far` reads (§2.15, 0.5): a user name
/// or a CN, as the list naming it says, or a face's `far` that no subject
/// names in either list, whose kind the block cannot tell.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum NameKind {
    User,
    Cn,
    Unbound,
}

/// One policy of a router's block, as read (§2.15, 0.4): the ids of the
/// subjects it lists. Its rules are not read here: which policies list a
/// subject is what the subject checks need.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct BlockPolicy {
    pub subjects: Vec<String>,
}

/// A block's posture, every subject it defines and every policy's subject
/// list, when they were read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BlockSubjects {
    pub posture: Posture,
    pub subjects: Vec<BlockSubject>,
    pub policies: Vec<BlockPolicy>,
}

impl BlockSubjects {
    /// The indices of the policies that list the subject `id`.
    fn listing(&self, id: &str) -> BTreeSet<usize> {
        self.policies
            .iter()
            .enumerate()
            .filter(|(_, p)| p.subjects.iter().any(|s| s == id))
            .map(|(i, _)| i)
            .collect()
    }
}

/// What a router runs for one face, as somebody read it (§2.15).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Block {
    /// The deployment's namespace, empty for none (core §1.6).
    pub namespace: String,
    /// The block's `enabled`, as read: `Some(false)` when access control is
    /// not enabled, which a tool reading a router's configuration also reads
    /// for an `enabled` absent from it, as zenoh 1.10.1 does (§2.15, 0.7,
    /// F-124); `None` when it was not read.
    pub enabled: Option<bool>,
    /// The denies of every policy that lists one subject that can match
    /// the far principal's sessions on the face (§2.15): a tool checks each
    /// such subject's denies alone, since any allow wins across subjects.
    pub deny: Vec<BlockDeny>,
    /// In the block's order.
    pub downsampling: Vec<BlockRule>,
    /// The block's posture, subjects and policies' subject lists, which
    /// [`check_subjects`] and [`check_narrowing`] read; `None` when they
    /// were not read.
    pub subjects: Option<BlockSubjects>,
}

/// Checks a router's block for the face `face` (§2.15): `block_disabled`
/// when its access control is not enabled (0.7, F-124), beside every other
/// finding, which reads the block as written; `zk_not_denied`;
/// `wildcard_downsampling` and `intersecting_downsampling`. On a device
/// face (`device`, v2 §2.15) `zk_not_denied` reads §2.6's carve: a whole
/// `zk` passes, and so does the carve; on any other face the carve fails.
#[must_use]
pub fn check_block(face: &str, device: bool, block: &Block) -> Vec<Finding> {
    let mut out = Vec::new();
    if block.enabled == Some(false) {
        out.push(Finding::new(Code::BlockDisabled, Some(face), "enabled"));
    }
    let ns = block.namespace.trim_matches('/');
    let with_ns = |k: &str| {
        if ns.is_empty() {
            k.to_owned()
        } else {
            format!("{ns}/{k}")
        }
    };
    let denied = if device {
        ZK_CARVED
            .iter()
            .all(|k| zk_denied_on(&with_ns(k), &block.deny, |_, _| true))
            && zk_denied_on(&with_ns(ZK_INSTANCE), &block.deny, |f, m| {
                !OWN_PAIRS.contains(&(f, m))
            })
    } else {
        zk_denied_on(&with_ns(ZK_DENY), &block.deny, |_, _| true)
    };
    if !denied {
        out.push(Finding::new(Code::ZkNotDenied, Some(face), "@zk"));
    }
    let parsed: Vec<Option<&keyexpr>> = block
        .downsampling
        .iter()
        .map(|r| keyexpr::new(r.key_expr.as_str()).ok())
        .collect();
    for (j, r) in block.downsampling.iter().enumerate() {
        // `*`, `**` and `$*` each carry a `*` (zenoh-keyexpr's own test).
        if parsed[j].is_none_or(|k| k.as_str().contains('*')) {
            out.push(Finding::new(
                Code::WildcardDownsampling,
                Some(face),
                r.key_expr.clone(),
            ));
        }
        let hit = (0..j).any(|i| match (parsed[i], parsed[j]) {
            (Some(a), Some(b)) => a.intersects(b),
            _ => false,
        });
        if hit {
            out.push(Finding::new(
                Code::IntersectingDownsampling,
                Some(face),
                r.key_expr.clone(),
            ));
        }
    }
    sort_findings(&mut out);
    out
}

/// Whether every pair of the nine messages and both flows that `pairs`
/// holds is denied on a key expression that includes `target` (§2.15; v2
/// §2.15).
fn zk_denied_on(target: &str, deny: &[BlockDeny], pairs: impl Fn(&str, &str) -> bool) -> bool {
    let Ok(target) = keyexpr::new(target) else {
        return false;
    };
    FLOWS.iter().all(|flow| {
        MESSAGES.iter().filter(|m| pairs(flow, m)).all(|m| {
            deny.iter().any(|d| {
                d.flows.iter().any(|f| f == flow)
                    && d.messages.iter().any(|x| x == m)
                    && d.key_exprs
                        .iter()
                        .any(|k| keyexpr::new(k.as_str()).is_ok_and(|k| k.includes(target)))
            })
        })
    })
}

/// Checks a router's subjects against the face `name` they must keep to
/// its far principal (§2.4, §2.15):
/// - `near_subject_on_face`, each subject on the face bound by a user name
///   or a CN that is not the far principal's, whatever else it names
///   (0.4): zenoh ties no credential to a link, and matches one value of
///   each property, so a session over the face with another name the
///   subject binds matches it. The far principal's names it alone in one
///   list and nothing in the other (0.5): a subject naming user names and
///   CNs matches only a session presenting one of each, whose principal
///   the block cannot tell, and its policies are not the far principal's;
/// - `face_subject_beyond_face`, each face subject (on the face, bound by
///   no user name and no CN) whose link protocols are absent or name one
///   outside the face's: sessions off the face match it too (0.4);
/// - `face_subject_misplaced`, each face subject not listed in exactly the
///   policies that list a subject of the far principal's on the face, at
///   least one: it would grant every session over the face another
///   policy's rules, miss one of the far principal's denies, or, listed in
///   none, get the default (0.4);
/// - `face_subject_missing`, under `allow`, each link protocol of the face
///   that no face subject naming no interface and no zid names in its
///   `link_protocols`: a session over it that matches no other subject
///   gets the default, everything.
#[must_use]
pub fn check_subjects(name: &str, face: &Face, block: &BlockSubjects) -> Vec<Finding> {
    let mut out = Vec::new();
    let on_face: Vec<&BlockSubject> = block.subjects.iter().filter(|s| s.on_face(face)).collect();
    // The far principal's policies: those listing one of its subjects on
    // the face.
    let far_policies: BTreeSet<usize> = on_face
        .iter()
        .filter(|s| s.far_alone(&face.far))
        .flat_map(|s| block.listing(&s.id))
        .collect();
    for s in &on_face {
        let mut found = |code: Code| out.push(Finding::new(code, Some(name), s.id.clone()));
        if s.bound() {
            if !s.far_alone(&face.far) {
                found(Code::NearSubjectOnFace);
            }
            continue;
        }
        if s.protocols()
            .is_none_or(|l| l.iter().any(|x| !face.link_protocols.contains(x)))
        {
            found(Code::FaceSubjectBeyondFace);
        }
        let listed = block.listing(&s.id);
        if listed.is_empty() || listed != far_policies {
            found(Code::FaceSubjectMisplaced);
        }
    }
    if block.posture == Posture::Allow {
        for p in &face.link_protocols {
            let selected = block.subjects.iter().any(|s| {
                !s.bound()
                    && s.interfaces.is_empty()
                    && s.zids.is_empty()
                    && s.protocols().is_some_and(|l| l.contains(p))
            });
            if !selected {
                out.push(Finding::new(
                    Code::FaceSubjectMissing,
                    Some(name),
                    p.clone(),
                ));
            }
        }
    }
    sort_findings(&mut out);
    out
}

/// Checks a router's subjects against every face of `policy` at once
/// (§2.4, §2.15, 0.4, 0.5): under `allow`, `narrowed_too_far` (no face,
/// `at` the name) for each name the block binds, read by kind: each user
/// name a subject names, as a user name; each CN, as a CN; and each face's
/// far principal that no subject names in either list, of a kind the block
/// cannot tell. Such a name is reported with a link protocol of §2.1's
/// list, outside every face whose far principal it is not, that no subject
/// answering for it selects: one naming no interface and no zid, and either
/// naming no user name and no CN, or naming the name in the list of its
/// kind and nothing in the other (0.5, F-121). zenoh matches one value of
/// each property a subject names, so a session with that name alone over
/// that link protocol matches no subject, and is allowed everything (core
/// §11.3): a far principal with no subject at all among them. One finding
/// per name, whichever kinds fail. Under `deny`, such a session gets
/// nothing, and there is nothing to report.
#[must_use]
pub fn check_narrowing(policy: &FacePolicy, block: &BlockSubjects) -> Vec<Finding> {
    let mut out = Vec::new();
    if block.posture != Posture::Allow {
        return out;
    }
    let mut names: BTreeSet<(&str, NameKind)> = BTreeSet::new();
    for s in &block.subjects {
        names.extend(s.usernames.iter().map(|u| (u.as_str(), NameKind::User)));
        names.extend(
            s.cert_common_names
                .iter()
                .map(|c| (c.as_str(), NameKind::Cn)),
        );
    }
    for f in policy.faces.values() {
        // Named in either list, by any subject, interfaces and zids
        // included: it is then read by the kinds those lists give it.
        let bound = block.subjects.iter().any(|s| {
            s.usernames
                .iter()
                .chain(&s.cert_common_names)
                .any(|x| *x == f.far)
        });
        if !bound {
            names.insert((f.far.as_str(), NameKind::Unbound));
        }
    }
    let mut bare_names: BTreeSet<&str> = BTreeSet::new();
    for (name, kind) in names {
        let kept: Vec<String> =
            narrowed(policy, |f| policy.faces[f].far == name).unwrap_or_else(|| {
                policy
                    .binding
                    .protocols()
                    .iter()
                    .map(|p| (*p).to_owned())
                    .collect()
            });
        let bare = kept.iter().any(|p| {
            !block
                .subjects
                .iter()
                .any(|s| s.answers(name, kind) && s.selects(p))
        });
        if bare {
            bare_names.insert(name);
        }
    }
    for name in bare_names {
        out.push(Finding::new(Code::NarrowedTooFar, None, name));
    }
    sort_findings(&mut out);
    out
}

/// The link protocols a subject bound to a principal is selected by, on the
/// router of `policy` (§2.4): every one of the binding's closed list (v2
/// §2.4; §2.1's nine for a `link.v1` policy) outside the faces whose far
/// principal it is not (`is_far`, by the face's name), in the list's order.
/// `None` when no face excludes any: the subject names none. Empty when
/// every protocol is excluded: the principal could connect over none.
#[must_use]
pub fn narrowed(policy: &FacePolicy, is_far: impl Fn(&str) -> bool) -> Option<Vec<String>> {
    let excluded: BTreeSet<&str> = policy
        .faces
        .iter()
        .filter(|(name, _)| !is_far(name))
        .flat_map(|(_, f)| f.link_protocols.iter().map(String::as_str))
        .collect();
    (!excluded.is_empty()).then(|| {
        policy
            .binding
            .protocols()
            .iter()
            .filter(|p| !excluded.contains(*p))
            .map(|p| (*p).to_owned())
            .collect()
    })
}

// ── Lint (§2.1, §2.3, §2.11, §2.15) ──────────────────────────────────────

/// What a linter is given: the policy's text, and what else it has.
#[derive(Debug, Clone, Copy, Default)]
pub struct LintInput<'a> {
    pub text: &'a str,
    /// When given, the plan is derived, and its findings included.
    pub deployment: Option<&'a Deployment>,
    /// The windows the deployment configures, by address; needs the
    /// deployment.
    pub windows: Option<&'a BTreeMap<String, u64>>,
    /// A router's block, and the face it guards.
    pub block: Option<(&'a str, &'a Block)>,
}

/// Every finding of a face policy and of what comes with it, sorted. The
/// plan, the windows and the block are checked only when the policy has no
/// error.
#[must_use]
pub fn lint(input: &LintInput<'_>) -> Vec<Finding> {
    let parsed = parse(input.text);
    let mut out = parsed.findings;
    let Some(policy) = parsed.policy else {
        return out;
    };
    if let Some(d) = input.deployment {
        match plan(&policy, d) {
            Ok(plans) => out.extend(plans.into_iter().flat_map(|p| p.findings)),
            Err(f) => out.extend(f),
        }
        if let Some(w) = input.windows {
            out.extend(check_windows(&policy, d, w));
        }
    }
    if let Some((face, block)) = input.block {
        let device = policy.faces.get(face).is_some_and(|f| f.attach.is_device());
        out.extend(check_block(face, device, block));
        if let Some(s) = &block.subjects {
            if let Some(f) = policy.faces.get(face) {
                out.extend(check_subjects(face, f, s));
            }
            out.extend(check_narrowing(&policy, s));
        }
    }
    sort_findings(&mut out);
    out
}

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

    fn ke(s: &str) -> &keyexpr {
        keyexpr::new(s).unwrap()
    }

    /// A binding reads from a tool's configuration by its policy name, and
    /// any other string is refused with the names it could have been.
    #[test]
    fn a_binding_deserializes_by_its_name() {
        for b in Binding::ALL {
            let read: Binding = serde_json::from_value(Value::from(b.as_str())).unwrap();
            assert_eq!(read, b);
            assert_eq!(serde_json::to_value(b).unwrap(), Value::from(b.as_str()));
        }
        let e = serde_json::from_value::<Binding>(Value::from("zenoh-1.10.0"))
            .unwrap_err()
            .to_string();
        assert!(
            e.contains("zenoh-1.10.0")
                && e.contains("`zenoh-1.10.1`")
                && e.contains("`zenoh-1.10.2`")
                && e.contains("`zm-1.10.2-r1`"),
            "{e}"
        );
        assert!(serde_json::from_value::<Binding>(Value::from(1)).is_err());
    }

    /// A binding parses from a tool's flag by its policy name, and any
    /// other string is refused with the names it could have been, from the
    /// one list, [`Binding::NAMES`], in [`Binding::ALL`]'s order.
    #[test]
    fn a_binding_parses_by_its_name() {
        assert_eq!(Binding::NAMES, Binding::ALL.map(Binding::as_str));
        for b in Binding::ALL {
            assert_eq!(b.as_str().parse::<Binding>(), Ok(b));
            assert_eq!(b.to_string().parse::<Binding>(), Ok(b));
        }
        let e = "zenoh-1.10.0".parse::<Binding>().unwrap_err();
        assert_eq!(e, UnknownBinding("zenoh-1.10.0".to_owned()));
        assert_eq!(
            e.to_string(),
            "not a binding; one of: zenoh-1.10.1, zenoh-1.10.2, zm-1.10.2-r1, or zm-1.10.2-r<n> \
             for a later release of the fork"
        );
        assert!("".parse::<Binding>().is_err());
        assert!(
            "Zenoh-1.10.1".parse::<Binding>().is_err(),
            "names are exact"
        );
    }

    /// A later release of the fork on zenoh 1.10.2 names the fork's
    /// binding (v2 §2.4; #1191): `zm-1.10.2-r2` parses, from a policy and
    /// from a flag, as `zm-1.10.2-r1`, with its protocols and defaults, and
    /// a policy naming it plans as one naming `r1` does. `r0`, a leading
    /// zero, no number, or anything after it is no binding.
    #[test]
    fn a_later_release_of_the_fork_names_its_binding() {
        for name in ["zm-1.10.2-r2", "zm-1.10.2-r10", "zm-1.10.2-r123"] {
            assert_eq!(Binding::parse(name), Some(Binding::Zm1_10_2R1), "{name}");
            assert_eq!(name.parse::<Binding>(), Ok(Binding::Zm1_10_2R1), "{name}");
            assert_eq!(
                serde_json::from_value::<Binding>(Value::from(name)).ok(),
                Some(Binding::Zm1_10_2R1),
                "{name}"
            );
        }
        for name in [
            "zm-1.10.2-r0",
            "zm-1.10.2-r01",
            "zm-1.10.2-r",
            "zm-1.10.2-r2x",
            "zm-1.10.2-r-2",
            "zm-1.10.3-r1",
            "zm-1.10.2",
        ] {
            assert_eq!(Binding::parse(name), None, "{name}");
        }
        let policy = |binding: &str| {
            format!(
                "profile  = \"link.v2\"\nsystem   = \"lab\"\nservices = [\"radio-a\"]\n\
                 binding  = \"{binding}\"\n\n[transport]\nlease_ms             = 240000\n\
                 keep_alive           = 4\nwait_before_close_ms = 240000\n\
                 sequence             = \"16bit\"\nbatch_bytes          = 222\n\n[face.radio]\n\
                 far              = \"ground\"\nattach           = \"client\"\n\
                 select           = {{ link_protocols = [\"unixsock-dgram\"] }}\n\
                 class            = \"constrained\"\nexpose           = \"link\"\n\
                 interval_s       = 60\nmax_outage_s     = 3600\nlink_bps         = 2400\n\
                 loss_ppm         = 0\narq              = true\nreply_timeout_ms = 15000\n"
            )
        };
        let r1 = parse(&policy("zm-1.10.2-r1"));
        let r2 = parse(&policy("zm-1.10.2-r2"));
        assert_eq!(
            r2.findings, r1.findings,
            "the same findings: none on unixsock-dgram"
        );
        let (r1, r2) = (r1.policy.expect("r1 reads"), r2.policy.expect("r2 reads"));
        assert_eq!(r2.binding, Binding::Zm1_10_2R1);
        assert_eq!(r2, r1, "a policy naming r2 reads as one naming r1");
    }

    /// Stock 1.10.2 reads as 1.10.1 (v2 §2.4, §2.19; #1165): one list of
    /// link protocols, `unixsock-dgram` not among them, and one column of
    /// defaults, whose 5 s `wait_before_close` is not the fork's 10 s. A
    /// policy names it all the same, and its plan carries it.
    #[test]
    fn zenoh_1_10_2_is_a_binding_that_reads_as_1_10_1() {
        let (stock, next, fork) = (
            Binding::Zenoh1_10_1,
            Binding::Zenoh1_10_2,
            Binding::Zm1_10_2R1,
        );
        assert_eq!(Binding::ALL, [stock, next, fork], "v2 §2.4's order");
        assert_eq!(next.protocols(), stock.protocols());
        assert!(!next.protocols().contains(&"unixsock-dgram"));
        assert!(fork.protocols().contains(&"unixsock-dgram"));
        assert_eq!(next.defaults(), stock.defaults());
        assert_eq!(next.defaults().wait_before_close_ms, 5_000);
        assert_ne!(next.defaults(), fork.defaults());
        assert_eq!(
            Binding::default(),
            stock,
            "a link.v1 policy reads as 1.10.1"
        );

        let policy = |protocol: &str| {
            format!(
                "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
                 binding = \"zenoh-1.10.2\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
                 wait_before_close_ms = 10000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
                 [face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
                 select = {{ link_protocols = [\"{protocol}\"] }}\n\
                 class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
                 link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n"
            )
        };
        let read = parse(&policy("unixsock-stream"));
        assert!(read.findings.is_empty(), "{:?}", read.findings);
        assert_eq!(read.policy.map(|p| p.binding), Some(next));
        let refused = parse(&policy("unixsock-dgram"));
        assert_eq!(
            refused.findings.iter().map(|f| f.code).collect::<Vec<_>>(),
            [Code::UnknownProtocol],
            "{:?}",
            refused.findings
        );
    }

    /// The zenoh facts the plan rests on (§0, §2.6, §2.7).
    #[test]
    fn key_expression_facts() {
        // `**` matches zero chunks: a subtree deny includes its prefix, and
        // `zk2/**/@zk/**` the contract keys.
        assert!(ke("zk2/*/*/m.v1/stream/a/**").includes(ke("zk2/h/s/m.v1/stream/a")));
        assert!(ke(ZK_DENY).includes(ke("zk2/@zk/contract/m.v1/abc")));
        assert!(ke(ZK_DENY).includes(ke("zk2/h/s/@zk/instance/0123456789abcdef")));
        assert!(ke("**/@zk/**").includes(ke(ZK_DENY)));
        // A rest parameter takes one or more chunks: `*/**` leaves its prefix.
        assert!(!ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs")));
        assert!(ke("zk2/*/*/m.v1/events/logs/*/**").includes(ke("zk2/h/s/m.v1/events/logs/a/b")));
        // `*` never matches a verbatim chunk, so a wholesale deny spells it.
        assert!(!ke("zk2/*/*/*/stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
        assert!(ke("zk2/*/*/*/@stream/**").includes(ke("zk2/h/s/m.v1/@stream/x")));
        assert!(ke(ADV_DENY).includes(ke("zk2/h/s/m.v1/stream/x/@adv/pub/abc")));
    }

    /// A device face's carve (v2 §2.6): an instance key crosses on the Own
    /// row's seven pairs and no other, and every other `@zk` key on none.
    #[test]
    fn the_carve_lets_an_instance_key_cross_on_the_own_pairs_alone() {
        let carve = zk_carve();
        let denied = |key: &str, flow: &str, m: &str| {
            carve.iter().any(|d| {
                d.flows.contains(&flow)
                    && d.messages.contains(&m)
                    && d.key_exprs.iter().any(|k| ke(k).includes(ke(key)))
            })
        };
        let instance = "zk2/lab/probe-a/@zk/instance/0123456789abcdef";
        let mut open = Vec::new();
        for flow in FLOWS {
            for m in MESSAGES {
                for key in [
                    "zk2/lab/probe-a/@zk/alive/probe.v1",
                    "zk2/lab/probe-a/@zk/member/0123456789abcdef/x",
                    "zk2/@zk/contract/probe.v1/abc",
                ] {
                    assert!(denied(key, flow, m), "{key} {flow} {m}");
                }
                if !denied(instance, flow, m) {
                    open.push((flow, m));
                }
            }
        }
        open.sort_unstable();
        let mut own = OWN_PAIRS.to_vec();
        own.sort_unstable();
        assert_eq!(open, own);
        // The carve names no address: whose instance keys is the grants'.
        assert!(
            carve
                .iter()
                .flat_map(|d| &d.key_exprs)
                .all(|k| k.starts_with("zk2/*/*/") || k == "zk2/@zk/**")
        );
    }

    #[test]
    fn keys_collapse_a_trailing_rest() {
        assert_eq!(
            key("r", &[Seg::Lit("x".into()), Seg::Rest], "/**"),
            "r/x/*/**"
        );
        assert_eq!(key("r", &[], "/**"), "r/**");
        assert_eq!(key("r", &[Seg::Lit("a".into())], "/*/**"), "r/a/*/**");
    }

    fn res(template: &str, annotations: Value) -> Res {
        Res::new(
            Template::parse(template).unwrap(),
            KindToken::Stream,
            serde_json::from_value(annotations).unwrap(),
        )
    }

    /// Two revisions read together (§2.3, 0.3): exposed only where every
    /// one that declares a resource exposes it, a horizon only where every
    /// one gives one, the least; a resource one revision adds is its own.
    #[test]
    fn revisions_are_read_together_failing_closed() {
        let a = vec![
            res(
                "x",
                serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
            ),
            res(
                "y",
                serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 10}),
            ),
            res("w", serde_json::json!({"link.exposure": "LINK"})),
        ];
        let b = vec![
            res("x", serde_json::json!({"freshness.ttl_s": 4})),
            res(
                "y",
                serde_json::json!({"link.exposure": "link", "freshness.ttl_s": 0}),
            ),
            res("w", serde_json::json!({})),
            res("z", serde_json::json!({"link.exposure": "link"})),
        ];
        let (m, disagree) = merge(&[a, b]);
        let read = |t: &str| {
            let r = m.iter().find(|r| r.template.as_str() == t).unwrap();
            (exposure_of_res(r), horizon(r).ttl().map(|d| d.as_secs()))
        };
        assert_eq!(read("x"), (Exposure::Host, Some(4)));
        assert_eq!(read("y"), (Exposure::Link, None));
        assert_eq!(read("z"), (Exposure::Link, None));
        // Two readings of host, one invalid: no disagreement to report.
        assert_eq!(disagree, BTreeSet::from([0]));
    }

    /// What link.v2 weighs, each revision judged alone, in either order
    /// (v2 §2.3, 0.6, F-469): one raw revision makes it not packed, one
    /// deadline timed, and the longest put is a `block` revision's.
    #[test]
    fn link_v2_judges_each_revision_alone() {
        let raw = res("s", serde_json::json!({"link.exposure": "link"}));
        let mut packed = raw.clone();
        packed.packed = true;
        packed.block = true;
        packed.longest_bytes = Some(300);
        let mut timed = raw.clone();
        timed.packed = true;
        timed.longest_bytes = Some(400);
        timed
            .annotations
            .insert(crate::timing::DEADLINE_MS.to_owned(), Value::from(2000));
        for revs in [
            [vec![raw.clone()], vec![packed.clone()], vec![timed.clone()]],
            [vec![timed.clone()], vec![packed.clone()], vec![raw.clone()]],
        ] {
            let (m, _) = merge(&revs);
            let r = &m[0];
            assert!(!r.packed, "one revision's raw type");
            assert!(r.shape().timed, "one revision's deadline");
            assert!(r.block);
            assert_eq!(r.longest_bytes, Some(300), "the block revision's");
        }
        let (m, _) = merge(&[vec![packed.clone()], vec![timed.clone()]]);
        assert!(m[0].packed, "packed in every revision");
        let (m, _) = merge(&[vec![timed.clone()], vec![raw]]);
        assert_eq!(m[0].longest_bytes, Some(400), "none block: the longest");
    }

    fn exposure_of_res(r: &Res) -> Exposure {
        match exposure(kind_of(r.token), &r.annotations) {
            Exposure::Invalid(_) => Exposure::Host,
            e => e,
        }
    }

    fn face(far: &str, protocols: &[&str]) -> Face {
        Face {
            far: far.to_owned(),
            attach: Attach::Client,
            link_protocols: protocols.iter().map(|p| (*p).to_owned()).collect(),
            expose: Expose::Link,
            interval_s: Some(1),
            max_outage_s: 1,
            batch_bytes: 1,
            link_bps: 1,
            lease_ms: DEFAULT_LEASE_MS,
            loss_ppm: None,
            arq: None,
            reply_timeout_ms: None,
            frames: None,
            events: None,
            horizon_s: None,
            opens: Opens::Far,
        }
    }

    /// A subject keeps the closed list outside every face whose far
    /// principal it is not (§2.4, 0.3).
    #[test]
    fn a_subject_is_narrowed_off_the_faces_it_is_not_far_of() {
        let policy = |faces: Vec<(&str, Face)>| FacePolicy {
            profile: Profile::V1,
            system: "lab".into(),
            services: vec![],
            faces: faces.into_iter().map(|(n, f)| (n.to_owned(), f)).collect(),
            binding: Binding::Zenoh1_10_1,
            transport: None,
            catalog: None,
        };
        let two = policy(vec![
            ("radio", face("ground", &["unixsock-stream"])),
            ("sat", face("sat", &["serial", "unixpipe"])),
        ]);
        let of = |p: &str| narrowed(&two, |name| two.faces[name].far == p);
        assert_eq!(
            of("local").unwrap(),
            ["tcp", "udp", "tls", "quic", "vsock", "ws"]
        );
        assert_eq!(
            of("ground").unwrap(),
            [
                "tcp",
                "udp",
                "tls",
                "quic",
                "unixsock-stream",
                "vsock",
                "ws"
            ]
        );
        let one = policy(vec![("radio", face("ground", &["unixsock-stream"]))]);
        assert_eq!(narrowed(&one, |_| true), None);
        let all = policy(vec![("x", face("x", Binding::Zenoh1_10_1.protocols()))]);
        assert_eq!(narrowed(&all, |_| false), Some(Vec::new()));
        // The fork's list keeps `unixsock-dgram`, after `unixsock-stream`
        // (v2 §2.4).
        let fork = FacePolicy {
            binding: Binding::Zm1_10_2R1,
            ..policy(vec![("radio", face("ground", &["unixsock-stream"]))])
        };
        assert_eq!(
            narrowed(&fork, |_| false).unwrap(),
            [
                "tcp",
                "udp",
                "tls",
                "quic",
                "serial",
                "unixpipe",
                "unixsock-dgram",
                "vsock",
                "ws"
            ]
        );
    }

    /// `keep_alive_flaps` over v2's Appendix B (v2 §2.16): at 5 % loss,
    /// 240 s with 4 keep-alives expects 0.36 false closes a day, 120 s with
    /// 2 expects 144; at no loss 2 never flaps, and 1 always does.
    #[test]
    fn the_keep_alive_lint_is_exact() {
        assert!(!flaps(240_000, 4, 50_000));
        assert!(!flaps(120_000, 4, 50_000));
        assert!(!flaps(1_080_000, 4, 50_000));
        assert!(flaps(120_000, 2, 50_000));
        assert!(flaps(60_000, 2, 50_000));
        assert!(!flaps(3_600_000, 2, 0));
        assert!(flaps(3_600_000, 1, 0));
        // 2 × 86,400 × 1,000 × 4 × 0.05^3 = lease_ms exactly: not above.
        assert!(!flaps(86_400, 4, 50_000));
        assert!(flaps(86_399, 4, 50_000));
        // The bounds, exactly: 255 keep-alives at 99.9999 % delivery.
        assert!(flaps(MAX_U32, MAX_KEEP_ALIVE, MAX_LOSS_PPM - 1));
        assert!(!flaps(MAX_U32, MAX_KEEP_ALIVE, 0));
    }

    /// A good face beside a `[transport]` that is not one never makes a
    /// policy (v2 §2.1): the face takes its batch and lease from it, and the
    /// error `[transport]` pushed refuses the whole.
    #[test]
    fn a_bad_transport_refuses_a_good_face() {
        let face = "[face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
                    select = { link_protocols = [\"unixsock-stream\"] }\n\
                    class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
                    link_bps = 2400\nloss_ppm = 0\narq = true\nreply_timeout_ms = 15000\n";
        let head = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
                    binding = \"zenoh-1.10.1\"\n";
        let good = "[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
                    wait_before_close_ms = 10000\nsequence = \"16bit\"\n";
        let ok = parse(&format!("{head}{good}{face}"));
        assert!(ok.policy.is_some(), "{:?}", ok.findings);
        for (transport, code, at) in [
            ("", Code::TransportMissing, "transport"),
            ("transport = 1\n", Code::BadValue, "transport"),
            (
                &good.replace("lease_ms = 10000", "lease_ms = 0"),
                Code::BadValue,
                "transport.lease_ms",
            ),
            (
                &good.replace("lease_ms = 10000\n", ""),
                Code::MissingField,
                "transport.lease_ms",
            ),
            (
                &format!("{good}batch_bytes = 65536\n"),
                Code::BadValue,
                "transport.batch_bytes",
            ),
        ] {
            let p = parse(&format!("{head}{transport}{face}"));
            assert!(p.policy.is_none(), "{transport:?}");
            assert!(
                p.findings
                    .iter()
                    .any(|f| f.code == code && f.at == at && f.face.is_none()),
                "{transport:?}: {:?}",
                p.findings
            );
        }
    }

    /// `wait_under_lease` reads both values as integers (v2 §2.19): a u64
    /// above i64::MAX and a negative i64 among them; a value of another type
    /// is `transport_differs`, which the check of every key reports.
    #[test]
    fn wait_under_lease_reads_integers_and_a_wrong_type_differs() {
        let p = parse(
            "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
             binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
             wait_before_close_ms = 10000\nsequence = \"32bit\"\n[face.rf]\n\
             far = \"ground\"\nattach = \"client\"\n\
             select = { link_protocols = [\"unixsock-stream\"] }\nclass = \"constrained\"\n\
             expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
             arq = true\nreply_timeout_ms = 15000\n",
        )
        .policy
        .expect("a policy");
        let wbc = TransportKey::WaitBeforeClose.path();
        let lease = TransportKey::Lease.path();
        let found = |pairs: &[(&str, Value)]| -> Vec<(&'static str, String)> {
            // A router that stamps nothing, as the generator writes it.
            let stated = StatedTransport(
                pairs
                    .iter()
                    .map(|(k, v)| ((*k).to_owned(), v.clone()))
                    .chain([("timestamping/enabled".to_owned(), Value::from(false))])
                    .collect(),
            );
            check_transport(&p, &stated, None)
                .into_iter()
                .map(|f| (f.code.as_str(), f.at))
                .collect()
        };
        let at = || "transport.wait_before_close_ms".to_owned();
        let differs = || ("transport_differs", at());
        let under = || ("wait_under_lease", at());
        assert_eq!(found(&[(wbc, Value::from(10_000_000u64))]), []);
        assert_eq!(found(&[(wbc, Value::from(u64::MAX))]), [differs()]);
        assert_eq!(found(&[(wbc, Value::from(-1i64))]), [differs(), under()]);
        assert_eq!(found(&[(wbc, Value::from("10000000"))]), [differs()]);
        assert_eq!(found(&[(wbc, Value::from(1.0e7))]), [differs()]);
        assert_eq!(
            found(&[
                (lease, Value::from("10000")),
                (wbc, Value::from(10_000_000u64))
            ]),
            [("transport_differs", "transport.lease_ms".to_owned())]
        );
    }

    /// A `null` among the eight keys (v2 §2.19, 0.18): left out at
    /// `routing/interests/timeout`, which zenoh fills with its default, so
    /// the key is not stated and reads at the binding's; a value stated,
    /// and none zenoh runs, at each of the seven other keys.
    #[test]
    fn a_null_reads_as_left_out_at_the_interests_timeout_alone() {
        let policy = |interests_ms: u64| {
            parse(&format!(
                "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
                 binding = \"zenoh-1.10.1\"\n[transport]\nlease_ms = 10000\nkeep_alive = 4\n\
                 wait_before_close_ms = 10000\nsequence = \"32bit\"\n\
                 interests_timeout_ms = {interests_ms}\n[face.rf]\n\
                 far = \"ground\"\nattach = \"client\"\n\
                 select = {{ link_protocols = [\"unixsock-stream\"] }}\nclass = \"constrained\"\n\
                 expose = \"none\"\nmax_outage_s = 3600\nlink_bps = 1000000\nloss_ppm = 0\n\
                 arq = true\nreply_timeout_ms = 15000\n"
            ))
            .policy
            .expect("a policy")
        };
        // The router's file, read from its tree: every key the policy's but
        // the one written `null`, and no stamp.
        let router = |null_at: TransportKey| {
            let mut tree = serde_json::json!({
                "transport": {
                    "link": {"tx": {
                        "lease": 10_000, "keep_alive": 4, "batch_size": 65_535,
                        "sequence_number_resolution": "32bit",
                        "queue": {"congestion_control": {"block": {
                            "wait_before_close": 10_000_000,
                        }}},
                    }},
                    "unicast": {"open_timeout": 10_000, "accept_timeout": 10_000},
                },
                "routing": {"interests": {"timeout": 10_000}},
                "timestamping": {"enabled": false},
            });
            let mut node = &mut tree;
            for part in null_at.path().split('/') {
                node = node.get_mut(part).expect("the path");
            }
            *node = Value::Null;
            StatedTransport::read(&tree)
        };
        let found = |p: &FacePolicy, r: &StatedTransport| -> Vec<(&'static str, String)> {
            check_transport(p, r, None)
                .into_iter()
                .map(|f| (f.code.as_str(), f.at))
                .collect()
        };
        let defaults = Binding::Zenoh1_10_1.defaults();
        let interests = TransportKey::InterestsTimeout;

        // At the interests timeout: kept as written, not stated, the default.
        let r = router(interests);
        assert_eq!(r.0.get(interests.path()), Some(&Value::Null));
        assert!(r.null_left_out(interests));
        assert!(!r.states(interests));
        assert_eq!(r.runs(interests, &defaults), Value::from(10_000u64));
        // Under a policy at the default it is the policy's: no finding.
        assert_eq!(found(&policy(10_000), &r), []);
        // Under another it is the default, not the policy's.
        assert_eq!(
            found(&policy(40_000), &r),
            [("transport_differs", interests.at())]
        );
        // The fork's default there is the same, so it reads alike.
        assert_eq!(
            r.runs(interests, &Binding::Zm1_10_2R1.defaults()),
            Value::from(10_000u64)
        );

        // At each other key: a value stated, which is no value zenoh runs.
        for key in TransportKey::ALL {
            if key == interests {
                continue;
            }
            let r = router(key);
            assert!(!r.null_left_out(key), "{}", key.key());
            assert!(r.states(key), "{}", key.key());
            assert_eq!(r.runs(key, &defaults), Value::Null, "{}", key.key());
            // `wait_under_lease` has no integer to read, and skips it.
            assert_eq!(
                found(&policy(10_000), &r),
                [("transport_differs", key.at())],
                "{}",
                key.key()
            );
        }

        // Left out and `null` read alike, as a file that omits the key.
        let omitted = StatedTransport::default();
        assert!(!omitted.states(interests) && !omitted.null_left_out(interests));
        assert_eq!(
            omitted.runs(interests, &defaults),
            r.runs(interests, &defaults)
        );
    }

    /// A router's timestamping read at its mode (v2 §2.19, core §4.1):
    /// a boolean whatever the mode, a value per mode, or zenoh 1.10.1's
    /// default where neither is stated, on for a router only; no mode is
    /// zenohd's `router`.
    #[test]
    fn a_routers_timestamping_is_read_at_its_mode() {
        let stamps = |mode: Option<&str>, enabled: Option<Value>| {
            let mut m = BTreeMap::new();
            if let Some(mode) = mode {
                m.insert("mode".to_owned(), Value::from(mode));
            }
            if let Some(e) = enabled {
                m.insert("timestamping/enabled".to_owned(), e);
            }
            StatedTransport(m).stamps()
        };
        assert!(stamps(None, None), "zenohd's router stamps by default");
        assert!(stamps(Some("router"), None));
        assert!(!stamps(Some("peer"), None));
        assert!(!stamps(Some("client"), None));
        assert!(stamps(Some("peer"), Some(Value::from(true))));
        assert!(!stamps(Some("router"), Some(Value::from(false))));
        let off = serde_json::json!({"router": false, "peer": false});
        assert!(!stamps(None, Some(off.clone())));
        assert!(!stamps(Some("peer"), Some(off)));
        // A per-mode value that leaves the router's mode out is its default.
        assert!(stamps(
            Some("router"),
            Some(serde_json::json!({"peer": false}))
        ));
        assert!(stamps(
            Some("peer"),
            Some(serde_json::json!({"peer": true}))
        ));
        // The generator's posture, read back: a router that stamps nothing.
        let written = StatedTransport::read(&serde_json::json!({
            "mode": "router",
            "timestamping": {"enabled": {"router": false, "peer": false}},
        }));
        assert!(!written.stamps());
        assert_eq!(TIMESTAMPING_OFF.len(), 2);
        // Both its paths, each off, whatever the order.
        for path in ["timestamping/enabled/router", "timestamping/enabled/peer"] {
            assert!(
                TIMESTAMPING_OFF.contains(&(path, false)),
                "{path} in {TIMESTAMPING_OFF:?}"
            );
        }
        // A `null`, as zenoh reads it: left out, at the mode's default.
        assert!(stamps(Some("router"), Some(serde_json::Value::Null)));
        assert!(stamps(
            Some("router"),
            Some(serde_json::json!({"router": null, "peer": false}))
        ));
        assert!(!stamps(
            Some("peer"),
            Some(serde_json::json!({"router": false, "peer": null}))
        ));
        let null_mode = StatedTransport::read(&serde_json::json!({
            "mode": null,
            "timestamping": {"enabled": {"peer": false}},
        }));
        assert!(null_mode.stamps(), "a `null` mode runs as a router");
        // A `mode` zenoh refuses, a string that is none of its three or no
        // string, reads as `router` too (link.v2 0.22 §2.19): never a mode
        // of its own, off by default and with no entry per mode.
        for refused in [
            serde_json::json!("bogus"),
            serde_json::json!("Router"),
            serde_json::json!(5),
        ] {
            let read = |enabled: Option<Value>| {
                let mut m = BTreeMap::from([("mode".to_owned(), refused.clone())]);
                if let Some(e) = enabled {
                    m.insert("timestamping/enabled".to_owned(), e);
                }
                StatedTransport(m).stamps()
            };
            assert!(read(None), "{refused}: a router's default, on");
            assert!(
                read(Some(serde_json::json!({"peer": false}))),
                "{refused}: the router's value left out"
            );
            assert!(
                !read(Some(serde_json::json!({"router": false, "peer": false}))),
                "{refused}: off at the mode read"
            );
            assert!(!read(Some(Value::from(false))), "{refused}");
            // Its own name is no mode `timestamping/enabled` is read at.
            assert!(
                read(Some(serde_json::json!({"bogus": false, "5": false}))),
                "{refused}"
            );
        }
    }

    /// The keep-alive interval in words: exact, or "about" where the lease
    /// is no multiple of `keep_alive`.
    #[test]
    fn the_keep_alive_interval_says_when_it_rounds() {
        let t = |lease_ms, keep_alive| Transport {
            lease_ms,
            keep_alive,
            ..Binding::Zenoh1_10_1.defaults()
        };
        assert_eq!(t(240_000, 4).keep_alive_interval_words(), "60000 ms");
        assert_eq!(t(2_000, 3).keep_alive_interval_words(), "about 666 ms");
    }

    /// A put's allowance is the bound measured on rf0's face (link.v1 §2.8,
    /// #1136; `docs/zk2/measurements/wire-baseline/results/bound-*`): on
    /// `unixsock-stream` at a 222-byte batch, the largest payload in one
    /// batch at 16 and 32 bits, by QoS, and one byte more fragmented.
    #[test]
    fn a_puts_allowance_is_the_measured_bound() {
        let lane = ["unixsock-stream".to_owned()];
        let block = PutQos {
            block: true,
            ..PutQos::DATA_DROP
        };
        let express = PutQos {
            express: true,
            ..PutQos::DATA_DROP
        };
        let low = PutQos {
            priority_data: false,
            ..PutQos::DATA_DROP
        };
        for (qos, bit16, bit32) in [
            (PutQos::DATA_DROP, 212, 210),
            (block, 210, 208),
            (express, 210, 208),
            (low, 208, 206),
        ] {
            for (sequence, largest) in [(Sequence::Bit16, bit16), (Sequence::Bit32, bit32)] {
                assert!(
                    fits_batch(largest, 222, qos, sequence, &lane),
                    "{qos:?} {sequence:?}"
                );
                assert!(!fits_batch(largest + 1, 222, qos, sequence, &lane));
            }
        }
        // A payload under 128 bytes has a 1-byte length; a datagram link
        // spends nothing on the batch's length; 8 and 64 bits.
        assert_eq!(allowance(100, PutQos::DATA_DROP, Sequence::Bit16, &lane), 9);
        assert_eq!(
            allowance(16_384, PutQos::DATA_DROP, Sequence::Bit16, &lane),
            11
        );
        let serial = ["serial".to_owned(), "ws".to_owned()];
        assert_eq!(
            allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &serial),
            8
        );
        let mixed = ["serial".to_owned(), "udp".to_owned()];
        assert_eq!(
            allowance(200, PutQos::DATA_DROP, Sequence::Bit16, &mixed),
            10
        );
        assert_eq!(allowance(200, PutQos::DATA_DROP, Sequence::Bit8, &lane), 9);
        assert_eq!(
            allowance(200, PutQos::DATA_DROP, Sequence::Bit64, &lane),
            13
        );
    }

    /// The window and the handshake's air (v2 §2.16): RF's 324 full
    /// batches a lease fit 16 bits' window and not 8 bits'.
    #[test]
    fn the_sequence_window_and_the_handshake_are_integer_arithmetic() {
        assert!(!window_filled(Sequence::Bit16, 222, 240_000, 2_400));
        assert!(window_filled(Sequence::Bit8, 222, 240_000, 2_400));
        assert!(under_handshake(10_000, 293));
        assert!(!under_handshake(40_000, 293));
        assert!(!under_handshake(2_560, 2_400));
        assert!(under_handshake(2_559, 2_400));
        assert!(!reply_short(15_000, 2_400, 222));
        assert!(reply_short(11_000, 2_400, 222));
    }

    /// An empty `link_protocols`, which zenoh 1.10.1 refuses to load, is
    /// read as absent: the subject selects every link protocol (§2.15,
    /// 0.4).
    #[test]
    fn an_empty_link_protocol_list_reads_as_absent() {
        let radio = face("ground", &["unixsock-stream"]);
        let block = |links: Option<Vec<String>>| BlockSubjects {
            posture: Posture::Deny,
            subjects: vec![BlockSubject {
                id: "local".into(),
                usernames: vec!["local".into()],
                link_protocols: links,
                ..BlockSubject::default()
            }],
            policies: vec![BlockPolicy {
                subjects: vec!["local".into()],
            }],
        };
        let found = |links| check_subjects("radio", &radio, &block(links));
        assert_eq!(found(Some(Vec::new())), found(None));
        assert_eq!(found(None).len(), 1);
    }

    #[test]
    fn the_batch_against_the_lease_is_integer_arithmetic() {
        assert!(within_lease(1000, 2400, 10_000));
        assert!(!within_lease(1024, 2400, 10_000));
        assert!(within_lease(65_535, MAX_U32, MAX_U32));
    }

    /// The far side of a link.v2 face (v2 §2.20, §2.21): its reply timeout
    /// raises a shorter one, never a longer one; a face without ARQ
    /// re-declares; its session runs the eight `[transport]` keys; a
    /// `link.v1` policy and a face the policy does not name are refused.
    #[test]
    fn a_far_side_reads_its_face_of_a_link_v2_policy() {
        use std::time::Duration;
        let text = "profile = \"link.v2\"\nsystem = \"lab\"\nservices = []\n\
                    binding = \"zenoh-1.10.1\"\n\
                    [transport]\nlease_ms = 240000\nkeep_alive = 4\n\
                    wait_before_close_ms = 240000\nsequence = \"16bit\"\nbatch_bytes = 222\n\
                    [face.rf]\nfar = \"ground\"\nattach = \"client\"\n\
                    select = { link_protocols = [\"unixsock-stream\"] }\n\
                    class = \"constrained\"\nexpose = \"none\"\nmax_outage_s = 3600\n\
                    link_bps = 2400\nloss_ppm = 50000\narq = false\nreply_timeout_ms = 15000\n";
        let parsed = parse(text);
        let policy = parsed.policy.expect("a policy");
        let far = policy.far_side("rf").expect("its face");
        assert_eq!(far.reply_timeout(), Duration::from_secs(15));
        assert_eq!(
            far.at_least(Duration::from_secs(1)),
            Duration::from_secs(15)
        );
        assert_eq!(
            far.at_least(Duration::from_secs(30)),
            Duration::from_secs(30)
        );
        assert!(
            far.redeclares(),
            "no ARQ: a silent subscription is declared again"
        );
        assert_eq!(
            FarSide::silence(Duration::from_secs(300)),
            Duration::from_secs(600)
        );
        let keys = far.session_keys();
        assert_eq!(keys.len(), 8);
        assert_eq!(
            keys[2],
            (TransportKey::WaitBeforeClose, Value::from(240_000_000u64)),
            "wait_before_close in µs"
        );
        assert!(matches!(
            policy.far_side("sbd"),
            Err(FarSideRefusal::NoFace { faces, .. }) if faces == ["rf"]
        ));
        let v1 = FacePolicy {
            profile: Profile::V1,
            transport: None,
            ..policy
        };
        assert_eq!(v1.far_side("rf"), Err(FarSideRefusal::NotV2));
    }
}