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
//! `desired.v1`: desired documents, from their author to their target
//! (`spec/profiles/desired/v1.md`, #840).
//!
//! The profile's session-free half: the declaration read from a resolved
//! resource (§2.2), a requirement's binding and its slice's key (§2.3), a
//! stamp as a report writes it (§2.4), the standard `Report` with its
//! reading and its consistency (§2.10), a target's state machine (§2.6 to
//! §2.10), pure and two-phase like [`crate::config::Owner`], and §5's four
//! questions as judgements in three states (§2.17).
//!
//! ```text
//! declaration(kind, template, annotations) ─▶ declared [targets] │ invalid [reasons] │ not this profile's   §2.2
//! binding(slice, requirement, own address) ─▶ bound {key} │ unbound (the kill switch) │ invalid [problems] §2.3
//! parse_stamp(text) / Stamp's Display       ─▶ <time>/<id>, as zenoh writes a timestamp                    §2.4
//! decode(bytes), Report::from_json(v)       ─▶ Report │ Unreadable{json, schema, stamp, revision_range}    §2.10
//! Report::check()                           ─▶ the findings: keyless, key_form, observed_outcome, …        §2.10
//! Content::of_payload(bytes, json)          ─▶ a put's document, JCS-equal by exact value for JSON, else byte-equal  §2.7
//! revision_of_text(bytes) / revision_of_value(v) ─▶ a document's own revision, by its exact value          §2.4
//! Target::observe(sample)                   ─▶ act │ revert │ adopted │ held │ unstamped │ same_version │ older │ confirmed  §2.6–§2.9
//!   against the version held, every id remembered (16), then the one held waiting while an act runs
//! Target::finish(ended)                     ─▶ the report updated; done, or the held version adopted or acted on  §2.7, §2.10
//! Target::call()                            ─▶ source call                                                 §2.7
//! converged(target, author)                 ─▶ §5 "has the target converged on its author's current document?"
//! refused(target) / last_known(target) / in_force(target) ─▶ §5's other three questions              §2.17
//! ```
//!
//! There is no I/O and no clock here. A target's runtime subscribes, seeds
//! and reads an archive (§2.5, §2.9), hands each sample to
//! [`Target::observe`] as it arrives, performs each [`Act`] on its own
//! application (decode, check, apply or revert), tells
//! [`Target::finish`] how it ended, and puts [`Target::report`] whenever it
//! changes (§2.10). An author's writes, its diff and its record (§2.11) are
//! the runtime's.
//!
//! [`v2`] is `desired.v2`'s half (`spec/profiles/desired/v2.md`, #986),
//! which restates this major by reference. What the two share is here, one
//! copy of each rule: the state machine (`machine`, a version ordered by
//! a tick within an epoch, v1's time within an id and v2's seq within a
//! run), and §5's judges, which read a report of either major through
//! [`Reported`].

use std::collections::BTreeMap;
use std::fmt;

use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::authoring::{Kind, ParamType};
use crate::contract::Resource;
use crate::freshness;
use crate::grammar::{self, Addr, IfaceId, Key, KindToken, ZkKey};
use crate::seed::Stamp;
use crate::template::{Bindings, Template};

pub mod v2;

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

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

/// `desired.target_param` (§4).
pub const TARGET_PARAM: &str = "desired.target_param";

/// The published vocabulary (§4): the keys under `desired.`, which W105
/// reads in place of core Appendix D's interim row (core 0.36). The interim
/// `target` is retired, so W105 warns of it.
pub const VOCABULARY: &[&str] = &["target_param"];

/// The standard schema's stem (§3): `desired.v1.json`.
pub const SCHEMA_STEM: &str = "desired.v1";
/// The report's type name (§2.10, §3).
pub const REPORT: &str = "desired.v1.Report";
/// A version's type name (§2.4, §3).
pub const VERSION: &str = "desired.v1.Version";
/// A refusal's type name (§2.10, §3).
pub const REFUSAL: &str = "desired.v1.Refusal";

/// The standard schema's artifact ids the profile publishes (§3), oldest
/// first: text 0.1's, then text 0.2's, whose descriptions say "acted on or
/// adopted" (F-173). A type of one of these artifacts is the profile's.
pub const PUBLISHED: &[&str] = &[
    "sha256:8c5ffce35fadeb6196233a46e163ee3b15cbd2bd8339a05de2cf8fe22b52e9ef",
    "sha256:43c952598f454ec903dba63bad36419f5dcff3312db727bd4e58a88dc1ca55ae",
];

/// Whether `id` is one of the standard schema's published artifact ids.
#[must_use]
pub fn is_published(id: &str) -> bool {
    PUBLISHED.contains(&id)
}

/// R2's spelling of the target's own system (core §3.2).
pub const SELF_SYSTEM: &str = "self.system";
/// R2's spelling of the target's own service (core §3.2).
pub const SELF_SERVICE: &str = "self.service";

/// The longest refusal code, in characters (§3).
pub const MAX_CODE: usize = 64;

/// The profile's refusal codes (§2.7, §2.10): the document does not decode
/// as its type.
pub const UNDECODABLE: &str = "undecodable";
/// It names what the target needs to reach the bus.
pub const REACH: &str = "reach";
/// It carries a sensitive value: a secret, a credential, a key
/// (`config.v1`'s word).
pub const SENSITIVE: &str = "sensitive";
/// Its type, or the target's own validation of it, refuses it.
pub const INVALID: &str = "invalid";
/// An act that could not finish.
pub const APPLY: &str = "apply";

// --- §2.2: the declaration -----------------------------------------------------

/// Which identity of the target fills a target parameter (§2.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Binds {
    /// The one target parameter: `self.system` or `self.service`, as the
    /// deployment chooses.
    Either,
    /// The first of two: `self.system`.
    System,
    /// The second of two: `self.service`.
    Service,
}

impl Binds {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Either => "either",
            Self::System => SELF_SYSTEM,
            Self::Service => SELF_SERVICE,
        }
    }

    /// Whether a parameter binding spelled `bound` (core R2) is this one.
    #[must_use]
    pub fn admits(self, bound: &str) -> bool {
        match self {
            Self::Either => bound == SELF_SYSTEM || bound == SELF_SERVICE,
            Self::System => bound == SELF_SYSTEM,
            Self::Service => bound == SELF_SERVICE,
        }
    }
}

/// One target parameter (§2.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TargetParam {
    pub param: String,
    pub binds: Binds,
}

/// Why a declaration is invalid (§2.2), in the order checked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Invalid {
    /// The resource is not state.
    NotState,
    /// Not a string, nor an array of one or two strings.
    Value,
    /// A name twice.
    Repeated,
    /// A name that is no parameter of the template.
    NotAParam,
    /// A name of a rest parameter.
    RestParam,
    /// A template parameter the value does not name.
    ParamNotTarget,
    /// A target parameter, not a rest one, whose type is not `string`
    /// (text 0.2, F-170).
    NotString,
    /// `desired.v2` §2.2 alone, checked last: a horizon above 0 in a
    /// contract that does not use `freshness.v2` ([`v2::declaration`]).
    /// [`declaration`], `desired.v1`'s reading, never gives it.
    HorizonV1,
}

impl Invalid {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotState => "not_state",
            Self::Value => "value",
            Self::Repeated => "repeated",
            Self::NotAParam => "not_a_param",
            Self::RestParam => "rest_param",
            Self::ParamNotTarget => "param_not_target",
            Self::NotString => "not_string",
            Self::HorizonV1 => "horizon_v1",
        }
    }

    /// What it says, for a linter's line.
    #[must_use]
    pub fn says(self) -> &'static str {
        match self {
            Self::NotState => "a desired document is state of its author",
            Self::Value => "desired.target_param is a string, or an array of one or two strings",
            Self::Repeated => "a target parameter is named twice",
            Self::NotAParam => "a name is no parameter of the template",
            Self::RestParam => "a rest parameter cannot be a target parameter",
            Self::ParamNotTarget => {
                "every template parameter must be a target parameter: one document per target"
            }
            Self::NotString => "a target parameter holds a system or a service name, a string",
            Self::HorizonV1 => {
                "a horizon above 0 is confirmed by a heartbeat: the contract must use freshness.v2"
            }
        }
    }
}

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

/// A resource's declaration (§2.2).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Declaration {
    /// No `desired.target_param`.
    NotThisProfiles,
    /// The reasons, in the order checked.
    Invalid(Vec<Invalid>),
    /// The target parameters, in the value's order.
    Declared(Vec<TargetParam>),
}

impl Declaration {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NotThisProfiles => "not_this_profiles",
            Self::Invalid(_) => "invalid",
            Self::Declared(_) => "declared",
        }
    }

    /// The target parameters of a valid declaration.
    #[must_use]
    pub fn targets(&self) -> Option<&[TargetParam]> {
        match self {
            Self::Declared(t) => Some(t),
            _ => None,
        }
    }
}

/// Reads the declaration of a resource of `kind`, `template` and parameter
/// types `params` (core §2.2) from its resolved annotations (§2.2, core
/// §9.3). Each check runs alone, and a check that needs a value an earlier
/// one found wrong is skipped: `not_string` reads the type of a name that
/// is a parameter and not a rest one, and a parameter `params` does not
/// list (core E011's) is no finding here. A horizon, whatever its value,
/// makes no declaration invalid: its re-puts are the same document, which
/// a target adopts (§2.7).
#[must_use]
pub fn declaration(
    kind: Kind,
    template: &Template,
    params: &BTreeMap<String, ParamType>,
    annotations: &BTreeMap<String, Value>,
) -> Declaration {
    let Some(v) = annotations.get(TARGET_PARAM) else {
        return Declaration::NotThisProfiles;
    };
    let typed = params;
    let params: Vec<(&str, bool)> = template.params().collect();
    let mut why = Vec::new();
    if kind != Kind::State {
        why.push(Invalid::NotState);
    }
    let names: Option<Vec<&str>> = match v {
        Value::String(s) => Some(vec![s.as_str()]),
        Value::Array(a) if (1..=2).contains(&a.len()) => {
            a.iter().map(Value::as_str).collect::<Option<Vec<_>>>()
        }
        _ => None,
    };
    match &names {
        None => why.push(Invalid::Value),
        Some(names) => {
            if names.len() == 2 && names[0] == names[1] {
                why.push(Invalid::Repeated);
            }
            if names.iter().any(|n| !params.iter().any(|(p, _)| p == n)) {
                why.push(Invalid::NotAParam);
            }
            if names
                .iter()
                .any(|n| params.iter().any(|(p, rest)| *rest && p == n))
            {
                why.push(Invalid::RestParam);
            }
            if params.iter().any(|(p, _)| !names.contains(p)) {
                why.push(Invalid::ParamNotTarget);
            }
            // A system or a service name is a string (0.2, F-170). A rest
            // parameter is `path` (core §2.2), and `rest_param`'s alone.
            if names.iter().any(|n| {
                params.iter().any(|(p, rest)| !*rest && p == n)
                    && typed.get(*n).is_some_and(|t| *t != ParamType::String)
            }) {
                why.push(Invalid::NotString);
            }
        }
    }
    match names {
        Some(names) if why.is_empty() => Declaration::Declared(match names.as_slice() {
            [one] => vec![TargetParam {
                param: (*one).to_owned(),
                binds: Binds::Either,
            }],
            [first, second] => vec![
                TargetParam {
                    param: (*first).to_owned(),
                    binds: Binds::System,
                },
                TargetParam {
                    param: (*second).to_owned(),
                    binds: Binds::Service,
                },
            ],
            // One or two names, by the match above.
            _ => return Declaration::Invalid(vec![Invalid::Value]),
        }),
        _ => Declaration::Invalid(why),
    }
}

/// [`declaration`] of a resource of a contract.
#[must_use]
pub fn declaration_of(r: &Resource) -> Declaration {
    declaration(r.kind, &r.template, &r.params, &r.annotations)
}

// --- §2.3: the binding ---------------------------------------------------------

/// A target's requirement on a desired resource, as its descriptor lists it
/// (core §3.3).
#[derive(Debug, Clone, Copy)]
pub struct Requirement<'a> {
    /// The provider addresses, `<system>/<service>`, a chunk possibly `*`.
    pub bindings: &'a [String],
    /// The parameter bindings, as configured (core R2, R3).
    pub params: &'a BTreeMap<String, String>,
    /// Whether the role is optional (core §3.1).
    pub optional: bool,
    /// How many desired resources of the author's declaration the
    /// requirement names (text 0.6, F-218): one for a requirement §2.1
    /// allows, one role per document type; two or more is
    /// [`BindingProblem::TwoDocuments`].
    pub documents: usize,
}

/// The desired resource a requirement binds (§2.3): its interface, kind
/// token, template and target parameters.
#[derive(Debug, Clone, Copy)]
pub struct Slice<'a> {
    pub iface: &'a IfaceId,
    pub token: KindToken,
    pub template: &'a Template,
    pub targets: &'a [TargetParam],
}

/// Why a binding is invalid (§2.3), in the order checked.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BindingProblem {
    /// No binding, and the role is required.
    RequiredUnbound,
    /// The requirement names two or more desired resources of the author's
    /// declaration (text 0.6, F-218): one role per document type (§2.1),
    /// so there is no one slice to bind. Checked alone.
    TwoDocuments,
    /// More than one binding, or one with `*`, or one that is no address.
    NotOneAuthor,
    /// A target parameter `params` does not bind.
    TargetUnbound,
    /// A target parameter bound to anything but `self.system` or
    /// `self.service`.
    NotSelf,
    /// Of two target parameters, one bound to the other's self.
    WrongSelf,
}

impl BindingProblem {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::RequiredUnbound => "required_unbound",
            Self::TwoDocuments => "two_documents",
            Self::NotOneAuthor => "not_one_author",
            Self::TargetUnbound => "target_unbound",
            Self::NotSelf => "not_self",
            Self::WrongSelf => "wrong_self",
        }
    }
}

/// A requirement's binding (§2.3).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Binding {
    /// No binding, an optional role: the kill switch (§2.12).
    Unbound,
    /// The problems, in the order checked.
    Invalid(Vec<BindingProblem>),
    /// The target's slice: its one document's key.
    Bound { key: Key },
}

impl Binding {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Unbound => "unbound",
            Self::Invalid(_) => "invalid",
            Self::Bound { .. } => "bound",
        }
    }
}

/// The one author a binding names: an exact address, or `None`.
fn one_author(bindings: &[String]) -> Option<Addr> {
    let [one] = bindings else {
        return None;
    };
    if one.split('/').any(|c| c == "*") {
        return None;
    }
    one.parse().ok()
}

/// Reads a target's requirement on a desired resource (§2.3): the kill
/// switch, a binding's problems, or the target's slice, built from the
/// author's address and the target's own address `own`, each target
/// parameter's value the target's system or service as its binding says,
/// slugged (core §1.4). The problems in §2.3's order: `required_unbound`
/// alone; `two_documents` alone (text 0.6); then `not_one_author`,
/// `target_unbound`, `not_self` and `wrong_self`, each that applies.
#[must_use]
pub fn binding(slice: &Slice<'_>, req: &Requirement<'_>, own: &Addr) -> Binding {
    if req.bindings.is_empty() {
        return if req.optional {
            Binding::Unbound
        } else {
            Binding::Invalid(vec![BindingProblem::RequiredUnbound])
        };
    }
    // One role per document type (§2.1; text 0.6, F-218): checked after
    // the binding's absence, which reads nothing, and alone, since every
    // check after it binds the one slice there is not.
    if req.documents > 1 {
        return Binding::Invalid(vec![BindingProblem::TwoDocuments]);
    }
    let mut why = Vec::new();
    let author = one_author(req.bindings);
    if author.is_none() {
        why.push(BindingProblem::NotOneAuthor);
    }
    let bound = |t: &TargetParam| req.params.get(&t.param).map(String::as_str);
    if slice.targets.iter().any(|t| bound(t).is_none()) {
        why.push(BindingProblem::TargetUnbound);
    }
    if slice
        .targets
        .iter()
        .filter_map(bound)
        .any(|b| b != SELF_SYSTEM && b != SELF_SERVICE)
    {
        why.push(BindingProblem::NotSelf);
    }
    if slice.targets.iter().any(|t| {
        bound(t).is_some_and(|b| (b == SELF_SYSTEM || b == SELF_SERVICE) && !t.binds.admits(b))
    }) {
        why.push(BindingProblem::WrongSelf);
    }
    let Some(author) = author.filter(|_| why.is_empty()) else {
        return Binding::Invalid(why);
    };
    let mut values = Bindings::new();
    for t in slice.targets {
        let v = if bound(t) == Some(SELF_SYSTEM) {
            own.system.as_str()
        } else {
            own.service.as_str()
        };
        values.insert(t.param.clone(), vec![v.to_owned()]);
    }
    let built = slice.template.build(&values).ok().and_then(|chunks| {
        let refs: Vec<&str> = chunks.iter().map(String::as_str).collect();
        grammar::data_key(&author, slice.iface, slice.token, &refs).ok()
    });
    match built {
        Some(key) => Binding::Bound { key },
        // Every target parameter bound, every chunk a slug: only a template
        // that is no desired one's reaches here.
        None => Binding::Invalid(vec![BindingProblem::TargetUnbound]),
    }
}

// --- §2.4: stamps ----------------------------------------------------------------

/// Reads a stamp as a report writes it (§2.4): the NTP64 time in decimal,
/// `0` or without a leading zero, at most 2^64−1; `/`; the id in lowercase
/// hexadecimal without a leading zero, at most 32 digits. `None` for any
/// other spelling. [`Stamp`]'s `Display` writes this form.
#[must_use]
pub fn parse_stamp(s: &str) -> Option<Stamp> {
    let (time, id) = s.split_once('/')?;
    let digits = !time.is_empty() && time.bytes().all(|b| b.is_ascii_digit());
    if !digits || (time.len() > 1 && time.starts_with('0')) {
        return None;
    }
    Stamp::parse(time.parse().ok()?, id)
}

/// A stamp written as a string (§2.4).
mod stamp_text {
    use serde::{Deserialize, Deserializer, Serializer};

    use super::{Stamp, parse_stamp};

    pub fn serialize<S: Serializer>(s: &Stamp, ser: S) -> Result<S::Ok, S::Error> {
        ser.collect_str(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Stamp, D::Error> {
        let s = String::deserialize(de)?;
        parse_stamp(&s).ok_or_else(|| serde::de::Error::custom(format!("{s:?} is no stamp")))
    }
}

// --- §2.10: the report -----------------------------------------------------------

/// What is in force (§2.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Source {
    /// The target's own configuration, with no document.
    Baseline,
    /// A document the target acted on.
    Desired,
    /// A change the target's own operation made since.
    Call,
}

impl Source {
    /// The wire's and the fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Baseline => "baseline",
            Self::Desired => "desired",
            Self::Call => "call",
        }
    }

    fn parse(s: &str) -> Option<Self> {
        [Self::Baseline, Self::Desired, Self::Call]
            .into_iter()
            .find(|v| v.as_str() == s)
    }
}

/// What the last act did (§2.7, §2.8, §2.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Outcome {
    /// Applied whole.
    Converged,
    /// Nothing applied; what was in force kept.
    Refused,
    /// Applied in part.
    Failed,
    /// A delete acted on, the baseline back in force.
    Reverted,
}

impl Outcome {
    /// The wire's and the fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Converged => "converged",
            Self::Refused => "refused",
            Self::Failed => "failed",
            Self::Reverted => "reverted",
        }
    }

    fn parse(s: &str) -> Option<Self> {
        [Self::Converged, Self::Refused, Self::Failed, Self::Reverted]
            .into_iter()
            .find(|v| v.as_str() == s)
    }
}

/// One version of a document (§2.4): `desired.v1.Version`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Version {
    #[serde(with = "stamp_text")]
    pub stamp: Stamp,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<u64>,
}

/// Why a document was refused, or failed to apply (§2.10):
/// `desired.v1.Refusal`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Refusal {
    /// The profile's code ([`UNDECODABLE`], [`REACH`], [`SENSITIVE`],
    /// [`INVALID`], [`APPLY`]) or the type's own, 1 to 64 characters.
    pub code: String,
    /// Where in the document, a JSON Pointer (RFC 6901).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pointer: Option<String>,
    /// A line for a person.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

impl Refusal {
    /// A refusal with a code alone.
    #[must_use]
    pub fn new(code: impl Into<String>) -> Self {
        Self {
            code: code.into(),
            pointer: None,
            detail: None,
        }
    }
}

/// A target's report of one role (§2.10): `desired.v1.Report`. Its members
/// serialize as the schema names them, an absent one left out.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Report {
    /// The slice's key, absent only for an unbound role (§2.12).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub key: Option<String>,
    pub source: Source,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub in_force: Option<Version>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observed: Option<Version>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub outcome: Option<Outcome>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refusal: Option<Refusal>,
    /// `true` when `observed` was read from an archive (§2.9).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub last_known: bool,
}

/// Why a report does not read (§2.10): the first refusal only.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unreadable {
    /// Bytes that are not strict JSON.
    Json(String),
    /// Outside `desired.v1.Report`.
    Schema(String),
    /// A stamp not in zenoh's form (§2.4).
    Stamp(String),
    /// A revision above 2^64−1.
    RevisionRange(&'static str),
}

impl Unreadable {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Json(_) => "json",
            Self::Schema(_) => "schema",
            Self::Stamp(_) => "stamp",
            Self::RevisionRange(_) => "revision_range",
        }
    }
}

impl fmt::Display for Unreadable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Json(e) => write!(f, "not strict JSON: {e}"),
            Self::Schema(e) => write!(f, "not a desired.v1.Report: {e}"),
            Self::Stamp(s) => write!(f, "{s:?} is not a stamp as zenoh writes one"),
            Self::RevisionRange(m) => write!(f, "/{m}/revision is above 2^64-1"),
        }
    }
}

/// A report that reads, but breaks §2.10's consistency, of either major:
/// [`Report::check`] gives `desired.v1`'s eight, [`v2::Fields::check`]
/// `desired.v2`'s eight.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Finding {
    /// `desired.v2` alone: `source` or `outcome` is a later text's value.
    Escape,
    /// `desired.v2` alone: a version's fields do not hold together.
    RunFields,
    /// `desired.v1` alone: no key, and more than the baseline.
    Keyless,
    /// `desired.v1` alone: a key that is no state key.
    KeyForm,
    ObservedOutcome,
    Refusal,
    Source,
    InForce,
    RevisionOnRevert,
    LastKnown,
}

impl Finding {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Escape => "escape",
            Self::RunFields => "run_fields",
            Self::Keyless => "keyless",
            Self::KeyForm => "key_form",
            Self::ObservedOutcome => "observed_outcome",
            Self::Refusal => "refusal",
            Self::Source => "source",
            Self::InForce => "in_force",
            Self::RevisionOnRevert => "revision_on_revert",
            Self::LastKnown => "last_known",
        }
    }
}

/// A revision as the schema reads it: an integer from 0, an integral float
/// that integer; whether it fits 64 bits is checked after the stamps.
enum RevisionRead {
    InRange(u64),
    TooLarge,
}

/// A revision read from its number's exact value (text 0.3, F-181), as
/// [`exact_number`] writes it: an integer from 0, whatever its spelling
/// (`3`, `3.0`, `30e-1`, `18446744073709551615.0`), in range up to 2^64−1;
/// `None` for a negative number or one with a fraction (`1.5`).
fn exact_revision(canonical: &str) -> Option<RevisionRead> {
    if canonical == "0" {
        return Some(RevisionRead::InRange(0));
    }
    if canonical.starts_with('-') {
        return None;
    }
    let (digits, exp) = canonical.split_once('e')?;
    let exp: i128 = exp.parse().ok()?;
    // The significant digits keep no trailing zero, so a negative exponent
    // is a fraction.
    if exp < 0 {
        return None;
    }
    // A positive exponent is an integer, however large: past `usize` it is
    // far past 2^64−1. (Such a number is never finite, so strict JSON
    // refuses its text first, §2.10; this reads it as its text says.)
    let Ok(zeros) = usize::try_from(exp) else {
        return Some(RevisionRead::TooLarge);
    };
    // 2^64−1 has 20 digits.
    if digits.len().saturating_add(zeros) > 20 {
        return Some(RevisionRead::TooLarge);
    }
    let text = format!("{digits}{}", "0".repeat(zeros));
    Some(
        text.parse::<u64>()
            .map_or(RevisionRead::TooLarge, RevisionRead::InRange),
    )
}

/// A document's own revision (§2.4): a top-level member `revision` of a
/// JSON payload, an integer from 0 to 2^64−1 read by its exact value
/// (F-181), as a report's is. `None` when the payload is not strict JSON
/// (§2.10's reading), is not an object, has no such member, or holds one
/// that is no such integer.
#[must_use]
pub fn revision_of_text(bytes: &[u8]) -> Option<u64> {
    let text = std::str::from_utf8(bytes).ok()?;
    match Exact::of_strict_text(text)? {
        Exact::Object(m) => match m.get("revision")? {
            Exact::Number(n) => match exact_revision(n)? {
                RevisionRead::InRange(r) => Some(r),
                RevisionRead::TooLarge => None,
            },
            _ => None,
        },
        _ => None,
    }
}

/// A document's own revision from its decoded value (§2.4): a top-level
/// member `revision`, an integer from 0 to 2^64−1, an integral number read
/// as that integer, or a decimal string, as protobuf's JSON mapping writes a
/// 64-bit field. A JSON payload's is read from its text instead
/// ([`revision_of_text`]), every number exact.
#[must_use]
pub fn revision_of_value(v: &Value) -> Option<u64> {
    match v.get("revision")? {
        Value::String(s) if !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) => {
            s.parse().ok()
        }
        r => match revision(r)? {
            RevisionRead::InRange(n) => Some(n),
            RevisionRead::TooLarge => None,
        },
    }
}

fn revision(v: &Value) -> Option<RevisionRead> {
    let Value::Number(n) = v else {
        return None;
    };
    if let Some(u) = n.as_u64() {
        return Some(RevisionRead::InRange(u));
    }
    if n.as_i64().is_some() {
        return None; // negative
    }
    let f = n.as_f64()?;
    if !(f.is_finite() && f >= 0.0 && f.fract() == 0.0) {
        return None;
    }
    // 2^64, exactly a double.
    if f >= 2.0_f64.powi(64) {
        return Some(RevisionRead::TooLarge);
    }
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let n = f as u64;
    Some(RevisionRead::InRange(n))
}

/// A version's members, read by the schema's types.
struct RawVersion<'a> {
    stamp: &'a str,
    revision: Option<RevisionRead>,
}

/// `exact` is the version's object as [`Exact`] read it from the report's
/// text, when the reader had the text: its `revision` is then read by its
/// exact value (text 0.3, F-181), never as a double.
fn raw_version<'a>(
    v: &'a Value,
    member: &str,
    exact: Option<&Exact>,
) -> Result<RawVersion<'a>, Unreadable> {
    let schema = |why: &str| Unreadable::Schema(format!("/{member}{why}"));
    let Value::Object(o) = v else {
        return Err(schema(": not an object"));
    };
    let stamp = match o.get("stamp") {
        Some(Value::String(s)) if s.chars().count() >= 3 => s.as_str(),
        Some(Value::String(_)) => return Err(schema("/stamp: shorter than 3 characters")),
        Some(_) => return Err(schema("/stamp: not a string")),
        None => return Err(schema("/stamp: missing")),
    };
    let exact = match exact {
        Some(Exact::Object(m)) => match m.get("revision") {
            Some(Exact::Number(n)) => Some(n.as_str()),
            _ => None,
        },
        _ => None,
    };
    let revision = match (o.get("revision"), exact) {
        (None, _) => None,
        (Some(Value::Number(_)), Some(text)) => {
            Some(exact_revision(text).ok_or_else(|| schema("/revision: not an integer from 0"))?)
        }
        (Some(r), _) => {
            Some(revision(r).ok_or_else(|| schema("/revision: not an integer from 0"))?)
        }
    };
    Ok(RawVersion { stamp, revision })
}

fn optional_string(
    o: &serde_json::Map<String, Value>,
    m: &str,
    at: &str,
) -> Result<Option<String>, Unreadable> {
    match o.get(m) {
        None => Ok(None),
        Some(Value::String(s)) => Ok(Some(s.clone())),
        Some(_) => Err(Unreadable::Schema(format!("{at}/{m}: not a string"))),
    }
}

impl Report {
    /// A target's first report of a role (§2.10): its slice's key, or none
    /// for an unbound role, and the baseline in force.
    #[must_use]
    pub fn baseline(key: Option<String>) -> Self {
        Self {
            key,
            source: Source::Baseline,
            in_force: None,
            observed: None,
            outcome: None,
            refusal: None,
            last_known: false,
        }
    }

    /// Reads a decoded payload (§2.10): the schema's members, types and
    /// enums, an integral number read as an integer and a member the schema
    /// does not name ignored; then each stamp's form; then each revision's
    /// range. A decoded value holds a number with a fraction or an exponent
    /// as its double, so a revision past 2^53 written so is read as that
    /// double here; [`decode`] reads the text, every number by its exact
    /// value (text 0.3, F-181).
    ///
    /// # Errors
    ///
    /// [`Unreadable`]: the first refusal, in that order.
    pub fn from_json(v: &Value) -> Result<Self, Unreadable> {
        Self::read(v, None)
    }

    /// [`Report::from_json`], each revision read from `exact`, the report's
    /// text read with every number exact, when the reader has it
    /// ([`decode`]; text 0.3, F-181).
    fn read(v: &Value, exact: Option<&Exact>) -> Result<Self, Unreadable> {
        let schema = |why: String| Unreadable::Schema(why);
        let Value::Object(o) = v else {
            return Err(schema("not an object".into()));
        };
        let exact_of = |m: &str| match exact {
            Some(Exact::Object(e)) => e.get(m),
            _ => None,
        };
        let source = match o.get("source") {
            Some(Value::String(s)) => Source::parse(s),
            _ => None,
        }
        .ok_or_else(|| schema("/source: not baseline, desired or call".into()))?;
        let key = optional_string(o, "key", "")?;
        let in_force = o
            .get("in_force")
            .map(|v| raw_version(v, "in_force", exact_of("in_force")))
            .transpose()?;
        let observed = o
            .get("observed")
            .map(|v| raw_version(v, "observed", exact_of("observed")))
            .transpose()?;
        let outcome = match o.get("outcome") {
            None => None,
            Some(Value::String(s)) => Some(Outcome::parse(s).ok_or_else(|| {
                schema("/outcome: not converged, refused, failed or reverted".into())
            })?),
            Some(_) => return Err(schema("/outcome: not a string".into())),
        };
        let refusal = match o.get("refusal") {
            None => None,
            Some(Value::Object(r)) => {
                let code = match r.get("code") {
                    Some(Value::String(c)) if (1..=MAX_CODE).contains(&c.chars().count()) => {
                        c.clone()
                    }
                    Some(Value::String(_)) => {
                        return Err(schema("/refusal/code: not 1 to 64 characters".into()));
                    }
                    Some(_) => return Err(schema("/refusal/code: not a string".into())),
                    None => return Err(schema("/refusal/code: missing".into())),
                };
                Some(Refusal {
                    code,
                    pointer: optional_string(r, "pointer", "/refusal")?,
                    detail: optional_string(r, "detail", "/refusal")?,
                })
            }
            Some(_) => return Err(schema("/refusal: not an object".into())),
        };
        let last_known = match o.get("last_known") {
            None => false,
            Some(Value::Bool(b)) => *b,
            Some(_) => return Err(schema("/last_known: not a boolean".into())),
        };
        let stamp = |r: &RawVersion<'_>| {
            parse_stamp(r.stamp).ok_or_else(|| Unreadable::Stamp(r.stamp.to_owned()))
        };
        let in_force_stamp = in_force.as_ref().map(stamp).transpose()?;
        let observed_stamp = observed.as_ref().map(stamp).transpose()?;
        let rev = |r: &RawVersion<'_>, m: &'static str| match &r.revision {
            None => Ok(None),
            Some(RevisionRead::InRange(n)) => Ok(Some(*n)),
            Some(RevisionRead::TooLarge) => Err(Unreadable::RevisionRange(m)),
        };
        let in_force = match (&in_force, in_force_stamp) {
            (Some(r), Some(stamp)) => Some(Version {
                stamp,
                revision: rev(r, "in_force")?,
            }),
            _ => None,
        };
        let observed = match (&observed, observed_stamp) {
            (Some(r), Some(stamp)) => Some(Version {
                stamp,
                revision: rev(r, "observed")?,
            }),
            _ => None,
        };
        Ok(Self {
            key,
            source,
            in_force,
            observed,
            outcome,
            refusal,
            last_known,
        })
    }

    /// The report's findings (§2.10), every one that applies, in the order
    /// checked. A report with one is malformed, and answers nothing
    /// (§2.17).
    #[must_use]
    pub fn check(&self) -> Vec<Finding> {
        let mut out = Vec::new();
        if self.key.is_none() && (self.source != Source::Baseline || self.observed.is_some()) {
            out.push(Finding::Keyless);
        }
        if let Some(k) = &self.key
            && !matches!(
                grammar::parse(k),
                Ok(ZkKey::Data {
                    kind: KindToken::State | KindToken::ExplicitState,
                    ..
                })
            )
        {
            out.push(Finding::KeyForm);
        }
        if self.observed.is_some() != self.outcome.is_some() {
            out.push(Finding::ObservedOutcome);
        }
        let refusing = matches!(self.outcome, Some(Outcome::Refused | Outcome::Failed));
        if self.refusal.is_some() != refusing {
            out.push(Finding::Refusal);
        }
        if (self.source == Source::Desired && self.observed.is_none())
            || (self.outcome == Some(Outcome::Converged) && self.source == Source::Baseline)
            || (self.outcome == Some(Outcome::Reverted) && self.source == Source::Desired)
        {
            out.push(Finding::Source);
        }
        let misplaced = self.in_force.is_some()
            && (self.source != Source::Desired || self.outcome == Some(Outcome::Failed));
        let not_observed = self.outcome == Some(Outcome::Converged)
            && self.source == Source::Desired
            && self.in_force != self.observed;
        if misplaced || not_observed {
            out.push(Finding::InForce);
        }
        if self.outcome == Some(Outcome::Reverted)
            && self.observed.is_some_and(|o| o.revision.is_some())
        {
            out.push(Finding::RevisionOnRevert);
        }
        if self.last_known && self.observed.is_none() {
            out.push(Finding::LastKnown);
        }
        out
    }

    /// The report as JSON, as a target puts it.
    #[must_use]
    pub fn to_json(&self) -> Value {
        serde_json::to_value(self).unwrap_or(Value::Null)
    }
}

/// How deep a report or a document may nest (§2.10, text 0.2), counted as
/// `telemetry.v1` §2.6 counts it: an array or an object at the top is at
/// depth 1, one inside another one deeper, a scalar adding none.
pub const MAX_DEPTH: usize = crate::telemetry::decode::MAX_DEPTH;

/// One JSON text as strict JSON (§2.10): UTF-8, RFC 8259's grammar,
/// nothing after the value but whitespace, no duplicate member at any
/// depth, every string with a UTF-8 form, every number finite by rounding,
/// and at most [`MAX_DEPTH`] arrays and objects deep (text 0.2), read by
/// `telemetry.v1`'s strict reader, which stops at the same place. `None`
/// when the bytes are not one. An integer within 64 bits is held exactly;
/// any other number as its nearest double.
#[must_use]
pub fn strict_json(bytes: &[u8]) -> Option<Value> {
    fn value(d: &crate::telemetry::Datum) -> Option<Value> {
        use crate::telemetry::Datum as D;
        let float = |f: f64| serde_json::Number::from_f64(f).map(Value::Number);
        Some(match d {
            D::Null => Value::Null,
            D::Bool(b) => Value::Bool(*b),
            D::Int(i) => match (u64::try_from(*i), i64::try_from(*i)) {
                (Ok(u), _) => Value::from(u),
                (_, Ok(i)) => Value::from(i),
                // Beyond 64 bits, as `serde_json` reads one: its double.
                #[allow(clippy::cast_precision_loss)]
                _ => float(*i as f64)?,
            },
            D::BigInt(f) | D::Float(f) => float(*f)?,
            D::Text(t) => Value::String(t.clone()),
            D::Array(a) => Value::Array(a.iter().map(value).collect::<Option<_>>()?),
            D::Map(m) => Value::Object(
                m.iter()
                    .map(|(k, v)| Some((k.clone(), value(v)?)))
                    .collect::<Option<_>>()?,
            ),
            // JSON carries no byte string.
            D::Bytes(_) => return None,
        })
    }
    value(&crate::telemetry::decode::json(bytes)?)
}

/// Reads a report's bytes (§2.10): strict JSON first, as `alarms.v1` §2.4
/// reads a document (UTF-8, RFC 8259, nothing after the value but
/// whitespace, no duplicate member at any depth, every number finite), at
/// most [`MAX_DEPTH`] deep, then [`Report::from_json`].
///
/// **Finite** is by rounding (text 0.2, F-167, as `telemetry.v1` §2.6
/// reads it): a number's text, an integer's included, is finite when its
/// exact value rounded to the nearest double is not an infinity, so 10^400
/// written out is not strict JSON, and `1.7976931348623158e308` is.
/// **Depth** (text 0.2): 256 nested arrays read, 257 do not; `serde_json`'s
/// own recursion limit decides nothing ([`strict_json`]). **Numbers**
/// (text 0.3, F-181) are read by their exact value, as §2.7 compares a
/// document's: a number with a zero fraction is that integer, so
/// `18446744073709551615.0` is the revision 2^64−1, and `1.5` is no
/// integer.
///
/// # Errors
///
/// [`Unreadable::Json`] for bytes that are not strict JSON, else
/// [`Report::from_json`]'s.
pub fn decode(bytes: &[u8]) -> Result<Report, Unreadable> {
    let v = strict_json(bytes).ok_or_else(|| {
        Unreadable::Json(format!(
            "not strict JSON: UTF-8, RFC 8259, no duplicate member, every number finite, at most {MAX_DEPTH} deep"
        ))
    })?;
    // Every number by its exact value (text 0.3, F-181): a revision written
    // `18446744073709551615.0` is 2^64−1, in range.
    let exact = std::str::from_utf8(bytes)
        .ok()
        .and_then(Exact::of_strict_text);
    Report::read(&v, exact.as_ref())
}

// --- §2.6–§2.10: a target ------------------------------------------------------

/// Which path a sample came by (§2.5, §2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Via {
    /// The author's own answer, or its put.
    Owner,
    /// An archive's last-known (core S5, S6).
    Archive,
}

/// A sample's kind: a put, or a delete or a `reply_del`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Mutation {
    Put,
    Delete,
}

/// A put's document, as a target compares two (§2.7): the SHA-256 of its
/// canonical form for a payload encoded as JSON that reads as strict JSON,
/// else of its bytes. Equal digests are the same document.
///
/// The canonical form is JCS's (RFC 8785), members in order and nothing
/// but the value, with one change (text 0.2, F-166): a number is written
/// by its exact value, never as the double RFC 8785 reads, so `10`, `10.0`
/// and `1e1` are one document and 2^53 and 2^53 + 1 are two. Its bytes are
/// strict JSON, a number spelled as [`exact_number`] writes it, so they are
/// their own canonical form, and never the bytes of a payload that does
/// not read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Content([u8; 32]);

impl Content {
    fn digest(bytes: &[u8]) -> Self {
        use sha2::{Digest, Sha256};
        let mut d = [0u8; 32];
        d.copy_from_slice(&Sha256::digest(bytes));
        Self(d)
    }

    /// A decoded JSON document, compared by its canonical form. A
    /// `serde_json` float is a double, so it compares as the double's
    /// shortest spelling; an integer within 64 bits is exact. A runtime
    /// compares a payload's bytes ([`Content::of_payload`]), whose every
    /// number is exact.
    #[must_use]
    pub fn of_json(v: &Value) -> Self {
        let mut out = Vec::new();
        Exact::of_value(v).write(&mut out);
        Self::digest(&out)
    }

    /// A payload compared byte for byte: CBOR, protobuf, raw.
    #[must_use]
    pub fn of_bytes(bytes: &[u8]) -> Self {
        Self::digest(bytes)
    }

    /// A payload as a target compares it (§2.7): one encoded as JSON
    /// (`json`) by its canonical form when it reads as strict JSON (§2.10's
    /// reading, [`strict_json`]: every number finite by rounding, at most
    /// [`MAX_DEPTH`] deep), and every other payload, or JSON that does not
    /// read, byte for byte.
    #[must_use]
    pub fn of_payload(bytes: &[u8], json: bool) -> Self {
        let read = json
            .then(|| std::str::from_utf8(bytes).ok())
            .flatten()
            .and_then(Exact::of_strict_text);
        match read {
            Some(e) => {
                let mut out = Vec::new();
                e.write(&mut out);
                Self::digest(&out)
            }
            None => Self::of_bytes(bytes),
        }
    }
}

/// A number's text (RFC 8259's grammar) as its exact value, canonical
/// (§2.7, text 0.2): `0`, or an optional `-`, the significant digits with
/// no leading and no trailing zero, `e`, and the exponent in decimal. So
/// `10`, `10.0`, `1e1` and `100e-1` are `1e1`; `-0` is `0`; 2^53 is
/// `9007199254740992e0` and 2^53 + 1 `9007199254740993e0`. `None` for text
/// outside the grammar, or an exponent whose text does not fit 128 bits,
/// which a comparison then reads byte for byte.
#[must_use]
pub fn exact_number(text: &str) -> Option<String> {
    let (neg, rest) = match text.strip_prefix('-') {
        Some(r) => (true, r),
        None => (false, text),
    };
    let (mantissa, exp) = match rest.find(['e', 'E']) {
        Some(i) => (&rest[..i], Some(&rest[i + 1..])),
        None => (rest, None),
    };
    let (int, frac) = match mantissa.split_once('.') {
        Some((i, f)) => (i, Some(f)),
        None => (mantissa, None),
    };
    let digits = |d: &str| !d.is_empty() && d.bytes().all(|b| b.is_ascii_digit());
    if !digits(int) || (int.len() > 1 && int.starts_with('0')) {
        return None;
    }
    if frac.is_some_and(|f| !digits(f)) {
        return None;
    }
    let exp: i128 = match exp {
        None => 0,
        Some(e) => {
            let body = e.strip_prefix(['+', '-']).unwrap_or(e);
            if !digits(body) {
                return None;
            }
            e.parse().ok()?
        }
    };
    let frac = frac.unwrap_or("");
    let all: String = [int, frac].concat();
    let significant = all.trim_start_matches('0');
    if significant.is_empty() {
        return Some("0".to_owned());
    }
    let kept = significant.trim_end_matches('0');
    let trailing = i128::try_from(significant.len() - kept.len()).ok()?;
    let exp = exp
        .checked_sub(i128::try_from(frac.len()).ok()?)?
        .checked_add(trailing)?;
    Some(format!("{}{kept}e{exp}", if neg { "-" } else { "" }))
}

/// A JSON value as §2.7 compares it: members by name, every number by its
/// exact value.
enum Exact {
    Null,
    Bool(bool),
    Number(String),
    Text(String),
    Array(Vec<Exact>),
    Object(BTreeMap<String, Exact>),
}

impl Exact {
    fn of_value(v: &Value) -> Self {
        match v {
            Value::Null => Self::Null,
            Value::Bool(b) => Self::Bool(*b),
            Value::Number(n) => {
                let text = match (n.as_u64(), n.as_i64(), n.as_f64()) {
                    (Some(u), _, _) => u.to_string(),
                    (None, Some(i), _) => i.to_string(),
                    (None, None, Some(f)) => format!("{f:e}"),
                    (None, None, None) => n.to_string(),
                };
                // Every spelling above is in RFC 8259's grammar.
                Self::Number(exact_number(&text).unwrap_or(text))
            }
            Value::String(s) => Self::Text(s.clone()),
            Value::Array(a) => Self::Array(a.iter().map(Self::of_value).collect()),
            Value::Object(m) => Self::Object(
                m.iter()
                    .map(|(k, v)| (k.clone(), Self::of_value(v)))
                    .collect(),
            ),
        }
    }

    /// A text read as strict JSON (§2.10, [`strict_json`]), its numbers
    /// exact. `None` when it is not strict JSON, or a number's exponent does
    /// not fit (see [`exact_number`]). The strict read comes first, here,
    /// because [`ExactReader`] trusts what it accepted; this is the only
    /// way to it, and it is private to the module ([`Content::of_payload`]
    /// calls it).
    fn of_strict_text(text: &str) -> Option<Self> {
        crate::telemetry::decode::json(text.as_bytes())?;
        let mut r = ExactReader {
            text,
            s: text.as_bytes(),
            at: 0,
        };
        let v = r.value()?;
        r.ws();
        (r.at == r.s.len()).then_some(v)
    }

    fn write(&self, out: &mut Vec<u8>) {
        match self {
            Self::Null => out.extend_from_slice(b"null"),
            Self::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
            Self::Number(n) => out.extend_from_slice(n.as_bytes()),
            Self::Text(s) => write_string(s, out),
            Self::Array(a) => {
                out.push(b'[');
                for (i, v) in a.iter().enumerate() {
                    if i > 0 {
                        out.push(b',');
                    }
                    v.write(out);
                }
                out.push(b']');
            }
            Self::Object(m) => {
                // JCS orders members by their names' UTF-16 code units.
                let mut members: Vec<(&String, &Exact)> = m.iter().collect();
                members.sort_by(|a, b| a.0.encode_utf16().cmp(b.0.encode_utf16()));
                out.push(b'{');
                for (i, (k, v)) in members.into_iter().enumerate() {
                    if i > 0 {
                        out.push(b',');
                    }
                    write_string(k, out);
                    out.push(b':');
                    v.write(out);
                }
                out.push(b'}');
            }
        }
    }
}

fn write_string(s: &str, out: &mut Vec<u8>) {
    let quoted = serde_json::to_string(s).unwrap_or_default();
    out.extend_from_slice(quoted.as_bytes());
}

/// Reads a text [`strict_json`] already accepted, so that its numbers keep
/// their text: no duplicate, nothing after the value, and at most
/// [`MAX_DEPTH`] deep, which bounds its recursion.
///
/// **Precondition:** the text read as strict JSON. Only
/// [`Exact::of_strict_text`] builds one, after that read. The reader then
/// skips a string's escapes blindly (a `\` and the byte after it) and slices
/// the string's token by byte offsets, both right only for strict JSON;
/// every access is `get`, so text outside the precondition reads `None`,
/// never a panic.
struct ExactReader<'a> {
    text: &'a str,
    s: &'a [u8],
    at: usize,
}

impl ExactReader<'_> {
    fn ws(&mut self) {
        while let Some(b' ' | b'\t' | b'\n' | b'\r') = self.s.get(self.at) {
            self.at += 1;
        }
    }

    fn eat(&mut self, b: u8) -> bool {
        let hit = self.s.get(self.at) == Some(&b);
        if hit {
            self.at += 1;
        }
        hit
    }

    fn string(&mut self) -> Option<String> {
        let start = self.at;
        if !self.eat(b'"') {
            return None;
        }
        loop {
            match self.s.get(self.at)? {
                b'"' => break,
                b'\\' => self.at += 2,
                _ => self.at += 1,
            }
        }
        self.at += 1;
        serde_json::from_str(self.text.get(start..self.at)?).ok()
    }

    fn value(&mut self) -> Option<Exact> {
        self.ws();
        match *self.s.get(self.at)? {
            b'{' => {
                self.at += 1;
                let mut m = BTreeMap::new();
                self.ws();
                if self.eat(b'}') {
                    return Some(Exact::Object(m));
                }
                loop {
                    self.ws();
                    let k = self.string()?;
                    self.ws();
                    if !self.eat(b':') {
                        return None;
                    }
                    let v = self.value()?;
                    m.insert(k, v);
                    self.ws();
                    if self.eat(b'}') {
                        return Some(Exact::Object(m));
                    }
                    if !self.eat(b',') {
                        return None;
                    }
                }
            }
            b'[' => {
                self.at += 1;
                let mut a = Vec::new();
                self.ws();
                if self.eat(b']') {
                    return Some(Exact::Array(a));
                }
                loop {
                    a.push(self.value()?);
                    self.ws();
                    if self.eat(b']') {
                        return Some(Exact::Array(a));
                    }
                    if !self.eat(b',') {
                        return None;
                    }
                }
            }
            b'"' => self.string().map(Exact::Text),
            b't' | b'f' | b'n' => {
                for (word, v) in [
                    ("true", Exact::Bool(true)),
                    ("false", Exact::Bool(false)),
                    ("null", Exact::Null),
                ] {
                    if self.s[self.at..].starts_with(word.as_bytes()) {
                        self.at += word.len();
                        return Some(v);
                    }
                }
                None
            }
            _ => {
                let start = self.at;
                while let Some(b'-' | b'+' | b'.' | b'e' | b'E' | b'0'..=b'9') = self.s.get(self.at)
                {
                    self.at += 1;
                }
                exact_number(self.text.get(start..self.at)?).map(Exact::Number)
            }
        }
    }
}

/// One sample or reply of a target's slice, as its runtime received it
/// (§2.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Sample {
    pub via: Via,
    pub mutation: Mutation,
    /// The author's stamp, `None` when the sample carries none.
    pub stamp: Option<Stamp>,
    /// The document type's own revision, when it carries one (§2.4). A
    /// delete has none.
    pub revision: Option<u64>,
    /// A put's document ([`Content`]); `None` for a delete, and for a put
    /// whose runtime did not compare it, which is then never the same
    /// document as another.
    pub content: Option<Content>,
}

/// What an act does (§2.7, §2.8).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ActKind {
    /// Decode, check and apply the document.
    Apply,
    /// Apply the baseline.
    Revert,
}

/// An act the target's runtime performs, then reports by
/// [`Target::finish`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Act {
    pub kind: ActKind,
    pub stamp: Stamp,
    pub revision: Option<u64>,
    pub via: Via,
    pub content: Option<Content>,
}

impl Act {
    fn of(s: &Sample, stamp: Stamp) -> Self {
        Self {
            kind: match s.mutation {
                Mutation::Put => ActKind::Apply,
                Mutation::Delete => ActKind::Revert,
            },
            stamp,
            revision: match s.mutation {
                Mutation::Put => s.revision,
                Mutation::Delete => None,
            },
            via: s.via,
            content: match s.mutation {
                Mutation::Put => s.content,
                Mutation::Delete => None,
            },
        }
    }

    /// Whether `next` carries the same document as this act (§2.7): two
    /// puts whose documents compare equal, or two deletes.
    #[must_use]
    pub fn same_document(&self, next: &Act) -> bool {
        machine::same_document((self.kind, self.content), (next.kind, next.content))
    }

    /// The act's version, as the report writes it.
    #[must_use]
    pub fn version(&self) -> Version {
        Version {
            stamp: self.stamp,
            revision: self.revision,
        }
    }
}

/// How an act ended (§2.7, §2.10), with the refusal its major's report
/// carries: [`Refusal`] for `desired.v1`, [`v2::Refusal`] for `desired.v2`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Ended<R = Refusal> {
    /// Applied whole: a put converged, a delete reverted.
    Done,
    /// Refused whole, nothing applied. A revert is never refused: a
    /// refusal of one is read as [`Ended::Failed`].
    Refused(R),
    /// Applied in part.
    Failed(R),
}

/// What a step of a target does (§2.6–§2.9).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Step {
    /// Start this act now.
    Act(Act),
    /// Admitted, and the same document as the last version acted on or
    /// adopted: no act, and the report moved (§2.7).
    Adopted,
    /// Admitted while an act runs: held, replacing any version held before.
    Held,
    /// No stamp: never acted on (§2.6 step 1).
    Unstamped,
    /// The version held, received again (§2.6 step 3).
    SameVersion,
    /// An earlier time of the held version's id (§2.6 step 3).
    Older,
    /// The author's own sample of a version held from an archive (§2.9).
    /// When no act runs, the report changed: its `last_known` went.
    Confirmed,
    /// An act ended, and nothing is held.
    Done,
}

impl Step {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Act(Act {
                kind: ActKind::Apply,
                ..
            }) => "act",
            Self::Act(Act {
                kind: ActKind::Revert,
                ..
            }) => "revert",
            Self::Adopted => "adopted",
            Self::Held => "held",
            Self::Unstamped => "unstamped",
            Self::SameVersion => "same_version",
            Self::Older => "older",
            Self::Confirmed => "confirmed",
            Self::Done => "done",
        }
    }
}

/// How many ids a target remembers (§2.6, text 0.2, F-163): at least the
/// 16 most recent ids an instance acted on or adopted a version of. An id
/// forgotten beyond them is read as new. `desired.v2` remembers as many
/// runs ([`v2::REMEMBERED_RUNS`]).
pub const REMEMBERED_IDS: usize = 16;

/// The state machine both majors share (v1 §2.6 to §2.10, which
/// `desired.v2` §2.6 to §2.10 restates over runs and seqs): one copy of
/// each rule that did not change. A major gives its [`machine::Mark`], the
/// place of a version in its author's order, and renders its own report
/// from the [`machine::Ledger`].
pub(crate) mod machine {
    use std::cmp::Ordering;
    use std::fmt;

    use super::{ActKind, Content, Ended, Outcome, REMEMBERED_IDS, Source, Via};

    /// A version's place in its author's order: an epoch nothing orders
    /// against another (v1: the stamp's id; v2: the run, with its width)
    /// and a tick within it (v1: the time; v2: the seq).
    pub(crate) trait Mark: Copy + Eq + fmt::Debug {
        type Epoch: Copy + Eq + fmt::Debug;
        type Tick: Copy + Ord + fmt::Debug;
        fn epoch(&self) -> Self::Epoch;
        fn tick(&self) -> Self::Tick;
        /// A floor names no version (`desired.v2` §2.8's snapshot with no
        /// entry: its run and its asof): every version of its epoch at or
        /// below its tick is older, and it leaves no observed version.
        /// `desired.v1` has none.
        fn floor(&self) -> bool {
            false
        }
    }

    /// An act, as the machine holds one: what a major's `Act` says, its
    /// stamp a [`Mark`].
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) struct Doing<M> {
        pub kind: ActKind,
        pub mark: M,
        pub revision: Option<u64>,
        pub via: Via,
        pub content: Option<Content>,
    }

    /// Whether two acts carry the same document (§2.7): two puts whose
    /// documents compare equal, or two that carry none.
    pub(crate) fn same_document(
        a: (ActKind, Option<Content>),
        b: (ActKind, Option<Content>),
    ) -> bool {
        match (a.0, b.0) {
            (ActKind::Revert, ActKind::Revert) => true,
            (ActKind::Apply, ActKind::Apply) => a.1.is_some() && a.1 == b.1,
            _ => false,
        }
    }

    /// What a version received does (§2.6).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Judged<M> {
        Act(Doing<M>),
        Adopted,
        Held,
        SameVersion,
        Older,
        Confirmed,
    }

    /// What a floor received does (`desired.v2` §2.8).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Floored<M> {
        NoVerdict,
        Older,
        Held,
        Act(Doing<M>),
    }

    /// What follows an act's end (§2.7).
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(crate) enum Finished<M> {
        Done,
        Adopted,
        Act(Doing<M>),
    }

    /// What a report says, whatever its major's record (§2.10): a version
    /// is its mark and its document's own revision.
    #[derive(Debug, Clone, PartialEq, Eq)]
    pub(crate) struct Ledger<M, R> {
        pub source: Source,
        pub in_force: Option<(M, Option<u64>)>,
        pub observed: Option<(M, Option<u64>)>,
        /// `None` until an act ends in this process.
        pub outcome: Option<Outcome>,
        pub refusal: Option<R>,
        pub last_known: bool,
    }

    /// Why a version is not admitted over the one held.
    enum Not {
        Same,
        Older,
    }

    /// Whether `incoming` is admitted over `held` (§2.6, core §4.3): by
    /// tick within one epoch, the first value under another epoch
    /// accepted. At or below a floor of its epoch, it is older.
    fn admits<M: Mark>(held: &M, incoming: &M) -> Result<(), Not> {
        if held.epoch() != incoming.epoch() {
            return Ok(());
        }
        match incoming.tick().cmp(&held.tick()) {
            Ordering::Greater => Ok(()),
            Ordering::Equal if !held.floor() => Err(Not::Same),
            Ordering::Equal | Ordering::Less => Err(Not::Older),
        }
    }

    /// The author's own delivery of a version held from an archive
    /// confirms it (§2.9).
    fn confirm<M>(slot: &mut Doing<M>, via: Via) -> bool {
        let confirmed = via == Via::Owner && slot.via == Via::Archive;
        if confirmed {
            slot.via = Via::Owner;
        }
        confirmed
    }

    /// One process of a target's role: the version it last acted on or
    /// adopted, the one it holds while an act runs, per epoch the highest
    /// tick it acted on or adopted, and what its report says.
    #[derive(Debug, Clone)]
    pub(crate) struct Core<M: Mark, R> {
        acted: Option<Doing<M>>,
        running: bool,
        waiting: Option<Doing<M>>,
        /// `(epoch, tick, floor)`, the epoch acted on or adopted most
        /// recently first, at most [`REMEMBERED_IDS`].
        remembered: Vec<(M::Epoch, M::Tick, bool)>,
        ledger: Ledger<M, R>,
    }

    impl<M: Mark, R> Core<M, R> {
        /// At its start: nothing held, the baseline in force.
        pub fn new() -> Self {
            Self {
                acted: None,
                running: false,
                waiting: None,
                remembered: Vec::new(),
                ledger: Ledger {
                    source: Source::Baseline,
                    in_force: None,
                    observed: None,
                    outcome: None,
                    refusal: None,
                    last_known: false,
                },
            }
        }

        pub fn ledger(&self) -> &Ledger<M, R> {
            &self.ledger
        }

        /// The act that runs, if one does.
        pub fn running(&self) -> Option<&Doing<M>> {
            self.acted.as_ref().filter(|_| self.running)
        }

        /// The latest it admitted (§2.5's held stamp): the one held
        /// waiting, else the running act's, else the last acted on or
        /// adopted.
        pub fn latest(&self) -> Option<&Doing<M>> {
            self.waiting.as_ref().or(self.acted.as_ref())
        }

        /// The highest tick this process acted on or adopted under
        /// `epoch`, if it remembers the epoch (§2.6 step 4).
        pub fn remembered(&self, epoch: M::Epoch) -> Option<M::Tick> {
            self.remembered_as(epoch).map(|(t, _)| t)
        }

        fn remembered_as(&self, epoch: M::Epoch) -> Option<(M::Tick, bool)> {
            self.remembered
                .iter()
                .find(|(e, _, _)| *e == epoch)
                .map(|(_, t, f)| (*t, *f))
        }

        /// Records a version acted on or adopted (§2.6 step 4). Called
        /// from `start`, as an act starts and as a version is adopted, so
        /// an adoption counts as an act does; a version held waiting
        /// counts only once its act starts or it is adopted, and one
        /// passed over never.
        fn remember(&mut self, mark: M) {
            let (tick, floor) = match self
                .remembered
                .iter()
                .position(|(e, _, _)| *e == mark.epoch())
            {
                Some(at) => {
                    let (_, tick, floor) = self.remembered.remove(at);
                    match mark.tick().cmp(&tick) {
                        Ordering::Greater => (mark.tick(), mark.floor()),
                        Ordering::Equal => (tick, floor || mark.floor()),
                        Ordering::Less => (tick, floor),
                    }
                }
                None => (mark.tick(), mark.floor()),
            };
            self.remembered.insert(0, (mark.epoch(), tick, floor));
            self.remembered.truncate(REMEMBERED_IDS);
        }

        /// Judges a version (§2.6): against the version last acted on or
        /// adopted (the running act's while one runs) and every epoch
        /// remembered, then, while an act runs, against the one held
        /// waiting (§2.7): an act to start, adopted, held while one runs,
        /// or ignored with why.
        pub fn observe(&mut self, doing: Doing<M>) -> Judged<M> {
            let mark = doing.mark;
            let remembered = self.remembered_as(mark.epoch());
            if let Some(r) = self.acted.as_mut() {
                if r.mark.epoch() == mark.epoch() {
                    match admits(&r.mark, &mark) {
                        Ok(()) => {}
                        Err(Not::Same) if confirm(r, doing.via) => {
                            if !self.running {
                                self.ledger.last_known = false;
                            }
                            return Judged::Confirmed;
                        }
                        Err(Not::Same) => return Judged::SameVersion,
                        Err(Not::Older) => return Judged::Older,
                    }
                } else if let Some((tick, floor)) = remembered {
                    // Another epoch than the held one, acted on or adopted
                    // before in this process: never an older version of
                    // it, nor one acted on again. A version is its stamp
                    // (§2.4), so an equal one is the same version
                    // whatever document it carries.
                    match mark.tick().cmp(&tick) {
                        Ordering::Greater => {}
                        Ordering::Equal if !floor => return Judged::SameVersion,
                        Ordering::Equal | Ordering::Less => return Judged::Older,
                    }
                }
            }
            if let Some(w) = self.waiting.as_mut() {
                match admits(&w.mark, &mark) {
                    Ok(()) => {}
                    Err(Not::Same) if confirm(w, doing.via) => return Judged::Confirmed,
                    Err(Not::Same) => return Judged::SameVersion,
                    Err(Not::Older) => return Judged::Older,
                }
            }
            if self.running {
                self.waiting = Some(doing);
                return Judged::Held;
            }
            match self.start(doing) {
                Finished::Act(a) => Judged::Act(a),
                Finished::Adopted | Finished::Done => Judged::Adopted,
            }
        }

        /// Judges a floor (`desired.v2` §2.8): it reverts only a put's
        /// version of its own epoch at or below its tick, judged of the
        /// version last acted on or adopted, then of the one held waiting.
        pub fn observe_floor(&mut self, floor: M) -> Floored<M> {
            let reverts = |held: &Doing<M>| {
                if held.kind != ActKind::Apply || held.mark.epoch() != floor.epoch() {
                    Err(Floored::NoVerdict)
                } else if held.mark.tick() > floor.tick() {
                    Err(Floored::Older)
                } else {
                    Ok(())
                }
            };
            let Some(acted) = self.acted.as_ref() else {
                return Floored::NoVerdict;
            };
            if let Err(why) = reverts(acted) {
                return why;
            }
            if let Some(Err(why)) = self.waiting.as_ref().map(reverts) {
                return why;
            }
            let doing = Doing {
                kind: ActKind::Revert,
                mark: floor,
                revision: None,
                via: Via::Owner,
                content: None,
            };
            if self.running {
                self.waiting = Some(doing);
                return Floored::Held;
            }
            match self.start(doing) {
                Finished::Act(a) => Floored::Act(a),
                // A floor follows a put, never the same document.
                Finished::Adopted | Finished::Done => Floored::NoVerdict,
            }
        }

        /// The author's own word of `mark`, by an unchanged answer to a
        /// conditional read (`desired.v2` §2.5, §2.9): it confirms that
        /// version where the target holds it from an archive, acted on,
        /// running or waiting, and is no version received: nothing is
        /// judged, admitted or remembered. `true` when it confirmed one.
        pub fn unchanged(&mut self, mark: M) -> bool {
            if let Some(w) = self.waiting.as_mut().filter(|w| w.mark == mark) {
                return confirm(w, Via::Owner);
            }
            let Some(a) = self.acted.as_mut().filter(|a| a.mark == mark) else {
                return false;
            };
            let confirmed = confirm(a, Via::Owner);
            if confirmed && !self.running {
                self.ledger.last_known = false;
            }
            confirmed
        }

        fn start(&mut self, doing: Doing<M>) -> Finished<M> {
            self.remember(doing.mark);
            let version = (!doing.mark.floor()).then_some((doing.mark, doing.revision));
            if let Some(prev) = self.acted
                && same_document((prev.kind, prev.content), (doing.kind, doing.content))
            {
                let l = &mut self.ledger;
                if !prev.mark.floor() && l.in_force.is_some_and(|(m, _)| m == prev.mark) {
                    l.in_force = version;
                }
                l.observed = version;
                l.last_known = doing.via == Via::Archive;
                self.acted = Some(doing);
                return Finished::Adopted;
            }
            self.acted = Some(doing);
            self.running = true;
            Finished::Act(doing)
        }

        /// Ends the running act (§2.7, §2.10): the ledger updated, then
        /// the held version, if one is held, adopted or its act started.
        /// With no act running, nothing changes.
        pub fn finish(&mut self, ended: Ended<R>) -> Finished<M> {
            let Some(act) = self.acted.filter(|_| self.running) else {
                return Finished::Done;
            };
            self.running = false;
            let l = &mut self.ledger;
            let version = (act.mark, act.revision);
            if !act.mark.floor() {
                l.observed = Some(version);
                l.last_known = act.via == Via::Archive;
            } else if matches!(ended, Ended::Done) {
                // A revert on a floor has no observed version
                // (`desired.v2` §2.8). One that could not finish keeps
                // the version it was reverting: a failed act with none
                // stated would be malformed (§2.10).
                l.observed = None;
                l.last_known = false;
            }
            l.refusal = None;
            match (act.kind, ended) {
                (ActKind::Apply, Ended::Done) => {
                    l.source = Source::Desired;
                    l.in_force = Some(version);
                    l.outcome = Some(Outcome::Converged);
                }
                (ActKind::Revert, Ended::Done) => {
                    l.source = Source::Baseline;
                    l.in_force = None;
                    l.outcome = Some(Outcome::Reverted);
                }
                (ActKind::Apply, Ended::Refused(why)) => {
                    l.outcome = Some(Outcome::Refused);
                    l.refusal = Some(why);
                }
                (kind, Ended::Refused(why) | Ended::Failed(why)) => {
                    l.source = match kind {
                        ActKind::Apply => Source::Desired,
                        ActKind::Revert => Source::Baseline,
                    };
                    l.in_force = None;
                    l.outcome = Some(Outcome::Failed);
                    l.refusal = Some(why);
                }
            }
            match self.waiting.take() {
                Some(next) => self.start(next),
                None => Finished::Done,
            }
        }

        /// The target's own operation changed what is in force (§2.7):
        /// `source` is `call`, and no version is wholly in force. The
        /// last act's report stands, and no version is acted on again.
        pub fn call(&mut self) {
            self.ledger.source = Source::Call;
            self.ledger.in_force = None;
        }
    }
}

impl machine::Mark for Stamp {
    type Epoch = u128;
    type Tick = u64;
    fn epoch(&self) -> u128 {
        self.id
    }
    fn tick(&self) -> u64 {
        self.time
    }
}

impl From<machine::Doing<Stamp>> for Act {
    fn from(d: machine::Doing<Stamp>) -> Self {
        Self {
            kind: d.kind,
            stamp: d.mark,
            revision: d.revision,
            via: d.via,
            content: d.content,
        }
    }
}

/// One instance of a target's role (§2.6–§2.10): the version it last acted
/// on or adopted, the one it holds while an act runs, per id the latest
/// time it acted on or adopted (F-163), and its report. A restart is a new
/// `Target`, holding nothing (§2.7). Its rules are `machine::Core`'s,
/// which `desired.v2`'s target shares ([`v2::Target`]).
#[derive(Debug, Clone)]
pub struct Target {
    core: machine::Core<Stamp, Refusal>,
    key: Option<String>,
    running: Option<Act>,
    report: Report,
}

impl Target {
    /// A role bound to the slice `key`, or unbound (`None`, §2.12), at its
    /// start: nothing held, its report the baseline's.
    #[must_use]
    pub fn new(key: Option<String>) -> Self {
        Self {
            core: machine::Core::new(),
            running: None,
            report: Report::baseline(key.clone()),
            key,
        }
    }

    /// The report, as the target puts it (§2.10).
    #[must_use]
    pub fn report(&self) -> &Report {
        &self.report
    }

    /// The act that runs, if one does.
    #[must_use]
    pub fn running(&self) -> Option<&Act> {
        self.running.as_ref()
    }

    /// The latest time this instance acted on or adopted a version of `id`
    /// at, if it remembers the id (§2.6 step 4).
    #[must_use]
    pub fn remembered(&self, id: u128) -> Option<u64> {
        self.core.remembered(id)
    }

    /// The machine's ledger written as `desired.v1.Report`, and the
    /// running act as the runtime reads it.
    fn sync(&mut self) {
        let version = |(stamp, revision): (Stamp, Option<u64>)| Version { stamp, revision };
        let l = self.core.ledger();
        self.report = Report {
            key: self.key.clone(),
            source: l.source,
            in_force: l.in_force.map(version),
            observed: l.observed.map(version),
            outcome: l.outcome,
            refusal: l.refusal.clone(),
            last_known: l.last_known,
        };
        self.running = self.core.running().map(|d| Act::from(*d));
    }

    /// Judges a sample (§2.6): against the version last acted on or adopted
    /// (the running act's while one runs) and every id remembered, then,
    /// while an act runs, against the version held waiting (§2.7, text
    /// 0.2, F-162): an act to start, adopted, held while one runs, or
    /// ignored with why. After [`Step::Adopted`] the report changed.
    pub fn observe(&mut self, s: Sample) -> Step {
        let Some(stamp) = s.stamp else {
            return Step::Unstamped;
        };
        let act = Act::of(&s, stamp);
        let step = match self.core.observe(machine::Doing {
            kind: act.kind,
            mark: stamp,
            revision: act.revision,
            via: act.via,
            content: act.content,
        }) {
            machine::Judged::Act(d) => Step::Act(d.into()),
            machine::Judged::Adopted => Step::Adopted,
            machine::Judged::Held => Step::Held,
            machine::Judged::SameVersion => Step::SameVersion,
            machine::Judged::Older => Step::Older,
            machine::Judged::Confirmed => Step::Confirmed,
        };
        self.sync();
        step
    }

    /// Ends the running act (§2.7, §2.10): the report updated, then the
    /// held version, if one is held, adopted or its act started, else
    /// [`Step::Done`]. With no act running, nothing changes, and it is
    /// [`Step::Done`].
    pub fn finish(&mut self, ended: Ended) -> Step {
        let step = match self.core.finish(ended) {
            machine::Finished::Done => Step::Done,
            machine::Finished::Adopted => Step::Adopted,
            machine::Finished::Act(d) => Step::Act(d.into()),
        };
        self.sync();
        step
    }

    /// The target's own operation changed what is in force (§2.7): the
    /// report's `source` is `call`, and no version is wholly in force. The
    /// last act's report stands, and no version is acted on again.
    pub fn call(&mut self) {
        self.core.call();
        self.sync();
    }
}

// --- §2.17, §5: what a tool may conclude ---------------------------------------

/// A participant's presence, as the tool saw it (core §8.1, §8.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Seen {
    /// Its instance token was seen.
    Present,
    /// A complete read held no instance token of it: absence (core §8.1,
    /// 0.37), never a withdrawal heard live (text 0.3, F-187).
    Absent,
    /// Not seen, in a read possibly incomplete or refused, or a read not
    /// made through a session cut off (core §8.1, 0.37).
    Incomplete,
    /// Across a constrained face, where presence does not cross and the
    /// deployment's word stands for the descriptor (§2.17, text 0.2,
    /// F-168).
    AcrossFace,
}

/// What the target's descriptor says of the role (core §3.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Listing {
    /// Its `requires` do not list the role.
    NotListed,
    /// They list it, bound (`bound`) or with `"bindings": []`.
    Listed { bound: bool },
}

/// What §2.17's step 5 reads of a report, of either major.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Facts {
    pub source: Source,
    /// The last act's outcome, `None` with no act yet in this process: a
    /// `desired.v1` report with no `outcome`, a `desired.v2` one that says
    /// `not_acted`.
    pub outcome: Option<Outcome>,
    pub last_known: bool,
    /// Whether a version is wholly in force: v1's `in_force`, v2's
    /// `in_force` `observed` or `other`.
    pub in_force: bool,
}

/// A report of either major, as §5's judges read one: [`Report`]
/// (`desired.v1`) or [`v2::Read`] (`desired.v2`).
pub trait Reported {
    /// What step 5 reads, or `None` for a malformed report (§2.10's
    /// consistency), which answers nothing.
    fn facts(&self) -> Option<Facts>;
}

impl Reported for Report {
    fn facts(&self) -> Option<Facts> {
        self.check().is_empty().then(|| Facts {
            source: self.source,
            outcome: self.outcome,
            last_known: self.last_known,
            in_force: self.in_force.is_some(),
        })
    }
}

/// The target's report of the role's slice, as the tool read it (§2.10):
/// `R` is the major's report as read, [`Report`] or [`v2::Read`].
#[derive(Debug)]
pub enum ReportRead<'a, R = Report> {
    /// None read.
    NotRead,
    /// Bytes that do not read ([`decode`] or [`v2::read`] refused them).
    Unreadable,
    /// A report that reads; malformed when it has a finding
    /// ([`Reported::facts`]).
    Read(&'a R),
}

impl<R> Clone for ReportRead<'_, R> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<R> Copy for ReportRead<'_, R> {}

/// What the tool read of the target (§2.17 steps 1 to 4).
#[derive(Debug)]
pub struct TargetReading<'a, R = Report> {
    pub presence: Seen,
    /// Its descriptor, `None` when not read. Ignored across a face.
    pub descriptor: Option<Listing>,
    /// Across a face, the deployment's word for what the descriptor would
    /// say, `None` when the tool has none (§2.17 step 2, text 0.2, F-168).
    /// Ignored elsewhere.
    pub deployment: Option<Listing>,
    pub report: ReportRead<'a, R>,
    /// The report's freshness by the `freshness` major its contract uses,
    /// [`freshness::Verdict::NotAsked`] when its resource declares no
    /// horizon.
    pub freshness: freshness::Verdict,
}

impl<R> Clone for TargetReading<'_, R> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<R> Copy for TargetReading<'_, R> {}

/// The author's latest version of the slice, by S4's GET (§2.17 step 6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Current {
    /// No GET made.
    NotRead,
    /// A GET that ended at its timeout or with an error reply.
    Incomplete,
    /// A GET that drew nothing for the key.
    Silent,
    /// Its latest put.
    Put(Stamp),
    /// Its latest delete, or `reply_del`.
    Delete(Stamp),
}

/// What the tool read of the author (§2.17 step 6).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthorReading {
    pub presence: Seen,
    pub current: Current,
}

/// A question of §5, answered in its states: the two poles, not yet, and
/// the two unestablished kinds apart (core O5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Answer {
    Yes,
    No,
    /// The target has not acted on the author's current version yet.
    NotYet,
    /// The question was put, and the reading could not answer it.
    Unobservable,
    /// Nobody put the question, or its premise does not hold.
    NotAsked,
}

impl Answer {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Yes => "yes",
            Self::No => "no",
            Self::NotYet => "not_yet",
            Self::Unobservable => "unobservable",
            Self::NotAsked => "not_asked",
        }
    }
}

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

/// Why an answer is what it is: the fixture's reason (§2.17).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reason {
    TargetAbsent,
    PresenceIncomplete,
    NoDescriptor,
    NotATarget,
    Unbound,
    NoReport,
    NothingCrossed,
    ReportInvalid,
    ReportStale,
    ReportUnobservable,
    NotActed,
    Converged,
    Refused,
    Failed,
    Reverted,
    LastKnown,
    Current,
    Desired,
    Partial,
    Baseline,
    Call,
    AuthorAbsent,
    AuthorPresenceIncomplete,
    AuthorNotRead,
    AuthorReadIncomplete,
    AuthorSilent,
    Behind,
    Ahead,
    OtherEpoch,
}

impl Reason {
    /// The fixture's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::TargetAbsent => "target_absent",
            Self::PresenceIncomplete => "presence_incomplete",
            Self::NoDescriptor => "no_descriptor",
            Self::NotATarget => "not_a_target",
            Self::Unbound => "unbound",
            Self::NoReport => "no_report",
            Self::NothingCrossed => "nothing_crossed",
            Self::ReportInvalid => "report_invalid",
            Self::ReportStale => "report_stale",
            Self::ReportUnobservable => "report_unobservable",
            Self::NotActed => "not_acted",
            Self::Converged => "converged",
            Self::Refused => "refused",
            Self::Failed => "failed",
            Self::Reverted => "reverted",
            Self::LastKnown => "last_known",
            Self::Current => "current",
            Self::Desired => "desired",
            Self::Partial => "partial",
            Self::Baseline => "baseline",
            Self::Call => "call",
            Self::AuthorAbsent => "author_absent",
            Self::AuthorPresenceIncomplete => "author_presence_incomplete",
            Self::AuthorNotRead => "author_not_read",
            Self::AuthorReadIncomplete => "author_read_incomplete",
            Self::AuthorSilent => "author_silent",
            Self::Behind => "behind",
            Self::Ahead => "ahead",
            Self::OtherEpoch => "other_epoch",
        }
    }
}

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

/// An answer and its reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Judged {
    pub answer: Answer,
    pub reason: Reason,
}

impl Judged {
    const fn new(answer: Answer, reason: Reason) -> Self {
        Self { answer, reason }
    }
}

/// §2.17 steps 1 to 4, shared by every question and by both majors: the
/// report to answer from with what step 5 reads of it, or the answer.
/// `unbound` is the answer for an unbound role. Across a face, the
/// deployment's word answers step 2 in the descriptor's place (text 0.2,
/// F-168).
fn premises<'a, R: Reported>(
    t: &TargetReading<'a, R>,
    unbound: Judged,
) -> Result<(&'a R, Facts), Judged> {
    use Answer::{NotAsked, Unobservable};
    let listing = match t.presence {
        Seen::Absent => return Err(Judged::new(NotAsked, Reason::TargetAbsent)),
        Seen::Incomplete => return Err(Judged::new(Unobservable, Reason::PresenceIncomplete)),
        Seen::AcrossFace => t.deployment,
        Seen::Present => t.descriptor,
    };
    match listing {
        None => return Err(Judged::new(Unobservable, Reason::NoDescriptor)),
        Some(Listing::NotListed) => return Err(Judged::new(NotAsked, Reason::NotATarget)),
        Some(Listing::Listed { bound: false }) => return Err(unbound),
        Some(Listing::Listed { bound: true }) => {}
    }
    let report = match t.report {
        ReportRead::NotRead => {
            return Err(Judged::new(
                Unobservable,
                if t.presence == Seen::AcrossFace {
                    Reason::NothingCrossed
                } else {
                    Reason::NoReport
                },
            ));
        }
        ReportRead::Unreadable => return Err(Judged::new(Unobservable, Reason::ReportInvalid)),
        ReportRead::Read(r) => match r.facts() {
            Some(f) => (r, f),
            None => return Err(Judged::new(Unobservable, Reason::ReportInvalid)),
        },
    };
    match t.freshness {
        freshness::Verdict::Stale => Err(Judged::new(Unobservable, Reason::ReportStale)),
        freshness::Verdict::Unobservable => {
            Err(Judged::new(Unobservable, Reason::ReportUnobservable))
        }
        freshness::Verdict::Fresh | freshness::Verdict::NotAsked => Ok(report),
    }
}

const UNBOUND: Judged = Judged::new(Answer::NotAsked, Reason::Unbound);

/// §5's first question up to step 6's read, for either major: the
/// premises, then the author's presence.
fn converging<'a, R: Reported>(
    t: &TargetReading<'a, R>,
    author: Seen,
) -> Result<(&'a R, Facts), Judged> {
    let r = premises(t, UNBOUND)?;
    match author {
        Seen::Absent => Err(Judged::new(Answer::NotAsked, Reason::AuthorAbsent)),
        Seen::Incomplete => Err(Judged::new(
            Answer::Unobservable,
            Reason::AuthorPresenceIncomplete,
        )),
        Seen::Present | Seen::AcrossFace => Ok(r),
    }
}

/// Step 7, of either major: the report's observed version against the
/// author's. The same version answers by the last act's outcome; within
/// one epoch (v1: an id; v2: a run) a lower tick is behind and a higher
/// one ahead; another epoch is `other_epoch`.
fn compared<M: machine::Mark>(observed: &M, current: &M, outcome: Outcome) -> Judged {
    if observed == current {
        return match outcome {
            Outcome::Converged | Outcome::Reverted => {
                Judged::new(Answer::Yes, outcome_reason(outcome))
            }
            Outcome::Refused | Outcome::Failed => Judged::new(Answer::No, outcome_reason(outcome)),
        };
    }
    if observed.epoch() != current.epoch() {
        return Judged::new(Answer::NotYet, Reason::OtherEpoch);
    }
    if observed.tick() < current.tick() {
        Judged::new(Answer::NotYet, Reason::Behind)
    } else {
        Judged::new(Answer::Unobservable, Reason::Ahead)
    }
}

fn outcome_reason(o: Outcome) -> Reason {
    match o {
        Outcome::Converged => Reason::Converged,
        Outcome::Refused => Reason::Refused,
        Outcome::Failed => Reason::Failed,
        Outcome::Reverted => Reason::Reverted,
    }
}

/// §5's second question, "is the target's last act refused or failed?"
/// (§2.17), of a report of either major. Yes is the finding.
#[must_use]
pub fn refused<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
    let r = match premises(t, UNBOUND) {
        Ok((_, f)) => f,
        Err(j) => return j,
    };
    match r.outcome {
        None => Judged::new(Answer::NotAsked, Reason::NotActed),
        Some(o @ (Outcome::Refused | Outcome::Failed)) => {
            Judged::new(Answer::Yes, outcome_reason(o))
        }
        Some(o) => Judged::new(Answer::No, outcome_reason(o)),
    }
}

/// §5's third question, "is what the target acted on last-known?" (§2.9,
/// §2.17), of a report of either major. Informative. Not asked with no act
/// yet: a consistent `desired.v1` report has an `observed` exactly when it
/// has an `outcome`, and a `desired.v2` one that reverted on a snapshot
/// with no entry has an outcome and no observed version.
#[must_use]
pub fn last_known<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
    let r = match premises(t, UNBOUND) {
        Ok((_, f)) => f,
        Err(j) => return j,
    };
    match (r.outcome, r.last_known) {
        (None, _) => Judged::new(Answer::NotAsked, Reason::NotActed),
        (Some(_), true) => Judged::new(Answer::Yes, Reason::LastKnown),
        (Some(_), false) => Judged::new(Answer::No, Reason::Current),
    }
}

/// §5's fourth question, "is a desired document in force?" (§2.10,
/// §2.12, §2.17), of a report of either major. An unbound role answers no:
/// the kill switch. Informative.
#[must_use]
pub fn in_force<R: Reported>(t: &TargetReading<'_, R>) -> Judged {
    let r = match premises(t, Judged::new(Answer::No, Reason::Unbound)) {
        Ok((_, f)) => f,
        Err(j) => return j,
    };
    match r.source {
        Source::Desired if r.in_force => Judged::new(Answer::Yes, Reason::Desired),
        Source::Desired => Judged::new(Answer::Yes, Reason::Partial),
        Source::Baseline => Judged::new(Answer::No, Reason::Baseline),
        Source::Call => Judged::new(Answer::No, Reason::Call),
    }
}

/// §5's first question, "has the target converged on its author's current
/// document?" (§2.17): the premises, then the author, then the comparison
/// of the report's `observed` with the author's version by value. No is the
/// finding.
#[must_use]
pub fn converged(t: &TargetReading<'_>, a: &AuthorReading) -> Judged {
    use Answer::{NotYet, Unobservable};
    let r = match converging(t, a.presence) {
        Ok((r, _)) => r,
        Err(j) => return j,
    };
    let current = match a.current {
        Current::NotRead => return Judged::new(Unobservable, Reason::AuthorNotRead),
        Current::Incomplete => return Judged::new(Unobservable, Reason::AuthorReadIncomplete),
        Current::Silent => return Judged::new(Unobservable, Reason::AuthorSilent),
        Current::Put(s) | Current::Delete(s) => s,
    };
    let (Some(observed), Some(outcome)) = (&r.observed, r.outcome) else {
        return Judged::new(NotYet, Reason::NotActed);
    };
    compared(&observed.stamp, &current, outcome)
}

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

    fn st(time: u64, id: &str) -> Stamp {
        Stamp::parse(time, id).expect("a stamp")
    }

    fn put(time: u64, id: &str) -> Sample {
        Sample {
            via: Via::Owner,
            mutation: Mutation::Put,
            stamp: Some(st(time, id)),
            revision: Some(time),
            content: Some(Content::of_json(&serde_json::json!({"revision": time}))),
        }
    }

    #[test]
    fn stamps_read_as_zenoh_writes_them() {
        assert_eq!(
            parse_stamp("7386690599959157260/33"),
            Some(st(7_386_690_599_959_157_260, "33"))
        );
        assert_eq!(st(7, "1bc0").to_string(), "7/1bc0");
        assert_eq!(parse_stamp("0/1"), Some(st(0, "1")));
        assert_eq!(
            parse_stamp(&format!("{}/1", u64::MAX)),
            Some(st(u64::MAX, "1"))
        );
        for bad in [
            "",
            "1",
            "/1",
            "1/",
            "01/1",
            "1/01",
            "1/A",
            "+1/1",
            "1/0",
            "18446744073709551616/1",
            "1/1/1",
            " 1/1",
        ] {
            assert_eq!(parse_stamp(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn a_report_serializes_as_the_schema_names_it() {
        let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
        assert_eq!(
            t.report().to_json(),
            serde_json::json!({"key": "zk2/a/b/i.v1/state/x", "source": "baseline"})
        );
        assert!(matches!(t.observe(put(100, "a1")), Step::Act(_)));
        t.finish(Ended::Done);
        let v = t.report().to_json();
        assert_eq!(
            v,
            serde_json::json!({
                "key": "zk2/a/b/i.v1/state/x",
                "source": "desired",
                "in_force": {"stamp": "100/a1", "revision": 100},
                "observed": {"stamp": "100/a1", "revision": 100},
                "outcome": "converged",
            })
        );
        let back: Report = serde_json::from_value(v.clone()).expect("serde reads it back");
        assert_eq!(&back, t.report());
        assert_eq!(Report::from_json(&v).as_ref(), Ok(t.report()));
        assert!(t.report().check().is_empty());
    }

    #[test]
    fn every_report_the_machine_makes_is_consistent() {
        let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
        let mut seen = Vec::new();
        let steps = vec![
            put(100, "a1"),
            put(200, "a1"),
            Sample {
                mutation: Mutation::Delete,
                revision: None,
                ..put(300, "a1")
            },
            Sample {
                via: Via::Archive,
                ..put(400, "b2")
            },
        ];
        for (i, s) in steps.into_iter().enumerate() {
            assert!(
                matches!(t.observe(s), Step::Act(_)),
                "a new document is acted on"
            );
            // The same document again, under a later stamp, while the act runs.
            let again = Sample {
                stamp: s.stamp.map(|x| Stamp {
                    time: x.time + 1,
                    ..x
                }),
                ..s
            };
            assert_eq!(t.observe(again), Step::Held);
            let ended = match i % 3 {
                0 => Ended::Done,
                1 => Ended::Refused(Refusal::new(REACH)),
                _ => Ended::Failed(Refusal::new(APPLY)),
            };
            assert_eq!(
                t.finish(ended),
                Step::Adopted,
                "the held re-put is the same document"
            );
            seen.push(t.report().clone());
            t.call();
            seen.push(t.report().clone());
        }
        for r in &seen {
            assert!(r.check().is_empty(), "{r:?}: {:?}", r.check());
        }
    }

    #[test]
    fn numbers_compare_by_their_exact_value() {
        for (text, exact) in [
            ("0", "0"),
            ("-0", "0"),
            ("0.000", "0"),
            ("0e99", "0"),
            ("10", "1e1"),
            ("10.0", "1e1"),
            ("1e1", "1e1"),
            ("100E-1", "1e1"),
            ("1.5", "15e-1"),
            ("-0.25", "-25e-2"),
            ("9007199254740992", "9007199254740992e0"),
            ("9007199254740993", "9007199254740993e0"),
            ("18446744073709551617", "18446744073709551617e0"),
            ("1e+2", "1e2"),
        ] {
            assert_eq!(exact_number(text).as_deref(), Some(exact), "{text}");
        }
        for bad in ["", "-", "01", "1.", ".5", "+1", "1e", "1e+", "--1", "0x1"] {
            assert_eq!(exact_number(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn a_payload_and_its_decoded_value_compare_alike() {
        let same = |a: &str, b: &str| {
            Content::of_payload(a.as_bytes(), true) == Content::of_payload(b.as_bytes(), true)
        };
        assert!(same(
            r#"{"a":10,"b":[1,2]}"#,
            r#" { "b" : [1, 2.0], "a" : 1e1 } "#
        ));
        assert!(same(r#"{"s":"\u0041"}"#, r#"{"s":"A"}"#));
        assert!(!same(
            r#"{"revision":9007199254740992}"#,
            r#"{"revision":9007199254740993}"#
        ));
        assert!(!same(
            r#"{"revision":18446744073709551616}"#,
            r#"{"revision":18446744073709551617}"#
        ));
        assert!(!same(r#"{"x":0.1}"#, r#"{"x":0.10000000000000000555}"#));
        // Not strict JSON: byte for byte.
        assert!(same(r#"{"a":1e400}"#, r#"{"a":1e400}"#));
        assert!(!same(r#"{"a":1e400}"#, r#"{"a": 1e400}"#));
        assert!(!same(r#"{"a":1,"a":1}"#, r#"{"a":1}"#));
        for text in [
            r#"{"mode":"run","rate_hz":10.0,"revision":1}"#,
            r#"{"revision":9007199254740993,"x":[-0.5,true,null,"é"]}"#,
        ] {
            let v = crate::strict::parse_json(text).expect("strict JSON");
            assert_eq!(
                Content::of_payload(text.as_bytes(), true),
                Content::of_json(&v),
                "{text}"
            );
        }
        assert_ne!(
            Content::of_payload(b"{}", false),
            Content::of_payload(b"{ }", false),
            "a payload that is not JSON compares byte for byte"
        );
    }

    #[test]
    fn a_decoded_value_and_its_text_agree_where_the_text_says() {
        let of_json = |v: Value| Content::of_json(&serde_json::json!({ "x": v }));
        let of_text = |t: &str| Content::of_payload(format!(r#"{{"x":{t}}}"#).as_bytes(), true);
        // One value: a large integral float and its integer's text.
        assert_eq!(
            of_json(serde_json::json!(1e20)),
            of_text("100000000000000000000")
        );
        assert_eq!(of_json(serde_json::json!(1e20)), of_text("1e20"));
        assert_eq!(of_json(serde_json::json!(1e300)), of_text("1e300"));
        assert_eq!(
            of_json(serde_json::json!(1e300)),
            of_text(&format!("1{}", "0".repeat(300)))
        );
        assert_eq!(of_json(serde_json::json!(-0.0)), of_text("0"));
        assert_eq!(of_json(serde_json::json!(0)), of_text("-0.0"));
        assert_eq!(of_json(serde_json::json!(0.1)), of_text("0.1"));
        assert_eq!(
            of_json(serde_json::json!(9_007_199_254_740_993_u64)),
            of_text("9007199254740993")
        );
        // Two values: the text's exact value, never its double's.
        assert_ne!(
            of_json(serde_json::json!(0.1)),
            of_text("0.10000000000000000555")
        );
        assert_ne!(
            of_json(serde_json::json!(9_007_199_254_740_992_u64)),
            of_text("9007199254740993")
        );
        assert_ne!(
            of_json(serde_json::json!(1e20)),
            of_text("100000000000000000001")
        );
    }

    #[test]
    fn a_held_version_is_remembered_only_once_it_starts() {
        let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
        assert!(matches!(t.observe(put(100, "a1")), Step::Act(_)));
        assert_eq!(t.observe(put(50, "b2")), Step::Held);
        assert_eq!(t.remembered(0xb2), None, "held waiting, not acted on");
        assert_eq!(t.remembered(0xa1), Some(100), "the running act counts");
        assert!(matches!(t.finish(Ended::Done), Step::Act(_)));
        assert_eq!(t.remembered(0xb2), Some(50));
        t.finish(Ended::Done);
        // An adoption counts as an act does.
        let again = Sample {
            content: put(50, "b2").content,
            revision: Some(50),
            ..put(70, "b2")
        };
        assert_eq!(t.observe(again), Step::Adopted);
        assert_eq!(t.remembered(0xb2), Some(70));
        assert_eq!(t.observe(put(60, "b2")), Step::Older);
    }

    #[test]
    fn finite_is_by_rounding() {
        let with = |n: &str| format!(r#"{{"source":"baseline","x":{n}}}"#);
        assert!(decode(with("1.7976931348623158e308").as_bytes()).is_ok());
        for n in ["1.7976931348623159e308", "1e400", "-1e400"] {
            assert!(
                matches!(decode(with(n).as_bytes()), Err(Unreadable::Json(_))),
                "{n}"
            );
        }
        // Depth (0.2): the report's object at depth 1, then arrays.
        let nested = |n: usize| {
            format!(
                r#"{{"source":"baseline","x":{}{}}}"#,
                "[".repeat(n),
                "]".repeat(n)
            )
        };
        assert!(decode(nested(MAX_DEPTH - 1).as_bytes()).is_ok());
        assert!(matches!(
            decode(nested(MAX_DEPTH).as_bytes()),
            Err(Unreadable::Json(_))
        ));
        assert!(matches!(
            decode(nested(100_000).as_bytes()),
            Err(Unreadable::Json(_))
        ));
        // A document past the depth compares byte for byte; one at it, by
        // its canonical form.
        let deep = |n: usize, ws: &str| format!("{}{ws}{}", "[".repeat(n), "]".repeat(n));
        assert_eq!(
            Content::of_payload(deep(MAX_DEPTH, " ").as_bytes(), true),
            Content::of_payload(deep(MAX_DEPTH, "").as_bytes(), true)
        );
        assert_ne!(
            Content::of_payload(deep(MAX_DEPTH + 1, " ").as_bytes(), true),
            Content::of_payload(deep(MAX_DEPTH + 1, "").as_bytes(), true)
        );
        let big = format!("1{}", "0".repeat(400));
        assert!(matches!(
            decode(with(&big).as_bytes()),
            Err(Unreadable::Json(_))
        ));
    }

    /// Text 0.3, F-181: a revision reads by its exact value, in a report's
    /// text and in a document's.
    #[test]
    fn a_revision_reads_by_its_exact_value() {
        let rep = |r: &str| {
            format!(
                r#"{{"key":"zk2/a/b/i.v1/state/x","source":"desired","in_force":{{"stamp":"1/a","revision":{r}}},"observed":{{"stamp":"1/a","revision":{r}}},"outcome":"converged"}}"#
            )
        };
        let observed = |r: &str| decode(rep(r).as_bytes()).map(|x| x.observed.unwrap().revision);
        assert_eq!(observed("18446744073709551615.0"), Ok(Some(u64::MAX)));
        assert_eq!(observed("30e-1"), Ok(Some(3)));
        assert_eq!(observed("-0.0"), Ok(Some(0)));
        assert_eq!(observed("1e19"), Ok(Some(10_000_000_000_000_000_000)));
        assert!(matches!(
            observed("18446744073709551616.0"),
            Err(Unreadable::RevisionRange(_))
        ));
        assert!(matches!(observed("1e400"), Err(Unreadable::Json(_))));
        assert!(
            matches!(observed("1e99999999999999999999"), Err(Unreadable::Json(_))),
            "never finite: not strict JSON, before the schema"
        );
        assert!(matches!(
            exact_revision("1e99999999999999999999"),
            Some(RevisionRead::TooLarge)
        ));
        assert!(exact_revision("1e-99999999999999999999").is_none());
        assert!(matches!(observed("1.5"), Err(Unreadable::Schema(_))));
        assert!(matches!(observed("-1"), Err(Unreadable::Schema(_))));
        // A decoded value holds the double: 2^64 exactly.
        let v: Value = serde_json::from_str(&rep("18446744073709551615.0")).unwrap();
        assert!(matches!(
            Report::from_json(&v),
            Err(Unreadable::RevisionRange(_))
        ));
        assert_eq!(
            revision_of_text(br#"{"revision": 3.0, "mode": "run"}"#),
            Some(3)
        );
        assert_eq!(
            revision_of_text(br#"{"revision": 18446744073709551615.0}"#),
            Some(u64::MAX)
        );
        for none in [
            &br#"{"revision": 1.5}"#[..],
            br#"{"revision": "1"}"#,
            br#"{"revision": 18446744073709551616}"#,
            br#"[1]"#,
            br#"{"rev": 1}"#,
            b"not json",
        ] {
            assert_eq!(
                revision_of_text(none),
                None,
                "{}",
                String::from_utf8_lossy(none)
            );
        }
        assert_eq!(
            revision_of_value(&serde_json::json!({"revision": "18446744073709551615"})),
            Some(u64::MAX),
            "protobuf's JSON mapping writes a 64-bit field as a string"
        );
        assert_eq!(
            revision_of_value(&serde_json::json!({"revision": 7})),
            Some(7)
        );
        assert_eq!(
            revision_of_value(&serde_json::json!({"revision": "x"})),
            None
        );
    }

    #[test]
    fn an_id_forgotten_beyond_sixteen_is_read_as_new() {
        let mut t = Target::new(Some("zk2/a/b/i.v1/state/x".into()));
        let ids: Vec<String> = (1..=17).map(|i| format!("{i:x}")).collect();
        for (n, id) in ids.iter().enumerate() {
            let s = Sample {
                revision: Some(n as u64),
                content: Some(Content::of_json(&serde_json::json!({"revision": n}))),
                ..put(500, id)
            };
            assert!(matches!(t.observe(s), Step::Act(_)), "{id}");
            t.finish(Ended::Done);
        }
        // The second id is the sixteenth most recent: still remembered.
        assert_eq!(t.remembered(2), Some(500));
        assert_eq!(t.observe(put(400, "2")), Step::Older);
        assert_eq!(t.observe(put(500, "2")), Step::SameVersion);
        // The first is the seventeenth: forgotten, so new.
        assert_eq!(t.remembered(1), None);
        assert!(matches!(t.observe(put(400, "1")), Step::Act(_)));
    }
}