zenkey-model 0.24.0

zk2 keys and contracts without a Zenoh session: the key grammar, the contract authoring format, canonical form, fingerprints and bundles
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
//! `config.v1`: changing a running service's configuration
//! (`spec/profiles/config/v1.md`, #768).
//!
//! The profile's session-free half: the wire types of its standard contract
//! (§3), the validators every owner refuses with (§2.5, §2.10, §2.13,
//! §2.18), the window (§2.8), redaction (§2.15), and [`Owner`], a pure
//! state machine of one owner's configuration (§2.6 to §2.17), driven by
//! explicit calls, device results and instants, which the runtime wraps.
//!
//! ```text
//! validate_set(schema, facts, group, req)  ─▶ Admitted │ Refusal{code, field, app}      §2.5 rows 0, 1, 3–11
//! validate_control(op, facts, req)         ─▶ ()       │ Refusal                        §2.10, §2.13
//! decode_set(body), decode_control(body)   ─▶ the request │ Refusal: outside its type, before row 1 (0.3)
//! check_desired(schema, doc)               ─▶ ()       │ DesiredRefusal{code, group, parameter}   §2.18
//! window(confirm_s, floor_s), deadline(t, w)                                            §2.8
//! log_request, device_detail                                                            §2.15
//!
//! Owner::set / confirm / cancel / extend ─▶ Step::Done{reply, events} │ Step::Act(Apply │ Undo)
//! Owner::due(now)                        ─▶ the act owed at now: the deadline's undo, or a reach apply
//! Owner::finish(now, DeviceResult)       ─▶ the act's outcome: the reply it owed, the events, or a next act
//! Owner::persist_plan / persisted        ─▶ the last change into the persisted layer
//! Owner::view / status                   ─▶ ConfigView │ ConfigStatus, its projection (§2.19)
//! Owner::converge(doc)                   ─▶ Wait │ Refused │ Set{group, request} │ Converged   §2.18
//! Owner::published(now)                  ─▶ the change events of the last hour, for the next instance §2.17
//! device_words(schema, act, words)       ─▶ the device's words as a log line may carry them    §2.15
//! ```
//!
//! There is no I/O and no clock here. The runtime receives calls, performs
//! each [`Act`] on its device, writes the persisted layer, keeps the timers
//! [`Owner::next_due`] names, and puts what [`Owner::view`],
//! [`Owner::status`] and the events say.
//!
//! [`v2`] is `config.v2`'s half: the schema declared in each adopter's
//! contract, one packed record, and an owner that runs this one.

use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;

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

pub mod v2;

/// The profile's id, which is also its standard contract's interface id.
pub const PROFILE: &str = "config.v1";

/// The standard contract's interface id (§3).
pub const IFACE: &str = "config.v1";

/// The read-back's template (§2.3): `state/view`.
pub const VIEW: &str = "view";
/// The compact status's template (§2.19): `state/status`.
pub const STATUS: &str = "status";
/// The set operation's template (§2.5): `@op/set/{group}`.
pub const SET: &str = "set/{group}";
/// `@op/confirm` (§2.10).
pub const CONFIRM: &str = "confirm";
/// `@op/cancel` (§2.10).
pub const CANCEL: &str = "cancel";
/// `@op/extend` (§2.10).
pub const EXTEND: &str = "extend";
/// `@op/persist` (§2.13), optional.
pub const PERSIST: &str = "persist";
/// The change event's template (§2.17): `events/change/<occurrence>`.
pub const CHANGE: &str = "change";

/// The view's and the status's horizon, their `freshness.ttl_s` (§2.3).
pub const TTL: Duration = Duration::from_secs(60);
/// The owner's bound between two confirmations of either (`freshness.v1`
/// §2.4).
pub const REFRESH: Duration = Duration::from_secs(30);
/// The contract's bound on a schema's groups, `set/{group}`'s cardinality
/// (§2.2).
pub const MAX_GROUPS: usize = 16;
/// How long an owner keeps an idempotency key's first answer (§2.14).
pub const KEY_HELD: Duration = Duration::from_secs(300);
/// The change event's rate, per [`RATE_PERIOD`] (§2.17).
pub const RATE: usize = 600;
/// The change event's rate period, an hour (§2.17, core §2.7).
pub const RATE_PERIOD: Duration = Duration::from_secs(3600);
/// What a log line writes for a sensitive value (§2.15).
pub const REDACTED: &str = "<redacted>";
/// A token's longest form, in characters (§2.6).
pub const MAX_TOKEN: usize = 64;
/// An idempotency key's longest form, in characters (§2.14).
pub const MAX_KEY: usize = 128;

// --- vocabulary (§4) ----------------------------------------------------------

/// A group's class (§2.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Class {
    /// Takes effect at once; a `set` answers the read-back after the apply.
    Hot,
    /// Decides whether the owner reaches the bus: a window or a join is
    /// required, and the reply goes before the apply.
    Reach,
    /// What the owner's transport was started against: refused at runtime.
    Contract,
}

impl Class {
    /// The wire's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Hot => "hot",
            Self::Reach => "reach",
            Self::Contract => "contract",
        }
    }
}

/// Where a running value came from (§2.3).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
    /// The owner's built-in default.
    Default,
    /// Its startup file.
    File,
    /// Its persisted layer (§2.13).
    Overlay,
    /// A change in this instance.
    Runtime,
}

impl Source {
    /// The wire's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::File => "file",
            Self::Overlay => "overlay",
            Self::Runtime => "runtime",
        }
    }
}

/// How a change ended (§2.17).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Outcome {
    /// Applied without a window, and permanent at once.
    Applied,
    /// A pending change kept by `confirm`.
    Confirmed,
    /// Undone: by `cancel`, at its deadline, or after its apply failed.
    RolledBack,
    /// Its undo failed: the read-back is the truth.
    Partial,
}

impl Outcome {
    /// The wire's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Applied => "applied",
            Self::Confirmed => "confirmed",
            Self::RolledBack => "rolled-back",
            Self::Partial => "partial",
        }
    }
}

/// `ConfigError`'s code, the `app` detail of every operation (§2.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ErrorCode {
    /// A contract group: set it in the startup configuration and restart.
    RestartRequired,
    /// The device refused; its words, when they may be carried, in `detail`.
    DeviceRefused,
}

impl ErrorCode {
    /// The wire's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::RestartRequired => "restart-required",
            Self::DeviceRefused => "device-refused",
        }
    }
}

/// Which document a control operation's reply carries (§2.10).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Answer {
    /// The read-back, the default.
    #[default]
    View,
    /// The compact status (§2.19).
    Status,
}

/// What an owner did with the last desired document it acted on (§2.18).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DesiredOutcome {
    /// Every value it names is the running value.
    Converged,
    /// Refused whole, before anything applied.
    Refused,
    /// A `set` made to converge it was refused.
    Failed,
}

/// Why a desired document was not converged (§2.18).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DesiredCode {
    /// It names a reach group.
    #[serde(rename = "reach")]
    Reach,
    /// It names a contract group.
    #[serde(rename = "contract")]
    Contract,
    /// It names a sensitive parameter.
    #[serde(rename = "sensitive")]
    Sensitive,
    /// A group or a parameter the schema does not declare.
    #[serde(rename = "not_found")]
    NotFound,
    /// A value of the wrong kind or out of bounds.
    #[serde(rename = "invalid_request")]
    InvalidRequest,
    /// A group outside the allowlist.
    #[serde(rename = "unavailable")]
    Unavailable,
    /// For `failed`: the event's rate was spent.
    #[serde(rename = "busy")]
    Busy,
    /// For `failed`: the device refused.
    #[serde(rename = "device-refused")]
    DeviceRefused,
}

impl DesiredCode {
    /// The wire's token.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Reach => "reach",
            Self::Contract => "contract",
            Self::Sensitive => "sensitive",
            Self::NotFound => "not_found",
            Self::InvalidRequest => "invalid_request",
            Self::Unavailable => "unavailable",
            Self::Busy => "busy",
            Self::DeviceRefused => "device-refused",
        }
    }
}

// --- the schema (§2.2) ----------------------------------------------------------

/// A parameter's kind, tagged by `kind` on the wire (§2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "lowercase")]
pub enum Kind {
    /// `true` or `false`.
    Bool,
    /// A signed 64-bit integer, with optional inclusive bounds and a unit.
    Integer {
        /// The smallest value accepted, inclusive.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        min: Option<i64>,
        /// The largest value accepted, inclusive.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        max: Option<i64>,
        /// A word for a person: `s`, `By`, `Hz`.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        unit: Option<String>,
    },
    /// Any string.
    Text,
}

/// Why a JSON value is not one of a kind's (§2.5).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Misfit {
    /// Not a value of the kind: `1` for a bool, `2.0` for an integer, `null`.
    Kind,
    /// An integer below the declared minimum.
    Below(i64),
    /// An integer above the declared maximum.
    Above(i64),
    /// An integer beyond the signed 64-bit range.
    Range,
}

impl Kind {
    /// The kind's name on the wire.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Bool => "bool",
            Self::Integer { .. } => "integer",
            Self::Text => "text",
        }
    }

    /// Reads `v` as a value of this kind, within its bounds (§2.5). An
    /// integer is a JSON number written without a fraction or an exponent.
    ///
    /// # Errors
    ///
    /// The [`Misfit`].
    pub fn check(&self, v: &Json) -> Result<Value, Misfit> {
        match (self, v) {
            (Self::Bool, Json::Bool(b)) => Ok(Value::Bool(*b)),
            (Self::Text, Json::String(s)) => Ok(Value::Text(s.clone())),
            (Self::Integer { min, max, .. }, Json::Number(n)) => {
                let Some(i) = n.as_i64() else {
                    return Err(if n.is_u64() {
                        Misfit::Range
                    } else {
                        Misfit::Kind
                    });
                };
                if let Some(m) = min
                    && i < *m
                {
                    return Err(Misfit::Below(*m));
                }
                if let Some(m) = max
                    && i > *m
                {
                    return Err(Misfit::Above(*m));
                }
                Ok(Value::Integer(i))
            }
            _ => Err(Misfit::Kind),
        }
    }
}

/// One parameter a group declares (§2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ParamDecl {
    /// Its name, unique in its group.
    pub name: String,
    /// Its kind.
    #[serde(flatten)]
    pub kind: Kind,
    /// One line for a person.
    pub description: String,
    /// Write-only (§2.15).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub sensitive: bool,
}

/// One group a schema declares (§2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroupDecl {
    /// Its name, the `{group}` of `@op/set/{group}`.
    pub name: String,
    /// Its class (§2.4).
    pub class: Class,
    /// One line for a person.
    pub description: String,
    /// Whether the startup allowlist lets a `set` reach it (§2.16).
    pub writable: bool,
    /// Its parameters, in the owner's order.
    pub parameters: Vec<ParamDecl>,
}

impl GroupDecl {
    /// The parameter by name, if declared.
    #[must_use]
    pub fn parameter(&self, name: &str) -> Option<&ParamDecl> {
        self.parameters.iter().find(|p| p.name == name)
    }

    fn is_sensitive(&self, name: &str) -> bool {
        self.parameter(name).is_none_or(|p| p.sensitive)
    }
}

/// An owner's schema: its groups, as the view serves them (§2.2).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Schema {
    /// The groups, in the owner's order.
    pub groups: Vec<GroupDecl>,
}

impl Schema {
    /// The group by name, if declared. Names compare exactly.
    #[must_use]
    pub fn group(&self, name: &str) -> Option<&GroupDecl> {
        self.groups.iter().find(|g| g.name == name)
    }

    /// The schema a view serves, without its values: what a tool checks a
    /// change against before it sends it (§2.5).
    #[must_use]
    pub fn of_view(view: &ConfigView) -> Self {
        Self {
            groups: view
                .groups
                .iter()
                .map(|g| GroupDecl {
                    name: g.name.clone(),
                    class: g.class,
                    description: g.description.clone(),
                    writable: g.writable,
                    parameters: g
                        .parameters
                        .iter()
                        .map(|p| ParamDecl {
                            name: p.name.clone(),
                            kind: p.kind.clone(),
                            description: p.description.clone(),
                            sensitive: p.sensitive,
                        })
                        .collect(),
                })
                .collect(),
        }
    }
}

// --- values and time ------------------------------------------------------------------

/// One parameter's value, untagged on the wire: the kind says which (§3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Value {
    /// A `bool`'s.
    Bool(bool),
    /// An `integer`'s.
    Integer(i64),
    /// A `text`'s.
    Text(String),
}

impl fmt::Display for Value {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Bool(b) => write!(f, "{b}"),
            Self::Integer(i) => write!(f, "{i}"),
            Self::Text(t) => write!(f, "{t:?}"),
        }
    }
}

/// An instant on the owner's clock, in milliseconds since the Unix epoch
/// (§2.8). Negative before 1970.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Time(i64);

impl Time {
    /// The instant `ms` milliseconds after the Unix epoch.
    #[must_use]
    pub const fn from_millis(ms: i64) -> Self {
        Self(ms)
    }

    /// Milliseconds since the Unix epoch.
    #[must_use]
    pub const fn millis(self) -> i64 {
        self.0
    }

    /// The instant `secs` seconds after the epoch, to the millisecond.
    #[must_use]
    pub fn from_secs_f64(secs: f64) -> Self {
        Self((secs * 1000.0).round() as i64)
    }

    /// This instant plus `d`, saturating.
    #[must_use]
    pub fn plus(self, d: Duration) -> Self {
        Self(
            self.0
                .saturating_add(i64::try_from(d.as_millis()).unwrap_or(i64::MAX)),
        )
    }

    /// This instant plus `secs` seconds, saturating.
    #[must_use]
    pub fn plus_secs(self, secs: u64) -> Self {
        self.plus(Duration::from_secs(secs))
    }

    /// The first whole second at or after this instant: itself on a whole
    /// second, else the next one (`config.v2` §2.8, which rounds a deadline
    /// and an `apply_at` up so that a window is never shorter than asked).
    #[must_use]
    pub fn ceil_second(self) -> Self {
        let r = self.0.rem_euclid(1000);
        if r == 0 {
            self
        } else {
            Self(self.0.saturating_add(1000 - r))
        }
    }

    /// Whether `self` is less than `d` after `earlier`.
    fn within(self, earlier: Self, d: Duration) -> bool {
        i128::from(self.0) - i128::from(earlier.0)
            < i128::try_from(d.as_millis()).unwrap_or(i128::MAX)
    }

    /// The owner's spelling (§2.8): RFC 3339 in UTC,
    /// `YYYY-MM-DDTHH:MM:SS.sssZ`, always three fraction digits.
    #[must_use]
    pub fn rfc3339(self) -> String {
        let days = self.0.div_euclid(86_400_000);
        let ms = self.0.rem_euclid(86_400_000);
        let (y, m, d) = civil_from_days(days);
        let (h, rest) = (ms / 3_600_000, ms % 3_600_000);
        let (mi, rest) = (rest / 60_000, rest % 60_000);
        let (s, frac) = (rest / 1000, rest % 1000);
        format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}.{frac:03}Z")
    }

    /// Reads any RFC 3339 date-time (§2.8): `Z` or an offset, a fraction of
    /// any length, kept to the millisecond (truncated). `None` when it is
    /// not one.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        let b = s.as_bytes();
        let num = |r: std::ops::Range<usize>| -> Option<i64> {
            let t = s.get(r)?;
            if t.is_empty() || !t.bytes().all(|c| c.is_ascii_digit()) {
                return None;
            }
            t.parse().ok()
        };
        if b.len() < 20
            || b[4] != b'-'
            || b[7] != b'-'
            || !matches!(b[10], b'T' | b't')
            || b[13] != b':'
            || b[16] != b':'
        {
            return None;
        }
        let (y, mo, d) = (num(0..4)?, num(5..7)?, num(8..10)?);
        let (h, mi, sec) = (num(11..13)?, num(14..16)?, num(17..19)?);
        if !(1..=12).contains(&mo)
            || d < 1
            || d > days_in_month(y, mo)
            || h > 23
            || mi > 59
            || sec > 60
        {
            return None;
        }
        let mut i = 19;
        let mut ms = 0;
        if b.get(i) == Some(&b'.') {
            let start = i + 1;
            i = start;
            while b.get(i).is_some_and(u8::is_ascii_digit) {
                i += 1;
            }
            if i == start {
                return None;
            }
            let digits = &s[start..i];
            let three: String = digits.chars().chain("000".chars()).take(3).collect();
            ms = three.parse::<i64>().ok()?;
        }
        let offset_min = match b.get(i)? {
            b'Z' | b'z' if i + 1 == b.len() => 0,
            sign @ (b'+' | b'-') if i + 6 == b.len() && b[i + 3] == b':' => {
                let (oh, om) = (num(i + 1..i + 3)?, num(i + 4..i + 6)?);
                if oh > 23 || om > 59 {
                    return None;
                }
                let o = oh * 60 + om;
                if *sign == b'-' { -o } else { o }
            }
            _ => return None,
        };
        let days = days_from_civil(y, mo, d);
        let secs = days * 86_400 + h * 3600 + mi * 60 + sec - offset_min * 60;
        Some(Self(secs * 1000 + ms))
    }
}

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

fn days_in_month(y: i64, m: i64) -> i64 {
    match m {
        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
        4 | 6 | 9 | 11 => 30,
        _ if (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 => 29,
        _ => 28,
    }
}

/// Days since 1970-01-01 of a proleptic Gregorian date (H. Hinnant's
/// `days_from_civil`).
fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
    let y = if m <= 2 { y - 1 } else { y };
    let era = y.div_euclid(400);
    let yoe = y - era * 400;
    let mp = (m + 9) % 12;
    let doy = (153 * mp + 2) / 5 + d - 1;
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
    era * 146_097 + doe - 719_468
}

/// The date of a day count since 1970-01-01 (`civil_from_days`).
fn civil_from_days(z: i64) -> (i64, i64, i64) {
    let z = z + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = yoe + era * 400 + i64::from(m <= 2);
    (y, m, d)
}

/// The window of a `confirm_s`, raised to the floor: `max(confirm_s,
/// floor_s)` seconds (§2.8).
#[must_use]
pub fn window(confirm_s: u64, floor_s: u64) -> u64 {
    confirm_s.max(floor_s)
}

/// The deadline of a window counted from `received` (§2.8).
#[must_use]
pub fn deadline(received: Time, window_s: u64) -> Time {
    received.plus_secs(window_s)
}

// --- the wire types (§3) --------------------------------------------------------------

/// One parameter as the view shows it (§2.3): its declaration, and what the
/// owner runs with. A sensitive parameter never carries `value` or
/// `startup`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Parameter {
    /// Its name.
    pub name: String,
    /// Its kind, with an integer's bounds and unit.
    #[serde(flatten)]
    pub kind: Kind,
    /// One line for a person.
    pub description: String,
    /// Write-only (§2.15).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub sensitive: bool,
    /// The running value; absent when sensitive or unknown.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub value: Option<Value>,
    /// Where the running value came from.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<Source>,
    /// What a restart would run with, when it differs from a known running
    /// value; never for a sensitive parameter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub startup: Option<Value>,
}

/// One group as the view shows it (§2.2).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct GroupView {
    /// Its name.
    pub name: String,
    /// Its class.
    pub class: Class,
    /// One line for a person.
    pub description: String,
    /// Whether the allowlist lets a `set` reach it (§2.16).
    pub writable: bool,
    /// Its parameters, in the owner's order.
    pub parameters: Vec<Parameter>,
}

/// The pending change, as the view and the status show it (§2.7, §2.9).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Pending {
    /// Its token.
    pub token: String,
    /// Its groups, in the order they first joined.
    pub groups: Vec<String>,
    /// When its undo runs, on the owner's clock (§2.8).
    pub deadline: String,
    /// Whether every group of it is applied.
    pub applied: bool,
}

/// The last change made permanent in this instance (§2.6).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LastChange {
    /// Its token.
    pub token: String,
    /// Its groups.
    pub groups: Vec<String>,
}

/// Why a desired document was not converged, and where (§2.18).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DesiredRefusal {
    /// The code.
    pub code: DesiredCode,
    /// The group.
    pub group: String,
    /// The parameter, for a parameter's check.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parameter: Option<String>,
}

/// What the owner did with the last desired document it acted on (§2.18).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DesiredReport {
    /// The document's revision.
    pub observed_revision: u64,
    /// Converged, refused or failed.
    pub outcome: DesiredOutcome,
    /// Why, for refused and failed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub refusal: Option<DesiredRefusal>,
}

/// The read-back, `state/view` (§2.3).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigView {
    /// The owner's address, `<system>/<service>`.
    pub service: String,
    /// Its instance id.
    pub instance: String,
    /// The count of acts that moved its running values.
    pub revision: u64,
    /// Its floor, in seconds (§2.8).
    pub confirm_floor_s: u64,
    /// The pending change, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending: Option<Pending>,
    /// The last change, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_change: Option<LastChange>,
    /// The desired report, for an owner that converges desired state.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub desired: Option<DesiredReport>,
    /// The groups.
    pub groups: Vec<GroupView>,
}

/// The compact status, `state/status`: the view's projection (§2.19).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigStatus {
    /// The instance id.
    pub instance: String,
    /// The revision.
    pub revision: u64,
    /// The floor, in seconds.
    pub confirm_floor_s: u64,
    /// The pending change, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending: Option<Pending>,
    /// The last change, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_change: Option<LastChange>,
    /// The desired report, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub desired: Option<DesiredReport>,
    /// The values by group and name: no sensitive or unknown value, and no
    /// group left without one.
    pub values: BTreeMap<String, BTreeMap<String, Value>>,
}

impl ConfigStatus {
    /// The status a view projects to (§2.19).
    #[must_use]
    pub fn of(view: &ConfigView) -> Self {
        let mut values = BTreeMap::new();
        for g in &view.groups {
            let shown: BTreeMap<String, Value> = g
                .parameters
                .iter()
                .filter(|p| !p.sensitive)
                .filter_map(|p| p.value.clone().map(|v| (p.name.clone(), v)))
                .collect();
            if !shown.is_empty() {
                values.insert(g.name.clone(), shown);
            }
        }
        Self {
            instance: view.instance.clone(),
            revision: view.revision,
            confirm_floor_s: view.confirm_floor_s,
            pending: view.pending.clone(),
            last_change: view.last_change.clone(),
            desired: view.desired.clone(),
            values,
        }
    }
}

/// The body of `@op/set/{group}` (§2.5). Its values stay JSON until the
/// validator reads them against the schema, so a value of the wrong kind is
/// row 11's refusal, naming its parameter.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct SetRequest {
    /// Values for some parameters of the group.
    pub values: BTreeMap<String, Json>,
    /// The window, in seconds, at least 1.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirm_s: Option<u64>,
    /// The pending change's token, to join it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub token: Option<String>,
    /// The revision the caller read.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expected_revision: Option<u64>,
    /// A key that makes a retry return the first answer (§2.14).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub idempotency_key: Option<String>,
    /// Check, and answer the would-be view, touching nothing.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub dry_run: bool,
}

/// A reach `set`'s reply, before the apply (§2.9).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PendingReply {
    /// The change's token.
    pub token: String,
    /// When the group applies, on the owner's clock.
    pub apply_at: String,
    /// When the change rolls back unless confirmed.
    pub deadline: String,
}

/// The reply to a `set` (§2.9, §3): `{applied: ConfigView}` or `{pending:
/// PendingReply}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SetReply {
    /// The read-back after the apply, or a dry run's would-be read-back.
    Applied(Box<ConfigView>),
    /// A reach group's pending reply.
    Pending(PendingReply),
}

/// The body of `confirm`, `cancel`, `extend` and `persist` (§2.10).
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct ControlRequest {
    /// The change's token.
    pub token: String,
    /// For `extend` alone: the new window from now, in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub confirm_s: Option<u64>,
    /// The document the reply carries, the view by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub answer: Option<Answer>,
}

/// The reply to a control operation (§2.10): `{view: ConfigView}` or
/// `{status: ConfigStatus}`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ControlReply {
    /// The read-back after the act.
    View(Box<ConfigView>),
    /// The compact status after the act.
    Status(Box<ConfigStatus>),
}

/// One parameter a change set, in its event (§2.17).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Edit {
    /// Its group.
    pub group: String,
    /// Its name.
    pub parameter: String,
    /// Its value before the change; absent when unknown or redacted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub old: Option<Value>,
    /// The value the change set; absent when redacted.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub new: Option<Value>,
    /// A sensitive parameter's edit, with neither value.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub redacted: bool,
}

/// One change as it ended, `events/change/<occurrence>` (§2.17).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigChangeEvent {
    /// The owner's address.
    pub service: String,
    /// Its instance id.
    pub instance: String,
    /// The revision after the act that ended the change.
    pub revision: u64,
    /// The change's token.
    pub token: String,
    /// How it ended.
    pub outcome: Outcome,
    /// Its edits.
    pub edits: Vec<Edit>,
    /// The actor the `set` that started it claimed (core O7).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub actor: Option<String>,
    /// The request id it claimed.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub request_id: Option<String>,
    /// Where the call came from, best effort, unauthenticated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub claimed_source: Option<String>,
}

/// The `app` detail of every operation (§2.5).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConfigError {
    /// `restart-required` or `device-refused`.
    pub code: ErrorCode,
    /// For a person: the device's own words, when they may be carried.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub detail: Option<String>,
}

/// A desired document for a `config.v1` owner (§2.18). Its values stay JSON
/// until [`check_desired`] reads them.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct DesiredConfig {
    /// The author's revision.
    pub revision: u64,
    /// Values by group and parameter.
    pub values: BTreeMap<String, BTreeMap<String, Json>>,
}

// --- refusals ---------------------------------------------------------------------------

/// The core §5.2 code of a refusal this profile makes. `fanout_forbidden`
/// and `internal` are the runtime's.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Code {
    /// `invalid_request`.
    InvalidRequest,
    /// `not_found`.
    NotFound,
    /// `unavailable`, always with cause `config` here.
    Unavailable,
    /// `forbidden`.
    Forbidden,
    /// `busy`.
    Busy,
    /// `app`, with a [`ConfigError`].
    App,
}

impl Code {
    /// The error's code.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::InvalidRequest => "invalid_request",
            Self::NotFound => "not_found",
            Self::Unavailable => "unavailable",
            Self::Forbidden => "forbidden",
            Self::Busy => "busy",
            Self::App => "app",
        }
    }
}

/// What a refusal is about, as the fixtures name it.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Field {
    /// The key's `{group}`.
    Group,
    /// A member of the request, as a JSON pointer (RFC 6901).
    Member(String),
}

impl Field {
    /// `"group"`, or the pointer.
    #[must_use]
    pub fn as_str(&self) -> &str {
        match self {
            Self::Group => "group",
            Self::Member(p) => p,
        }
    }

    fn member(name: &str) -> Self {
        Self::Member(format!("/{name}"))
    }

    fn value(name: &str) -> Self {
        Self::Member(format!(
            "/values/{}",
            name.replace('~', "~0").replace('/', "~1")
        ))
    }
}

/// A refusal, before or after an act: the error's code, its `app`
/// detail, what it is about, and a message for a person that never carries
/// a sensitive value (§2.15).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refusal {
    /// The code.
    pub code: Code,
    /// The `ConfigError`, with [`Code::App`] alone.
    pub app: Option<ConfigError>,
    /// What the refusal is about: `None` for the owner's state or the
    /// operation.
    pub field: Option<Field>,
    /// For a person, never parsed.
    pub message: String,
}

impl Refusal {
    fn new(code: Code, field: Option<Field>, message: impl Into<String>) -> Self {
        Self {
            code,
            app: None,
            field,
            message: message.into(),
        }
    }

    fn app(code: ErrorCode, detail: Option<String>, message: impl Into<String>) -> Self {
        Self {
            code: Code::App,
            app: Some(ConfigError { code, detail }),
            field: Some(Field::Group),
            message: message.into(),
        }
    }

    fn busy(message: impl Into<String>) -> Self {
        Self::new(Code::Busy, None, message)
    }

    /// The error's cause: `config` for `unavailable`, else none.
    #[must_use]
    pub fn cause(&self) -> Option<&'static str> {
        (self.code == Code::Unavailable).then_some("config")
    }
}

impl fmt::Display for Refusal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code.as_str(), self.message)
    }
}

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

// --- the validators (§2.5, §2.10, §2.13, §2.18) ----------------------------------------

/// What a validator needs of the owner's state.
#[derive(Debug, Clone, Copy, Default)]
pub struct Facts<'a> {
    /// The revision.
    pub revision: u64,
    /// The pending change, if any.
    pub pending: Option<PendingFacts<'a>>,
    /// The last change, if any.
    pub last_change: Option<LastFacts<'a>>,
    /// Whether the owner has a persisted layer.
    pub persist: bool,
    /// Whether an act is in flight.
    pub in_flight: bool,
}

/// The pending change, as a validator reads it.
#[derive(Debug, Clone, Copy)]
pub struct PendingFacts<'a> {
    /// Its token.
    pub token: &'a str,
    /// Whether every group of it is applied.
    pub applied: bool,
    /// Whether its deadline has passed with its undo not yet run.
    pub deadline_passed: bool,
}

/// The last change, as `persist` reads it.
#[derive(Debug, Clone, Copy)]
pub struct LastFacts<'a> {
    /// Its token.
    pub token: &'a str,
    /// Whether it set a sensitive parameter.
    pub set_sensitive: bool,
}

/// A `set` that passed §2.5's rows 0, 1 and 3 to 11.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Admitted {
    /// The group's class.
    pub class: Class,
    /// The values, read against their kinds.
    pub values: BTreeMap<String, Value>,
    /// Whether it joins the pending change.
    pub joins: bool,
    /// Whether it is a dry run.
    pub dry_run: bool,
}

/// A control operation (§2.10, §2.13).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ControlOp {
    /// `confirm`.
    Confirm,
    /// `cancel`.
    Cancel,
    /// `extend`.
    Extend,
    /// `persist`.
    Persist,
}

impl ControlOp {
    /// The operation's template.
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Confirm => CONFIRM,
            Self::Cancel => CANCEL,
            Self::Extend => EXTEND,
            Self::Persist => PERSIST,
        }
    }
}

fn too_long(s: &str, max: usize) -> bool {
    s.is_empty() || s.chars().count() > max
}

/// Whether `v` is a `ParamValue`, the type of `SetRequest`'s values (§3):
/// a boolean, a string, or an integer as JSON Schema reads one, a number
/// with no fractional part. `2.0` and an integer beyond 64 bits are; row 11
/// then refuses them against the parameter's kind (§2.5, text 0.2, F-107).
fn is_param_value(v: &Json) -> bool {
    match v {
        Json::Bool(_) | Json::String(_) => true,
        Json::Number(n) => {
            n.is_i64()
                || n.is_u64()
                || n.as_f64()
                    .is_some_and(|f| f.is_finite() && f.fract() == 0.0)
        }
        _ => false,
    }
}

/// The request's own type, before row 1 (§2.5): its members in the
/// bytewise order of their names, `values` last, and in it the first value
/// outside `ParamValue` by name (text 0.2, F-107).
fn check_set_shape(req: &SetRequest) -> Result<(), Refusal> {
    if req.confirm_s == Some(0) {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("confirm_s")),
            "confirm_s is a window of at least 1 s",
        ));
    }
    if let Some(k) = &req.idempotency_key
        && too_long(k, MAX_KEY)
    {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("idempotency_key")),
            format!("an idempotency key is 1 to {MAX_KEY} characters"),
        ));
    }
    if let Some(t) = &req.token
        && too_long(t, MAX_TOKEN)
    {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("token")),
            format!("a token is 1 to {MAX_TOKEN} characters"),
        ));
    }
    if let Some((name, _)) = req.values.iter().find(|(_, v)| !is_param_value(v)) {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::value(name)),
            format!(
                "{name}: not a boolean, an integer or a string, so outside the request's type \
                 (SetRequest's ParamValue)"
            ),
        ));
    }
    Ok(())
}

/// A control request's own type, in the bytewise order of its members'
/// names, as §2.5 takes a set's (§2.10; text 0.3): `confirm_s` before
/// `token`. `answer` is its decode's.
fn check_control_shape(req: &ControlRequest) -> Result<(), Refusal> {
    if req.confirm_s == Some(0) {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("confirm_s")),
            "confirm_s is a window of at least 1 s",
        ));
    }
    if too_long(&req.token, MAX_TOKEN) {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("token")),
            format!("a token is 1 to {MAX_TOKEN} characters"),
        ));
    }
    Ok(())
}

/// Whether `v` is an unsigned integer as core §3.3 reads one: a JSON number
/// written without a fraction or an exponent, within the unsigned 64-bit
/// range. `30.0`, `3e1` and `2^64` are integers to JSON Schema, and not
/// this (text 0.3, F-115).
fn is_u64(v: &Json) -> bool {
    v.as_number().is_some_and(serde_json::Number::is_u64)
}

/// A request member's own check, before row 1 (§2.5, "A request outside its
/// type"; text 0.3, F-115): the member's JSON form against its type.
fn member_fits(name: &str, v: &Json) -> Result<(), Refusal> {
    let refuse = |why: String| {
        Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member(name)),
            why,
        ))
    };
    match name {
        "confirm_s" if !(is_u64(v) && v.as_u64() != Some(0)) => refuse(
            "confirm_s is a window of at least 1 s, an integer written without a fraction or an \
             exponent"
                .to_owned(),
        ),
        "expected_revision" if !is_u64(v) => refuse(
            "expected_revision is a revision, an unsigned integer written without a fraction or \
             an exponent"
                .to_owned(),
        ),
        "dry_run" if !v.is_boolean() => refuse("dry_run is true or false".to_owned()),
        "idempotency_key" if !v.as_str().is_some_and(|k| !too_long(k, MAX_KEY)) => {
            refuse(format!("an idempotency key is 1 to {MAX_KEY} characters"))
        }
        "token" if !v.as_str().is_some_and(|t| !too_long(t, MAX_TOKEN)) => {
            refuse(format!("a token is 1 to {MAX_TOKEN} characters"))
        }
        "answer" if !matches!(v.as_str(), Some("view" | "status")) => {
            refuse("answer is view or status".to_owned())
        }
        _ => Ok(()),
    }
}

/// Decodes a `set`'s body as a `SetRequest`, refusing a request outside its
/// type as §2.5 orders it, before row 1: its members in the bytewise order
/// of their names, `values` last, and in `values` the first value outside
/// `ParamValue` by name. A member it does not know is ignored (§3: each
/// type is an open object). `confirm_s` and `expected_revision` are read as
/// core §3.3 reads an integer, so `30.0` is outside the type, though a
/// `2.0` in `values` is a `ParamValue` row 11 refuses (text 0.3, F-115).
///
/// # Errors
///
/// The first [`Refusal`], `invalid_request` naming the member.
pub fn decode_set(body: &Json) -> Result<SetRequest, Refusal> {
    let Some(members) = body.as_object() else {
        return Err(Refusal::new(
            Code::InvalidRequest,
            None,
            "a SetRequest is a JSON object",
        ));
    };
    let mut names: Vec<&String> = members.keys().filter(|k| *k != "values").collect();
    names.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
    for name in names {
        member_fits(name, &members[name])?;
    }
    let Some(values) = members.get("values").and_then(Json::as_object) else {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("values")),
            "values is an object of parameter values",
        ));
    };
    let mut names: Vec<&String> = values.keys().collect();
    names.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
    if let Some(name) = names.into_iter().find(|n| !is_param_value(&values[*n])) {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::value(name)),
            format!(
                "{name}: not a boolean, an integer or a string, so outside the request's type \
                 (SetRequest's ParamValue)"
            ),
        ));
    }
    serde_json::from_value(body.clone())
        .map_err(|e| Refusal::new(Code::InvalidRequest, None, format!("not a SetRequest: {e}")))
}

/// Decodes a control operation's body as a `ControlRequest`, refusing one
/// outside its type in the bytewise order of its members' names (§2.10,
/// "as §2.5 says of a set"; text 0.3).
///
/// # Errors
///
/// The first [`Refusal`], `invalid_request` naming the member.
pub fn decode_control(body: &Json) -> Result<ControlRequest, Refusal> {
    let Some(members) = body.as_object() else {
        return Err(Refusal::new(
            Code::InvalidRequest,
            None,
            "a ControlRequest is a JSON object",
        ));
    };
    if !members.contains_key("token") {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("token")),
            format!("a token is 1 to {MAX_TOKEN} characters"),
        ));
    }
    let mut names: Vec<&String> = members.keys().collect();
    names.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
    for name in names {
        member_fits(name, &members[name])?;
    }
    serde_json::from_value(body.clone()).map_err(|e| {
        Refusal::new(
            Code::InvalidRequest,
            None,
            format!("not a ControlRequest: {e}"),
        )
    })
}

/// [`validate_set`] over a body as it arrived: [`decode_set`], then the
/// rows.
///
/// # Errors
///
/// The first [`Refusal`] that applies.
pub fn validate_set_json(
    schema: &Schema,
    facts: &Facts<'_>,
    group: &str,
    body: &Json,
) -> Result<Admitted, Refusal> {
    let req = decode_set(body)?;
    validate_set(schema, facts, group, &req)
}

/// [`validate_control`] over a body as it arrived: `persist`'s missing
/// persisted layer first (§2.13, row 1: before the request's type), then
/// [`decode_control`], then the rest.
///
/// # Errors
///
/// The first [`Refusal`] that applies.
pub fn validate_control_json(op: ControlOp, facts: &Facts<'_>, body: &Json) -> Result<(), Refusal> {
    if op == ControlOp::Persist && !facts.persist {
        return validate_control(op, facts, &ControlRequest::default());
    }
    let req = decode_control(body)?;
    validate_control(op, facts, &req)
}

fn in_flight() -> Refusal {
    Refusal::busy("an act is in flight on this service's device; call again once it ends")
}

fn misfit_message(p: &ParamDecl, why: Misfit, v: &Json) -> String {
    let unit = match &p.kind {
        Kind::Integer { unit: Some(u), .. } => format!(" {u}"),
        _ => String::new(),
    };
    let shown = if p.sensitive {
        String::new()
    } else {
        format!(", got {v}")
    };
    match why {
        Misfit::Kind => format!(
            "{}: expected a value of kind {}{shown}",
            p.name,
            p.kind.as_str()
        ),
        Misfit::Below(m) => format!("{}: below the minimum of {m}{unit}{shown}", p.name),
        Misfit::Above(m) => format!("{}: above the maximum of {m}{unit}{shown}", p.name),
        Misfit::Range => format!("{}: beyond the signed 64-bit range{shown}", p.name),
    }
}

/// §2.5's rows 3 to 11: what a `set` is refused for by the schema and the
/// state, before the rate, a reach join's deadline and the device.
fn check_rows(
    schema: &Schema,
    facts: &Facts<'_>,
    group: &str,
    req: &SetRequest,
) -> Result<Admitted, Refusal> {
    let Some(g) = schema.group(group) else {
        return Err(Refusal::new(
            Code::NotFound,
            Some(Field::Group),
            format!("no group {group:?}: the view names every group this service accepts"),
        ));
    };
    if !g.writable {
        return Err(Refusal::new(
            Code::Unavailable,
            Some(Field::Group),
            format!("group {group:?} is outside this service's startup allowlist"),
        ));
    }
    if let Some(p) = &facts.pending
        && (req.token.as_deref() != Some(p.token) || p.deadline_passed)
    {
        return Err(Refusal::busy(format!(
            "a change is pending on this service (token {}); confirm, cancel or extend it, or carry its token",
            p.token
        )));
    }
    if req.token.is_some() && facts.pending.is_none() {
        return Err(Refusal::new(
            Code::NotFound,
            Some(Field::member("token")),
            "no change is pending: the token names nothing",
        ));
    }
    if let Some(e) = req.expected_revision
        && e != facts.revision
    {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("expected_revision")),
            format!(
                "the change expects revision {e} and the view is at {}; read it back and decide again",
                facts.revision
            ),
        ));
    }
    if g.class == Class::Contract {
        return Err(Refusal::app(
            ErrorCode::RestartRequired,
            None,
            format!(
                "group {group:?} is part of what this service was started against; set it in its startup \
                 configuration and restart"
            ),
        ));
    }
    if req.token.is_some() && req.confirm_s.is_some() {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("confirm_s")),
            "a change joining a pending one takes its window; drop confirm_s (extend moves the deadline)",
        ));
    }
    if g.class == Class::Reach && req.confirm_s.is_none() && req.token.is_none() && !req.dry_run {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("confirm_s")),
            format!(
                "group {group:?} can cut the link this reply travels on; send it with a window (confirm_s) and \
                 confirm over the new link"
            ),
        ));
    }
    let mut values = BTreeMap::new();
    for (name, v) in &req.values {
        let Some(p) = g.parameter(name) else {
            return Err(Refusal::new(
                Code::NotFound,
                Some(Field::value(name)),
                format!("group {group:?} declares no parameter {name:?}"),
            ));
        };
        match p.kind.check(v) {
            Ok(value) => {
                values.insert(name.clone(), value);
            }
            Err(why) => {
                return Err(Refusal::new(
                    Code::InvalidRequest,
                    Some(Field::value(name)),
                    misfit_message(p, why, v),
                ));
            }
        }
    }
    Ok(Admitted {
        class: g.class,
        values,
        joins: req.token.is_some(),
        dry_run: req.dry_run,
    })
}

/// Checks a `set` as §2.5 orders it: the request's own type (row 0), an act
/// in flight (row 1), then rows 3 to 11. Row 2, an idempotency key the owner
/// holds, needs the keys, and rows 12 to 14 the rate, the deadline and the
/// device: [`Owner::set`] adds them. A tool runs this against a view before
/// it sends (§2.5, "A caller that checks first").
///
/// # Errors
///
/// The first [`Refusal`] that applies.
pub fn validate_set(
    schema: &Schema,
    facts: &Facts<'_>,
    group: &str,
    req: &SetRequest,
) -> Result<Admitted, Refusal> {
    check_set_shape(req)?;
    if facts.in_flight {
        return Err(in_flight());
    }
    check_rows(schema, facts, group, req)
}

/// Checks a control operation as §2.10 and §2.13 order it.
///
/// # Errors
///
/// The first [`Refusal`] that applies.
pub fn validate_control(
    op: ControlOp,
    facts: &Facts<'_>,
    req: &ControlRequest,
) -> Result<(), Refusal> {
    if op == ControlOp::Persist && !facts.persist {
        return Err(Refusal::new(
            Code::Unavailable,
            None,
            "this service has no persisted layer: persist is unavailable here",
        ));
    }
    check_control_shape(req)?;
    if facts.in_flight {
        return Err(in_flight());
    }
    let window_wrong = match op {
        ControlOp::Extend => req.confirm_s.is_none(),
        _ => req.confirm_s.is_some(),
    };
    if window_wrong {
        return Err(Refusal::new(
            Code::InvalidRequest,
            Some(Field::member("confirm_s")),
            if op == ControlOp::Extend {
                "extend carries confirm_s, the new window from now".to_owned()
            } else {
                format!("{} carries no confirm_s", op.as_str())
            },
        ));
    }
    if op == ControlOp::Persist {
        if let Some(p) = &facts.pending
            && p.token == req.token
        {
            return Err(Refusal::busy(format!(
                "change {} is still pending; confirm it first",
                p.token
            )));
        }
        let Some(last) = facts.last_change.filter(|l| l.token == req.token) else {
            return Err(Refusal::new(
                Code::NotFound,
                Some(Field::member("token")),
                "persist takes the last change's token, and nothing older",
            ));
        };
        if last.set_sensitive {
            return Err(Refusal::new(
                Code::Forbidden,
                Some(Field::member("token")),
                "the last change set a sensitive value, which is never written to the persisted layer",
            ));
        }
        return Ok(());
    }
    let Some(p) = facts.pending.filter(|p| p.token == req.token) else {
        return Err(Refusal::new(
            Code::NotFound,
            Some(Field::member("token")),
            "no pending change by this token",
        ));
    };
    if p.deadline_passed {
        return Err(Refusal::busy(
            "the change's deadline has passed and its undo is running; it can no longer be kept",
        ));
    }
    if op == ControlOp::Confirm && !p.applied {
        return Err(Refusal::busy(
            "the change is not applied yet; confirm it once the view shows it applied",
        ));
    }
    Ok(())
}

/// Checks a desired document (§2.18): `Ok` when the owner may converge it,
/// else the first problem, in the profile's order.
///
/// # Errors
///
/// The [`DesiredRefusal`].
pub fn check_desired(schema: &Schema, doc: &DesiredConfig) -> Result<(), DesiredRefusal> {
    let refuse = |code, group: &str, parameter: Option<&str>| DesiredRefusal {
        code,
        group: group.to_owned(),
        parameter: parameter.map(str::to_owned),
    };
    for (gname, params) in &doc.values {
        let Some(g) = schema.group(gname) else {
            return Err(refuse(DesiredCode::NotFound, gname, None));
        };
        match g.class {
            Class::Contract => return Err(refuse(DesiredCode::Contract, gname, None)),
            Class::Reach => return Err(refuse(DesiredCode::Reach, gname, None)),
            Class::Hot => {}
        }
        if !g.writable {
            return Err(refuse(DesiredCode::Unavailable, gname, None));
        }
        for (pname, v) in params {
            let Some(p) = g.parameter(pname) else {
                return Err(refuse(DesiredCode::NotFound, gname, Some(pname)));
            };
            if p.sensitive {
                return Err(refuse(DesiredCode::Sensitive, gname, Some(pname)));
            }
            if p.kind.check(v).is_err() {
                return Err(refuse(DesiredCode::InvalidRequest, gname, Some(pname)));
            }
        }
    }
    Ok(())
}

// --- redaction (§2.15) -------------------------------------------------------------------

/// A `set` request as a log line may carry it (§2.15): every value whose
/// parameter is sensitive, or that the owner cannot tell is not (an unknown
/// group or parameter), written [`REDACTED`].
#[must_use]
pub fn log_request(schema: &Schema, group: &str, req: &SetRequest) -> Json {
    let g = schema.group(group);
    let mut out = serde_json::to_value(req).unwrap_or(Json::Null);
    if let Some(values) = out.get_mut("values").and_then(Json::as_object_mut) {
        for (name, v) in values.iter_mut() {
            if g.is_none_or(|g| g.is_sensitive(name)) {
                *v = Json::String(REDACTED.to_owned());
            }
        }
    }
    out
}

/// Whether a `set` carries a value whose parameter is sensitive, or one the
/// owner cannot tell is not.
#[must_use]
pub fn carries_sensitive(schema: &Schema, group: &str, req: &SetRequest) -> bool {
    let g = schema.group(group);
    req.values
        .keys()
        .any(|n| g.is_none_or(|g| g.is_sensitive(n)))
}

/// The `detail` of a `device-refused` envelope (§2.15): the device's
/// words, left out when the change carries a sensitive value, since they
/// may repeat it.
#[must_use]
pub fn device_detail(
    schema: &Schema,
    group: &str,
    req: &SetRequest,
    words: Option<&str>,
) -> Option<String> {
    if carries_sensitive(schema, group, req) {
        None
    } else {
        words.map(str::to_owned)
    }
}

// --- the owner (§2.6 to §2.17) -----------------------------------------------------------

/// The call metadata a call claimed (core O7): never authentication.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Call {
    /// The claimed actor.
    pub actor: Option<String>,
    /// The claimed request id.
    pub request_id: Option<String>,
}

/// What an owner starts from: its address, schema, startup layers and
/// device facts.
#[derive(Debug, Clone)]
pub struct Start {
    /// The owner's address, `<system>/<service>`.
    pub service: String,
    /// The instance id; tokens are minted `<instance>-<n>`.
    pub instance: String,
    /// The schema.
    pub schema: Schema,
    /// The startup file's and the defaults' values, `{group: {parameter:
    /// (value, source)}}`, each source `file` or `default`. A parameter
    /// absent here starts unknown.
    pub startup: BTreeMap<String, BTreeMap<String, (Value, Source)>>,
    /// The persisted layer, `{group: {parameter: value}}`.
    pub overlay: BTreeMap<String, BTreeMap<String, Value>>,
    /// The floor, in seconds, at least 1 (§2.8).
    pub floor_s: u64,
    /// How long after receiving a reach `set` the device applies it: the
    /// `apply_at` it states (§2.9). Less than the floor, so that a new
    /// reach change applies before its deadline.
    pub apply_after: Duration,
    /// Whether the owner has a persisted layer (§2.13).
    pub persist: bool,
    /// The change events already published, for the rate (§2.17).
    pub events: Vec<Time>,
}

/// Why [`Owner::start`] refused a [`Start`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartError(pub String);

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

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

/// A device act the runtime performs, then reports with
/// [`Owner::finish`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Act {
    /// Apply these values of one group.
    Apply {
        /// The group.
        group: String,
        /// The values, by parameter.
        values: BTreeMap<String, Value>,
    },
    /// The undo, once: restore each parameter to its value before the
    /// change (§2.11).
    Undo {
        /// What to restore.
        restore: Vec<Restore>,
    },
}

/// One parameter an undo restores.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Restore {
    /// Its group.
    pub group: String,
    /// Its name.
    pub parameter: String,
    /// Its value before the change.
    pub value: Value,
}

/// What the device said of an act. An apply reported `Failed` reads as
/// refused, and an undo reported `Refused` as failed with nothing read
/// back.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeviceResult {
    /// Done.
    Ok,
    /// An apply refused, in the device's words.
    Refused(String),
    /// An undo failed, in the device's words, with what the owner read
    /// back: `{group: {parameter: value}}`, a parameter not in it unknown.
    Failed {
        /// The device's words.
        words: String,
        /// What was read back.
        readback: BTreeMap<String, BTreeMap<String, Value>>,
    },
}

impl Act {
    /// Whether the act sets a value whose parameter is sensitive, or one
    /// the owner cannot tell is not (an unknown group or parameter): an
    /// apply of such a value, or an undo restoring one (§2.15).
    #[must_use]
    pub fn carries_sensitive(&self, schema: &Schema) -> bool {
        let sensitive = |g: &str, p: &str| schema.group(g).is_none_or(|g| g.is_sensitive(p));
        match self {
            Self::Apply { group, values } => values.keys().any(|p| sensitive(group, p)),
            Self::Undo { restore } => restore.iter().any(|r| sensitive(&r.group, &r.parameter)),
        }
    }
}

/// The device's words about `act` as a log line may carry them (§2.15):
/// left out when the act sets a sensitive value, since they may repeat it.
#[must_use]
pub fn device_words<'w>(schema: &Schema, act: &Act, words: &'w str) -> Option<&'w str> {
    (!act.carries_sensitive(schema)).then_some(words)
}

/// What converging a desired document asks of the owner next (§2.18),
/// from [`Owner::converge`].
#[derive(Debug, Clone, PartialEq)]
pub enum Converge {
    /// A change is pending, or an act is in flight: wait until it ends.
    Wait,
    /// Refused whole, before anything applied: the report to carry.
    Refused(DesiredReport),
    /// One `set` without a window, on the first group by bytewise name
    /// whose values differ from the document: its own change, `applied`.
    /// A refusal of it is the report [`desired_failed`] makes.
    Set {
        /// The group.
        group: String,
        /// The request: the values that differ, and nothing else.
        request: SetRequest,
    },
    /// Every value the document names is the running value.
    Converged(DesiredReport),
}

/// The report of a document whose converging `set` on `group` was refused
/// (§2.18): `failed`, with that refusal's code (`busy` for the rate,
/// `device-refused`) and group.
#[must_use]
pub fn desired_failed(revision: u64, group: &str, refusal: &Refusal) -> DesiredReport {
    let code = match refusal.code {
        Code::Busy => DesiredCode::Busy,
        Code::App => DesiredCode::DeviceRefused,
        Code::InvalidRequest => DesiredCode::InvalidRequest,
        Code::NotFound => DesiredCode::NotFound,
        // A set never answers `forbidden`; and `unavailable` is the
        // allowlist's, which check_desired refused first.
        Code::Unavailable | Code::Forbidden => DesiredCode::Unavailable,
    };
    DesiredReport {
        observed_revision: revision,
        outcome: DesiredOutcome::Failed,
        refusal: Some(DesiredRefusal {
            code,
            group: group.to_owned(),
            parameter: None,
        }),
    }
}

/// A reply an owner sends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Reply {
    /// To a `set`.
    Set(SetReply),
    /// To a control operation.
    Control(ControlReply),
}

impl Reply {
    /// The reply's JSON.
    #[must_use]
    pub fn to_json(&self) -> Json {
        match self {
            Self::Set(r) => serde_json::to_value(r),
            Self::Control(r) => serde_json::to_value(r),
        }
        .unwrap_or(Json::Null)
    }
}

/// An answered step: the reply owed to the call, if any, and the change
/// events to publish, in order.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Done {
    /// The reply, or the refusal, owed to the call; `None` when no call is
    /// answered (a deadline, a reach apply).
    pub reply: Option<Result<Reply, Refusal>>,
    /// The events to publish.
    pub events: Vec<ConfigChangeEvent>,
}

/// What the owner does next: answer, or have the runtime act on the device
/// and report back with [`Owner::finish`]. A call answered with an act
/// gets its reply from the act's finish.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
    /// Answered now.
    Done(Done),
    /// An act to perform first.
    Act(Act),
}

/// A `persist` the owner admitted: the entries the runtime writes, then
/// commits with [`Owner::persisted`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersistPlan {
    /// The last change's token.
    pub token: String,
    /// The values to write, `{group: {parameter: value}}`.
    pub entries: BTreeMap<String, BTreeMap<String, Value>>,
    answer: Answer,
}

type Key = (String, String);

#[derive(Debug, Clone)]
struct Slot {
    value: Option<Value>,
    source: Option<Source>,
}

#[derive(Debug, Clone)]
struct EditRec {
    old: Option<Value>,
    old_source: Option<Source>,
    new: Value,
    applied: bool,
    sensitive: bool,
}

#[derive(Debug, Clone)]
struct Wait {
    group: String,
    values: BTreeMap<String, Value>,
    apply_at: Time,
}

#[derive(Debug, Clone)]
struct Change {
    token: String,
    groups: Vec<String>,
    deadline: Time,
    call: Call,
    edits: BTreeMap<Key, EditRec>,
    waiting: Vec<Wait>,
}

#[derive(Debug, Clone)]
struct Last {
    token: String,
    groups: Vec<String>,
    /// The values the change set, as it set them: what `persist` writes,
    /// whatever a pending change runs since (§2.13, text 0.2, F-111).
    values: BTreeMap<Key, Value>,
    sensitive: bool,
}

impl Last {
    fn of(token: String, groups: Vec<String>, edits: &BTreeMap<Key, EditRec>) -> Self {
        Self {
            token,
            groups,
            values: edits
                .iter()
                .map(|(k, r)| (k.clone(), r.new.clone()))
                .collect(),
            sensitive: edits.values().any(|r| r.sensitive),
        }
    }
}

#[derive(Debug, Clone)]
struct Held {
    key: String,
    group: String,
    request: SetRequest,
    answer: Result<Reply, Refusal>,
    at: Time,
}

#[derive(Debug, Clone, Copy)]
enum UndoWhy {
    Deadline,
    Cancel(Answer),
    Failed,
}

#[derive(Debug, Clone)]
enum Flight {
    Set {
        group: String,
        request: SetRequest,
        call: Call,
        values: BTreeMap<String, Value>,
        received: Time,
    },
    Apply(Wait),
    Undo {
        why: UndoWhy,
        plan: Vec<Key>,
    },
}

/// One owner's configuration, as a pure state machine (§2.6 to §2.17).
///
/// Every method takes the instant it acts at. A call is answered by a
/// [`Step`]: [`Step::Done`] now, or [`Step::Act`], an act the runtime
/// performs on the device before it calls [`Owner::finish`] with the
/// result. While an act is in flight, every call is `busy` (§2.7). The
/// runtime calls [`Owner::due`] at [`Owner::next_due`], for the deadline's
/// undo and each reach apply.
#[derive(Debug, Clone)]
pub struct Owner {
    service: String,
    instance: String,
    schema: Schema,
    floor_s: u64,
    apply_after: Duration,
    persist: bool,
    file: BTreeMap<Key, (Value, Source)>,
    overlay: BTreeMap<Key, Value>,
    slots: BTreeMap<Key, Slot>,
    revision: u64,
    minted: u64,
    pending: Option<Change>,
    last: Option<Last>,
    keys: Vec<Held>,
    events: Vec<Time>,
    flight: Option<Flight>,
    desired: Option<DesiredReport>,
    whole_seconds: bool,
}

fn key(g: &str, p: &str) -> Key {
    (g.to_owned(), p.to_owned())
}

fn flat<T: Clone>(m: &BTreeMap<String, BTreeMap<String, T>>) -> BTreeMap<Key, T> {
    m.iter()
        .flat_map(|(g, ps)| ps.iter().map(move |(p, v)| (key(g, p), v.clone())))
        .collect()
}

impl Owner {
    /// Starts an owner from its startup values and its persisted layer,
    /// never from a runtime change (§2.12): revision 0, nothing pending.
    ///
    /// # Errors
    ///
    /// A [`StartError`] for a floor of 0, an `apply_after` not below the
    /// floor, more than 16 groups, a name declared twice, bounds that cross,
    /// a startup source other than `file` or `default`, or a layer naming a
    /// parameter the schema does not declare, or a sensitive one in the
    /// persisted layer.
    pub fn start(s: Start) -> Result<Self, StartError> {
        let fail = |m: String| Err(StartError(m));
        if s.floor_s == 0 {
            return fail("the floor is at least 1 s".into());
        }
        if s.apply_after >= Duration::from_secs(s.floor_s) {
            return fail("apply_after must be below the floor, so that a reach change applies before its deadline".into());
        }
        if s.schema.groups.len() > MAX_GROUPS {
            return fail(format!(
                "{} groups, above the contract's {MAX_GROUPS}",
                s.schema.groups.len()
            ));
        }
        for (i, g) in s.schema.groups.iter().enumerate() {
            if g.name.is_empty() || s.schema.groups[..i].iter().any(|h| h.name == g.name) {
                return fail(format!("group {:?} is empty or declared twice", g.name));
            }
            for (j, p) in g.parameters.iter().enumerate() {
                if p.name.is_empty() || g.parameters[..j].iter().any(|q| q.name == p.name) {
                    return fail(format!(
                        "parameter {:?} of {:?} is empty or declared twice",
                        p.name, g.name
                    ));
                }
                if let Kind::Integer {
                    min: Some(a),
                    max: Some(b),
                    ..
                } = p.kind
                    && a > b
                {
                    return fail(format!("{}.{}: min above max", g.name, p.name));
                }
            }
        }
        let file = flat(&s.startup);
        let overlay = flat(&s.overlay);
        for ((g, p), (v, src)) in &file {
            let Some(d) = s.schema.group(g).and_then(|gd| gd.parameter(p)) else {
                return fail(format!(
                    "the startup layer names {g}.{p}, which the schema does not declare"
                ));
            };
            if !matches!(src, Source::File | Source::Default) {
                return fail(format!(
                    "{g}.{p}: a startup value comes from the file or a default"
                ));
            }
            if d.kind
                .check(&serde_json::to_value(v).unwrap_or(Json::Null))
                .is_err()
            {
                return fail(format!(
                    "{g}.{p}: its startup value is not of its kind or bounds"
                ));
            }
        }
        for ((g, p), v) in &overlay {
            match s.schema.group(g).and_then(|gd| gd.parameter(p)) {
                None => {
                    return fail(format!(
                        "the persisted layer names {g}.{p}, which the schema does not declare"
                    ));
                }
                Some(d) if d.sensitive => {
                    return fail(format!("{g}.{p} is sensitive, never persisted"));
                }
                Some(d)
                    if d.kind
                        .check(&serde_json::to_value(v).unwrap_or(Json::Null))
                        .is_err() =>
                {
                    return fail(format!(
                        "{g}.{p}: its persisted value is not of its kind or bounds"
                    ));
                }
                Some(_) => {}
            }
        }
        let mut slots = BTreeMap::new();
        for g in &s.schema.groups {
            for p in &g.parameters {
                let k = key(&g.name, &p.name);
                let slot = match (overlay.get(&k), file.get(&k)) {
                    (Some(v), _) => Slot {
                        value: Some(v.clone()),
                        source: Some(Source::Overlay),
                    },
                    (None, Some((v, src))) => Slot {
                        value: Some(v.clone()),
                        source: Some(*src),
                    },
                    (None, None) => Slot {
                        value: None,
                        source: None,
                    },
                };
                slots.insert(k, slot);
            }
        }
        Ok(Self {
            service: s.service,
            instance: s.instance,
            schema: s.schema,
            floor_s: s.floor_s,
            apply_after: s.apply_after,
            persist: s.persist,
            file,
            overlay,
            slots,
            revision: 0,
            minted: 0,
            pending: None,
            last: None,
            keys: Vec::new(),
            events: s.events,
            flight: None,
            desired: None,
            whole_seconds: false,
        })
    }

    /// The owner with every deadline and `apply_at` it states rounded up
    /// to the next whole second, acted on at that instant: `config.v2`'s
    /// times (its §2.8), which [`v2::Owner`] runs this owner under.
    /// `config.v1` keeps milliseconds.
    #[must_use]
    pub fn whole_seconds(mut self) -> Self {
        self.whole_seconds = true;
        self
    }

    /// An instant this owner states: rounded up under
    /// [`Owner::whole_seconds`].
    fn stated(&self, t: Time) -> Time {
        if self.whole_seconds {
            t.ceil_second()
        } else {
            t
        }
    }

    /// The owner after a restart, as a new instance (§2.12): its startup
    /// values and persisted layer, revision 0, nothing pending, no last
    /// change, no key held. The persisted layer and the published events
    /// survive it.
    #[must_use]
    pub fn restart(&self, instance: impl Into<String>) -> Self {
        let unflat = |m: &BTreeMap<Key, (Value, Source)>| {
            let mut out: BTreeMap<String, BTreeMap<String, (Value, Source)>> = BTreeMap::new();
            for ((g, p), v) in m {
                out.entry(g.clone())
                    .or_default()
                    .insert(p.clone(), v.clone());
            }
            out
        };
        let mut overlay: BTreeMap<String, BTreeMap<String, Value>> = BTreeMap::new();
        for ((g, p), v) in &self.overlay {
            overlay
                .entry(g.clone())
                .or_default()
                .insert(p.clone(), v.clone());
        }
        let mut next = Self::start(Start {
            service: self.service.clone(),
            instance: instance.into(),
            schema: self.schema.clone(),
            startup: unflat(&self.file),
            overlay,
            floor_s: self.floor_s,
            apply_after: self.apply_after,
            persist: self.persist,
            events: self.events.clone(),
        })
        .expect("a start that succeeded once succeeds again");
        next.whole_seconds = self.whole_seconds;
        next
    }

    /// The schema.
    #[must_use]
    pub fn schema(&self) -> &Schema {
        &self.schema
    }

    /// The instance id.
    #[must_use]
    pub fn instance(&self) -> &str {
        &self.instance
    }

    /// The revision.
    #[must_use]
    pub fn revision(&self) -> u64 {
        self.revision
    }

    /// Whether an act is in flight.
    #[must_use]
    pub fn in_flight(&self) -> bool {
        self.flight.is_some()
    }

    /// The next instant [`Owner::due`] has something to do: the earliest
    /// reach `apply_at`, or the deadline.
    #[must_use]
    pub fn next_due(&self) -> Option<Time> {
        let ch = self.pending.as_ref()?;
        let apply = ch.waiting.iter().map(|w| w.apply_at).min();
        Some(apply.map_or(ch.deadline, |a| a.min(ch.deadline)))
    }

    /// The pending change's deadline, if a change is pending.
    #[must_use]
    pub fn deadline(&self) -> Option<Time> {
        self.pending.as_ref().map(|c| c.deadline)
    }

    /// The `apply_at` of the last reach group to join the pending change
    /// that has not applied yet, if one waits: `None` when the change is
    /// applied, or when none is pending (`config.v2` §2.9).
    #[must_use]
    pub fn apply_at(&self) -> Option<Time> {
        self.pending.as_ref()?.waiting.last().map(|w| w.apply_at)
    }

    /// Sets the desired report the view and the status carry (§2.18).
    pub fn report_desired(&mut self, report: Option<DesiredReport>) {
        self.desired = report;
    }

    /// The desired report the view and the status carry (§2.18).
    #[must_use]
    pub fn desired(&self) -> Option<&DesiredReport> {
        self.desired.as_ref()
    }

    /// The instants of the change events published within the last hour
    /// at `now`, oldest first (§2.17): what the next instance starts from
    /// ([`Start::events`]), so that the event's rate, which a re-mint does
    /// not reset (core §2.7), holds across a restart.
    #[must_use]
    pub fn published(&self, now: Time) -> Vec<Time> {
        let mut out: Vec<Time> = self
            .events
            .iter()
            .copied()
            .filter(|e| now.within(*e, RATE_PERIOD))
            .collect();
        out.sort();
        out
    }

    /// What converging `doc` asks next (§2.18): wait while a change is
    /// pending or an act is in flight; the document refused whole
    /// ([`check_desired`]); one `set` without a window on the first group,
    /// in the bytewise order of the group names, whose values differ from
    /// the running ones; or converged. Called again after each `set`, it
    /// moves to the next group, since the one applied no longer differs.
    #[must_use]
    pub fn converge(&self, doc: &DesiredConfig) -> Converge {
        if self.pending.is_some() || self.flight.is_some() {
            return Converge::Wait;
        }
        if let Err(refusal) = check_desired(&self.schema, doc) {
            return Converge::Refused(DesiredReport {
                observed_revision: doc.revision,
                outcome: DesiredOutcome::Refused,
                refusal: Some(refusal),
            });
        }
        for (g, params) in &doc.values {
            let Some(decl) = self.schema.group(g) else {
                continue;
            };
            let differ: BTreeMap<String, Json> = params
                .iter()
                .filter(|(p, v)| {
                    let wanted = decl.parameter(p).and_then(|d| d.kind.check(v).ok());
                    let running = self.slots.get(&key(g, p)).and_then(|s| s.value.as_ref());
                    wanted.as_ref() != running
                })
                .map(|(p, v)| (p.clone(), v.clone()))
                .collect();
            if !differ.is_empty() {
                return Converge::Set {
                    group: g.clone(),
                    request: SetRequest {
                        values: differ,
                        ..SetRequest::default()
                    },
                };
            }
        }
        Converge::Converged(DesiredReport {
            observed_revision: doc.revision,
            outcome: DesiredOutcome::Converged,
            refusal: None,
        })
    }

    /// What the validators read of the owner's state at `now`.
    #[must_use]
    pub fn facts(&self, now: Time) -> Facts<'_> {
        Facts {
            revision: self.revision,
            pending: self.pending.as_ref().map(|c| PendingFacts {
                token: &c.token,
                applied: c.waiting.is_empty(),
                deadline_passed: now >= c.deadline,
            }),
            last_change: self.last.as_ref().map(|l| LastFacts {
                token: &l.token,
                set_sensitive: l.sensitive,
            }),
            persist: self.persist,
            in_flight: self.flight.is_some(),
        }
    }

    fn startup_value(&self, k: &Key) -> Option<(Value, Source)> {
        self.overlay
            .get(k)
            .map(|v| (v.clone(), Source::Overlay))
            .or_else(|| self.file.get(k).cloned())
    }

    /// A parameter's startup value and its source (§2.12): the persisted
    /// layer's, else the startup file's or the default. `None` for a
    /// parameter that starts unknown, or that the schema does not declare.
    #[must_use]
    pub fn startup(&self, group: &str, parameter: &str) -> Option<(Value, Source)> {
        self.startup_value(&key(group, parameter))
    }

    /// The document a delete reverts the owner to, when `desired.v1` feeds
    /// it (`desired.v1` §2.16, text 0.3): each parameter of `named` (the
    /// ones the documents it acted on named) at its startup value, the
    /// persisted layer's, else the startup file's or the default; one that
    /// starts unknown is left out, and keeps its running value. Converged
    /// as any document is ([`Owner::converge`]): one `set` without a window
    /// per group whose running values differ, nothing for one that already
    /// runs its startup values.
    #[must_use]
    pub fn baseline_document<'n>(
        &self,
        named: impl IntoIterator<Item = (&'n str, &'n str)>,
    ) -> DesiredConfig {
        let mut values: BTreeMap<String, BTreeMap<String, Json>> = BTreeMap::new();
        for (g, p) in named {
            if let Some((v, _)) = self.startup(g, p) {
                values
                    .entry(g.to_owned())
                    .or_default()
                    .insert(p.to_owned(), serde_json::to_value(&v).unwrap_or(Json::Null));
            }
        }
        DesiredConfig {
            revision: 0,
            values,
        }
    }

    /// What a re-mint returns the device to first (§2.12, "A re-mint is a
    /// restart"): each parameter whose running value is not its startup
    /// value, unknown included, at its startup value (the persisted
    /// layer's, else the startup file's or the default), in the schema's
    /// order. Empty when the device runs its startup values. `Err` names
    /// the first parameter that runs a value but starts unknown, which
    /// nothing returns it to. Read with nothing pending: a pending change
    /// is cancelled first.
    ///
    /// # Errors
    ///
    /// `(group, parameter)` of a parameter with a running value and no
    /// startup value.
    pub fn restart_plan(&self) -> Result<Vec<Restore>, (String, String)> {
        let mut plan = Vec::new();
        for g in &self.schema.groups {
            for p in &g.parameters {
                let k = key(&g.name, &p.name);
                let running = self.slots.get(&k).and_then(|s| s.value.as_ref());
                match (running, self.startup_value(&k)) {
                    (r, Some((v, _))) if r != Some(&v) => plan.push(Restore {
                        group: g.name.clone(),
                        parameter: p.name.clone(),
                        value: v,
                    }),
                    (Some(_), None) => return Err(k),
                    _ => {}
                }
            }
        }
        Ok(plan)
    }

    fn render(&self, slots: &BTreeMap<Key, Slot>) -> ConfigView {
        let groups = self
            .schema
            .groups
            .iter()
            .map(|g| GroupView {
                name: g.name.clone(),
                class: g.class,
                description: g.description.clone(),
                writable: g.writable,
                parameters: g
                    .parameters
                    .iter()
                    .map(|d| {
                        let k = key(&g.name, &d.name);
                        let slot = slots.get(&k);
                        let value = slot.and_then(|s| s.value.clone());
                        let startup = self.startup_value(&k).map(|(v, _)| v);
                        Parameter {
                            name: d.name.clone(),
                            kind: d.kind.clone(),
                            description: d.description.clone(),
                            sensitive: d.sensitive,
                            value: if d.sensitive { None } else { value.clone() },
                            source: slot.and_then(|s| s.source),
                            startup: match (d.sensitive, value, startup) {
                                (false, Some(v), Some(s)) if v != s => Some(s),
                                _ => None,
                            },
                        }
                    })
                    .collect(),
            })
            .collect();
        ConfigView {
            service: self.service.clone(),
            instance: self.instance.clone(),
            revision: self.revision,
            confirm_floor_s: self.floor_s,
            pending: self.pending.as_ref().map(|c| Pending {
                token: c.token.clone(),
                groups: c.groups.clone(),
                deadline: c.deadline.rfc3339(),
                applied: c.waiting.is_empty(),
            }),
            last_change: self.last.as_ref().map(|l| LastChange {
                token: l.token.clone(),
                groups: l.groups.clone(),
            }),
            desired: self.desired.clone(),
            groups,
        }
    }

    /// The read-back (§2.3).
    #[must_use]
    pub fn view(&self) -> ConfigView {
        self.render(&self.slots)
    }

    /// The compact status, the view's projection (§2.19).
    #[must_use]
    pub fn status(&self) -> ConfigStatus {
        ConfigStatus::of(&self.view())
    }

    fn control_reply(&self, answer: Answer) -> Reply {
        let view = self.view();
        Reply::Control(match answer {
            Answer::View => ControlReply::View(Box::new(view)),
            Answer::Status => ControlReply::Status(Box::new(ConfigStatus::of(&view))),
        })
    }

    fn mint(&mut self) -> String {
        self.minted += 1;
        format!("{}-{}", self.instance, self.minted)
    }

    fn rate_spent(&self, now: Time) -> bool {
        self.events
            .iter()
            .filter(|e| now.within(**e, RATE_PERIOD))
            .count()
            >= RATE
    }

    fn edits(&self, groups: &[String], edits: &BTreeMap<Key, EditRec>) -> Vec<Edit> {
        groups
            .iter()
            .flat_map(|g| {
                edits
                    .iter()
                    .filter(move |((eg, _), _)| eg == g)
                    .map(|((eg, ep), r)| {
                        if r.sensitive {
                            Edit {
                                group: eg.clone(),
                                parameter: ep.clone(),
                                old: None,
                                new: None,
                                redacted: true,
                            }
                        } else {
                            Edit {
                                group: eg.clone(),
                                parameter: ep.clone(),
                                old: r.old.clone(),
                                new: Some(r.new.clone()),
                                redacted: false,
                            }
                        }
                    })
            })
            .collect()
    }

    fn event(
        &mut self,
        now: Time,
        token: &str,
        outcome: Outcome,
        edits: Vec<Edit>,
        call: &Call,
    ) -> ConfigChangeEvent {
        self.events.retain(|e| now.within(*e, RATE_PERIOD));
        self.events.push(now);
        ConfigChangeEvent {
            service: self.service.clone(),
            instance: self.instance.clone(),
            revision: self.revision,
            token: token.to_owned(),
            outcome,
            edits,
            actor: call.actor.clone(),
            request_id: call.request_id.clone(),
            claimed_source: None,
        }
    }

    fn is_sensitive(&self, k: &Key) -> bool {
        self.schema
            .group(&k.0)
            .is_some_and(|g| g.is_sensitive(&k.1))
    }

    /// Records the values a change sets, keeping each parameter's value
    /// before the change from its first set.
    fn record(
        &self,
        edits: &mut BTreeMap<Key, EditRec>,
        group: &str,
        values: &BTreeMap<String, Value>,
        applied: bool,
    ) {
        for (p, v) in values {
            let k = key(group, p);
            let sensitive = self.is_sensitive(&k);
            match edits.get_mut(&k) {
                Some(r) => {
                    r.new = v.clone();
                    r.applied |= applied;
                }
                None => {
                    let slot = self.slots.get(&k);
                    edits.insert(
                        k,
                        EditRec {
                            old: slot.and_then(|s| s.value.clone()),
                            old_source: slot.and_then(|s| s.source),
                            new: v.clone(),
                            applied,
                            sensitive,
                        },
                    );
                }
            }
        }
    }

    fn write(&mut self, group: &str, values: &BTreeMap<String, Value>) {
        for (p, v) in values {
            self.slots.insert(
                key(group, p),
                Slot {
                    value: Some(v.clone()),
                    source: Some(Source::Runtime),
                },
            );
        }
        self.revision += 1;
    }

    fn forget_keys(&mut self, now: Time) {
        self.keys.retain(|h| now.within(h.at, KEY_HELD));
    }

    fn hold(&mut self, now: Time, group: &str, req: &SetRequest, answer: &Result<Reply, Refusal>) {
        if let Some(k) = &req.idempotency_key
            && !self.keys.iter().any(|h| &h.key == k)
        {
            self.keys.push(Held {
                key: k.clone(),
                group: group.to_owned(),
                request: req.clone(),
                answer: answer.clone(),
                at: now,
            });
        }
    }

    /// Whether a `set` of `group` with `req` would be answered now with the
    /// first answer its idempotency key holds (§2.14): what [`Owner::set`]
    /// replays, read without a change. A runtime that keeps the bytes it
    /// sent then sends them again, the first answer's as-of mark included
    /// (core §5.1, "An answer sent again").
    #[must_use]
    pub fn replays(&self, now: Time, group: &str, req: &SetRequest) -> bool {
        if check_set_shape(req).is_err() || self.flight.is_some() {
            return false;
        }
        req.idempotency_key.as_ref().is_some_and(|k| {
            self.held(now, k)
                .is_some_and(|h| h.group == group && h.request == *req)
        })
    }

    /// Whether the owner holds a first answer for idempotency key `key` at
    /// `now` (§2.14): within 300 s of it.
    #[must_use]
    pub fn holds_key(&self, now: Time, key: &str) -> bool {
        self.held(now, key).is_some()
    }

    fn held(&self, now: Time, key: &str) -> Option<&Held> {
        self.keys
            .iter()
            .find(|h| h.key == key && now.within(h.at, KEY_HELD))
    }

    /// A `set` (§2.5, §2.9): answered now, or an [`Act::Apply`] for a hot
    /// group, whose reply comes with [`Owner::finish`].
    pub fn set(&mut self, now: Time, group: &str, req: &SetRequest, call: &Call) -> Step {
        let refuse = |r: Refusal| {
            Step::Done(Done {
                reply: Some(Err(r)),
                events: Vec::new(),
            })
        };
        if let Err(r) = check_set_shape(req) {
            return refuse(r);
        }
        if self.flight.is_some() {
            return refuse(in_flight());
        }
        self.forget_keys(now);
        if let Some(k) = &req.idempotency_key
            && let Some(h) = self.keys.iter().find(|h| &h.key == k)
        {
            return if h.group == group && h.request == *req {
                Step::Done(Done {
                    reply: Some(h.answer.clone()),
                    events: Vec::new(),
                })
            } else {
                refuse(Refusal::new(
                    Code::InvalidRequest,
                    Some(Field::member("idempotency_key")),
                    "this idempotency key was used for another request within 300 s",
                ))
            };
        }
        let step = self.admit(now, group, req, call);
        if let Step::Done(Done {
            reply: Some(answer),
            ..
        }) = &step
        {
            self.hold(now, group, req, answer);
        }
        step
    }

    fn admit(&mut self, now: Time, group: &str, req: &SetRequest, call: &Call) -> Step {
        let refuse = |r: Refusal| {
            Step::Done(Done {
                reply: Some(Err(r)),
                events: Vec::new(),
            })
        };
        let facts = self.facts(now);
        let a = match check_rows(&self.schema, &facts, group, req) {
            Ok(a) => a,
            Err(r) => return refuse(r),
        };
        if a.dry_run {
            let mut slots = self.slots.clone();
            for (p, v) in &a.values {
                slots.insert(
                    key(group, p),
                    Slot {
                        value: Some(v.clone()),
                        source: Some(Source::Runtime),
                    },
                );
            }
            return Step::Done(Done {
                reply: Some(Ok(Reply::Set(SetReply::Applied(Box::new(
                    self.render(&slots),
                ))))),
                events: Vec::new(),
            });
        }
        if !a.joins && self.rate_spent(now) {
            return refuse(Refusal::busy(format!(
                "{RATE} change events within the last hour: the event's rate is spent; call again later"
            )));
        }
        match a.class {
            Class::Hot => {
                self.flight = Some(Flight::Set {
                    group: group.to_owned(),
                    request: req.clone(),
                    call: call.clone(),
                    values: a.values.clone(),
                    received: now,
                });
                Step::Act(Act::Apply {
                    group: group.to_owned(),
                    values: a.values,
                })
            }
            Class::Reach => {
                let apply_at = self.stated(now.plus(self.apply_after));
                if a.joins {
                    let deadline = self.pending.as_ref().map_or(now, |c| c.deadline);
                    if apply_at >= deadline {
                        return refuse(Refusal::busy(
                            "this group could not apply before the pending change's deadline; extend the change first",
                        ));
                    }
                    let mut ch = self.pending.take().expect("a join has a pending change");
                    self.record(&mut ch.edits, group, &a.values, false);
                    if !ch.groups.iter().any(|g| g == group) {
                        ch.groups.push(group.to_owned());
                    }
                    ch.waiting.push(Wait {
                        group: group.to_owned(),
                        values: a.values,
                        apply_at,
                    });
                    let reply = PendingReply {
                        token: ch.token.clone(),
                        apply_at: apply_at.rfc3339(),
                        deadline: ch.deadline.rfc3339(),
                    };
                    self.pending = Some(ch);
                    Step::Done(Done {
                        reply: Some(Ok(Reply::Set(SetReply::Pending(reply)))),
                        events: Vec::new(),
                    })
                } else {
                    let w = window(req.confirm_s.expect("row 10: a window"), self.floor_s);
                    let token = self.mint();
                    let deadline = self.stated(deadline(now, w));
                    let mut edits = BTreeMap::new();
                    self.record(&mut edits, group, &a.values, false);
                    self.pending = Some(Change {
                        token: token.clone(),
                        groups: vec![group.to_owned()],
                        deadline,
                        call: call.clone(),
                        edits,
                        waiting: vec![Wait {
                            group: group.to_owned(),
                            values: a.values,
                            apply_at,
                        }],
                    });
                    Step::Done(Done {
                        reply: Some(Ok(Reply::Set(SetReply::Pending(PendingReply {
                            token,
                            apply_at: apply_at.rfc3339(),
                            deadline: deadline.rfc3339(),
                        })))),
                        events: Vec::new(),
                    })
                }
            }
            Class::Contract => unreachable!("row 8 refuses a contract group"),
        }
    }

    /// `confirm` (§2.10): always answered now.
    pub fn confirm(&mut self, now: Time, req: &ControlRequest, _call: &Call) -> Step {
        if let Err(r) = validate_control(ControlOp::Confirm, &self.facts(now), req) {
            return Step::Done(Done {
                reply: Some(Err(r)),
                events: Vec::new(),
            });
        }
        let ch = self.pending.take().expect("validated: a change is pending");
        let edits = self.edits(&ch.groups, &ch.edits);
        let ev = self.event(now, &ch.token, Outcome::Confirmed, edits, &ch.call);
        self.last = Some(Last::of(ch.token.clone(), ch.groups.clone(), &ch.edits));
        Step::Done(Done {
            reply: Some(Ok(self.control_reply(req.answer.unwrap_or_default()))),
            events: vec![ev],
        })
    }

    /// `extend` (§2.10): always answered now; the deadline moves to `now`
    /// plus the window, earlier or later.
    pub fn extend(&mut self, now: Time, req: &ControlRequest, _call: &Call) -> Step {
        if let Err(r) = validate_control(ControlOp::Extend, &self.facts(now), req) {
            return Step::Done(Done {
                reply: Some(Err(r)),
                events: Vec::new(),
            });
        }
        let w = window(req.confirm_s.expect("validated: a window"), self.floor_s);
        let at = self.stated(deadline(now, w));
        if let Some(ch) = self.pending.as_mut() {
            ch.deadline = at;
        }
        Step::Done(Done {
            reply: Some(Ok(self.control_reply(req.answer.unwrap_or_default()))),
            events: Vec::new(),
        })
    }

    /// `cancel` (§2.10): the undo now, an [`Act::Undo`] when something of
    /// the change is applied, else answered now.
    pub fn cancel(&mut self, now: Time, req: &ControlRequest, _call: &Call) -> Step {
        if let Err(r) = validate_control(ControlOp::Cancel, &self.facts(now), req) {
            return Step::Done(Done {
                reply: Some(Err(r)),
                events: Vec::new(),
            });
        }
        self.end_by_undo(now, UndoWhy::Cancel(req.answer.unwrap_or_default()))
    }

    /// Admits a `persist` (§2.13): the entries to write. Nothing changes
    /// until [`Owner::persisted`]; a write that fails is the runtime's
    /// `internal`.
    ///
    /// # Errors
    ///
    /// The [`Refusal`].
    pub fn persist_plan(&self, now: Time, req: &ControlRequest) -> Result<PersistPlan, Refusal> {
        validate_control(ControlOp::Persist, &self.facts(now), req)?;
        let last = self.last.as_ref().expect("validated: a last change");
        // The values the last change set, never the running ones: a pending
        // change may run another since (§2.13, text 0.2, F-111).
        let mut entries: BTreeMap<String, BTreeMap<String, Value>> = BTreeMap::new();
        for ((g, p), v) in &last.values {
            entries
                .entry(g.clone())
                .or_default()
                .insert(p.clone(), v.clone());
        }
        Ok(PersistPlan {
            token: last.token.clone(),
            entries,
            answer: req.answer.unwrap_or_default(),
        })
    }

    /// Commits a `persist` whose entries the runtime wrote (§2.13): a
    /// parameter that runs the value persisted reads `source: overlay`,
    /// unless an applied group of a pending change holds it, which keeps
    /// its value and source and shows the persisted value as `startup`;
    /// and a pending change's value before it, when it is the value
    /// persisted, restores at `source: overlay` (text 0.2, F-111). No
    /// revision, no event.
    pub fn persisted(&mut self, plan: PersistPlan) -> Done {
        for (g, ps) in &plan.entries {
            for (p, v) in ps {
                let k = key(g, p);
                self.overlay.insert(k.clone(), v.clone());
                let pending = self.pending.as_mut().and_then(|c| c.edits.get_mut(&k));
                let held = pending.as_ref().is_some_and(|r| r.applied);
                if let Some(r) = pending
                    && r.old.as_ref() == Some(v)
                {
                    r.old_source = Some(Source::Overlay);
                }
                if !held
                    && let Some(s) = self.slots.get_mut(&k)
                    && s.value.as_ref() == Some(v)
                {
                    s.source = Some(Source::Overlay);
                }
            }
        }
        Done {
            reply: Some(Ok(self.control_reply(plan.answer))),
            events: Vec::new(),
        }
    }

    /// The act owed at `now`, if any (§2.9, §2.11): the deadline's undo,
    /// or else the earliest reach apply whose `apply_at` has come. A change
    /// with nothing applied ends at its deadline without an act. `None`
    /// while an act is in flight, or when nothing is owed.
    pub fn due(&mut self, now: Time) -> Option<Step> {
        if self.flight.is_some() {
            return None;
        }
        if now >= self.pending.as_ref()?.deadline {
            return Some(self.end_by_undo(now, UndoWhy::Deadline));
        }
        let ch = self.pending.as_mut()?;
        let i = ch
            .waiting
            .iter()
            .enumerate()
            .filter(|(_, w)| w.apply_at <= now)
            .min_by_key(|(i, w)| (w.apply_at, *i))
            .map(|(i, _)| i)?;
        let w = ch.waiting.remove(i);
        let act = Act::Apply {
            group: w.group.clone(),
            values: w.values.clone(),
        };
        self.flight = Some(Flight::Apply(w));
        Some(Step::Act(act))
    }

    /// Ends the pending change by its undo: an act over its applied groups,
    /// or, with none applied, `rolled-back` at once (§2.11).
    fn end_by_undo(&mut self, now: Time, why: UndoWhy) -> Step {
        let Some(ch) = self.pending.as_mut() else {
            return Step::Done(Done::default());
        };
        ch.waiting.clear();
        let plan: Vec<Key> = ch
            .edits
            .iter()
            .filter(|(_, r)| r.applied)
            .map(|(k, _)| k.clone())
            .collect();
        if plan.is_empty() {
            let ch = self.pending.take().expect("checked above");
            let edits = self.edits(&ch.groups, &ch.edits);
            let ev = self.event(now, &ch.token, Outcome::RolledBack, edits, &ch.call);
            let reply = match why {
                UndoWhy::Cancel(answer) => Some(Ok(self.control_reply(answer))),
                _ => None,
            };
            return Step::Done(Done {
                reply,
                events: vec![ev],
            });
        }
        let ch = self.pending.as_ref().expect("checked above");
        let restore = plan
            .iter()
            .filter_map(|k| {
                let r = &ch.edits[k];
                let value = r
                    .old
                    .clone()
                    .or_else(|| self.startup_value(k).map(|(v, _)| v))?;
                Some(Restore {
                    group: k.0.clone(),
                    parameter: k.1.clone(),
                    value,
                })
            })
            .collect();
        self.flight = Some(Flight::Undo { why, plan });
        Step::Act(Act::Undo { restore })
    }

    /// Reports the device's result for the act in flight, and answers what
    /// it owed: a `set`'s reply, a `cancel`'s, the events of a change it
    /// ended, or a next act (the undo after a reach apply that failed).
    pub fn finish(&mut self, now: Time, result: DeviceResult) -> Step {
        let Some(flight) = self.flight.take() else {
            return Step::Done(Done::default());
        };
        match flight {
            Flight::Set {
                group,
                request,
                call,
                values,
                received,
            } => {
                let done = match result {
                    DeviceResult::Ok => {
                        self.applied_hot(now, &group, &request, &call, &values, received)
                    }
                    DeviceResult::Refused(words) | DeviceResult::Failed { words, .. } => {
                        let detail = device_detail(&self.schema, &group, &request, Some(&words));
                        Done {
                            reply: Some(Err(Refusal::app(
                                ErrorCode::DeviceRefused,
                                detail,
                                format!("the device refused group {group:?}"),
                            ))),
                            events: Vec::new(),
                        }
                    }
                };
                if let Some(answer) = &done.reply {
                    self.hold(now, &group, &request, answer);
                }
                Step::Done(done)
            }
            Flight::Apply(w) => match result {
                DeviceResult::Ok => {
                    self.write(&w.group, &w.values);
                    if let Some(ch) = self.pending.as_mut() {
                        for p in w.values.keys() {
                            if let Some(r) = ch.edits.get_mut(&key(&w.group, p)) {
                                r.applied = true;
                            }
                        }
                    }
                    Step::Done(Done::default())
                }
                DeviceResult::Refused(_) | DeviceResult::Failed { .. } => {
                    self.end_by_undo(now, UndoWhy::Failed)
                }
            },
            Flight::Undo { why, plan } => {
                let ch = self
                    .pending
                    .take()
                    .expect("an undo ends the pending change");
                let outcome = match &result {
                    DeviceResult::Ok => {
                        for k in &plan {
                            let r = &ch.edits[k];
                            let (value, source) = match &r.old {
                                Some(v) => (Some(v.clone()), r.old_source),
                                None => match self.startup_value(k) {
                                    Some((v, s)) => (Some(v), Some(s)),
                                    None => (None, None),
                                },
                            };
                            self.slots.insert(k.clone(), Slot { value, source });
                        }
                        Outcome::RolledBack
                    }
                    DeviceResult::Refused(_) | DeviceResult::Failed { .. } => {
                        let empty = BTreeMap::new();
                        let readback = match &result {
                            DeviceResult::Failed { readback, .. } => readback,
                            _ => &empty,
                        };
                        for k in &plan {
                            let r = &ch.edits[k];
                            let read = readback.get(&k.0).and_then(|ps| ps.get(&k.1)).cloned();
                            let slot = match read {
                                Some(v) => {
                                    let source = if Some(&v) == r.old.as_ref() {
                                        r.old_source
                                    } else {
                                        Some(Source::Runtime)
                                    };
                                    Slot {
                                        value: Some(v),
                                        source,
                                    }
                                }
                                None => Slot {
                                    value: None,
                                    source: None,
                                },
                            };
                            self.slots.insert(k.clone(), slot);
                        }
                        Outcome::Partial
                    }
                };
                self.revision += 1;
                let edits = self.edits(&ch.groups, &ch.edits);
                let ev = self.event(now, &ch.token, outcome, edits, &ch.call);
                let reply = match why {
                    UndoWhy::Cancel(answer) => Some(Ok(self.control_reply(answer))),
                    UndoWhy::Deadline | UndoWhy::Failed => None,
                };
                Step::Done(Done {
                    reply,
                    events: vec![ev],
                })
            }
        }
    }

    fn applied_hot(
        &mut self,
        now: Time,
        group: &str,
        request: &SetRequest,
        call: &Call,
        values: &BTreeMap<String, Value>,
        received: Time,
    ) -> Done {
        let mut events = Vec::new();
        if let Some(mut ch) = self.pending.take() {
            self.record(&mut ch.edits, group, values, true);
            if !ch.groups.iter().any(|g| g == group) {
                ch.groups.push(group.to_owned());
            }
            self.pending = Some(ch);
            self.write(group, values);
        } else {
            let mut edits = BTreeMap::new();
            self.record(&mut edits, group, values, true);
            self.write(group, values);
            let token = self.mint();
            let groups = vec![group.to_owned()];
            if let Some(cs) = request.confirm_s {
                self.pending = Some(Change {
                    token,
                    groups,
                    deadline: self.stated(deadline(received, window(cs, self.floor_s))),
                    call: call.clone(),
                    edits,
                    waiting: Vec::new(),
                });
            } else {
                let list = self.edits(&groups, &edits);
                events.push(self.event(now, &token, Outcome::Applied, list, call));
                self.last = Some(Last::of(token, groups, &edits));
            }
        }
        Done {
            reply: Some(Ok(Reply::Set(SetReply::Applied(Box::new(self.view()))))),
            events,
        }
    }
}

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

    #[test]
    fn time_spells_and_reads_rfc3339() {
        assert_eq!(Time::from_millis(0).rfc3339(), "1970-01-01T00:00:00.000Z");
        assert_eq!(Time::from_millis(-1).rfc3339(), "1969-12-31T23:59:59.999Z");
        let t = Time::parse("2028-02-29T12:34:56.789Z").unwrap();
        assert_eq!(t.rfc3339(), "2028-02-29T12:34:56.789Z");
        assert_eq!(
            Time::parse("2026-10-18T14:00:00+02:00"),
            Time::parse("2026-10-18T12:00:00Z")
        );
        assert_eq!(
            Time::parse("2026-10-18t12:00:00.1234z").map(Time::millis),
            Time::parse("2026-10-18T12:00:00.123Z").map(Time::millis)
        );
        for bad in [
            "2027-02-29T00:00:00Z",
            "2026-13-01T00:00:00Z",
            "2026-10-18 12:00:00Z",
            "2026-10-18T12:00:00",
            "2026-10-18T12:00:00.Z",
            "2026-10-18T24:00:00Z",
            "",
        ] {
            assert_eq!(Time::parse(bad), None, "{bad:?}");
        }
    }

    #[test]
    fn a_kind_reads_json_as_the_profile_does() {
        let int = Kind::Integer {
            min: Some(0),
            max: Some(10),
            unit: None,
        };
        assert_eq!(int.check(&serde_json::json!(10)), Ok(Value::Integer(10)));
        assert_eq!(int.check(&serde_json::json!(11)), Err(Misfit::Above(10)));
        assert_eq!(int.check(&serde_json::json!(2.0)), Err(Misfit::Kind));
        assert_eq!(int.check(&serde_json::json!(u64::MAX)), Err(Misfit::Range));
        assert_eq!(Kind::Bool.check(&serde_json::json!(1)), Err(Misfit::Kind));
        assert_eq!(Kind::Text.check(&Json::Null), Err(Misfit::Kind));
    }

    #[test]
    fn the_wire_shapes_are_the_contracts() {
        let reply = SetReply::Pending(PendingReply {
            token: "i1-1".into(),
            apply_at: "1970-01-01T00:00:01.000Z".into(),
            deadline: "1970-01-01T00:02:00.000Z".into(),
        });
        assert_eq!(
            serde_json::to_value(&reply).unwrap(),
            serde_json::json!({"pending": {"token": "i1-1", "apply_at": "1970-01-01T00:00:01.000Z", "deadline": "1970-01-01T00:02:00.000Z"}})
        );
        let p = Parameter {
            name: "mtu".into(),
            kind: Kind::Integer {
                min: Some(68),
                max: None,
                unit: Some("By".into()),
            },
            description: String::new(),
            sensitive: false,
            value: Some(Value::Integer(1500)),
            source: Some(Source::File),
            startup: None,
        };
        let j = serde_json::to_value(&p).unwrap();
        assert_eq!(
            j,
            serde_json::json!({"name": "mtu", "kind": "integer", "min": 68, "unit": "By", "description": "", "value": 1500, "source": "file"})
        );
        assert_eq!(serde_json::from_value::<Parameter>(j).unwrap(), p);
        let decl: ParamDecl = serde_json::from_value(serde_json::json!({"name": "pin", "kind": "text", "description": "", "sensitive": true, "value": "x"})).unwrap();
        assert!(decl.sensitive);
        assert_eq!(decl.kind, Kind::Text);
    }

    /// scenarios.md's `rf`, reduced: `duty` and `sim` hot, `radio` reach.
    fn rf() -> Owner {
        let int = |min, max| Kind::Integer {
            min: Some(min),
            max: Some(max),
            unit: None,
        };
        let group = |name: &str, class, p: ParamDecl| GroupDecl {
            name: name.into(),
            class,
            description: String::new(),
            writable: true,
            parameters: vec![p],
        };
        let param = |name: &str, kind, sensitive| ParamDecl {
            name: name.into(),
            kind,
            description: String::new(),
            sensitive,
        };
        let schema = Schema {
            groups: vec![
                group(
                    "duty",
                    Class::Hot,
                    param("fraction_ppm", int(0, 1_000_000), false),
                ),
                group(
                    "radio",
                    Class::Reach,
                    param("frequency_hz", int(0, 1_000_000_000), false),
                ),
                group("sim", Class::Hot, param("pin", Kind::Text, true)),
                group("tx", Class::Hot, param("power", int(0, 30), false)),
            ],
        };
        let startup = [
            ("duty", "fraction_ppm", Value::Integer(10_000)),
            ("radio", "frequency_hz", Value::Integer(868_100_000)),
            ("tx", "power", Value::Integer(14)),
        ]
        .into_iter()
        .map(|(g, p, v)| {
            (
                g.to_owned(),
                BTreeMap::from([(p.to_owned(), (v, Source::File))]),
            )
        })
        .collect();
        Owner::start(Start {
            service: "lab/rf0".into(),
            instance: "i1".into(),
            schema,
            startup,
            overlay: BTreeMap::new(),
            floor_s: 10,
            apply_after: Duration::from_secs(1),
            persist: true,
            events: vec![Time::from_millis(0)],
        })
        .unwrap()
    }

    fn doc(revision: u64, values: Json) -> DesiredConfig {
        serde_json::from_value(serde_json::json!({"revision": revision, "values": values})).unwrap()
    }

    /// §2.18 "Converging": one set per differing group, bytewise; a group
    /// already at its values is skipped; a pending change is waited out;
    /// a reach group refuses the document whole, applying nothing.
    #[test]
    fn converging_a_desired_document() {
        let mut o = rf();
        let t = Time::from_millis(10_000);
        let d = doc(
            1,
            serde_json::json!({"tx": {"power": 20}, "duty": {"fraction_ppm": 10000}}),
        );
        let Converge::Set { group, request } = o.converge(&d) else {
            panic!("a set")
        };
        assert_eq!(group, "tx", "duty already runs its value");
        assert_eq!(
            request.values,
            BTreeMap::from([("power".into(), 20.into())])
        );
        assert_eq!((request.confirm_s, request.token.as_ref()), (None, None));
        let Step::Act(_) = o.set(t, &group, &request, &Call::default()) else {
            panic!("a hot apply")
        };
        let Step::Done(done) = o.finish(t, DeviceResult::Ok) else {
            panic!("done")
        };
        assert_eq!(done.events[0].outcome, Outcome::Applied);
        let Converge::Converged(r) = o.converge(&d) else {
            panic!("converged")
        };
        assert_eq!(
            (r.observed_revision, r.outcome),
            (1, DesiredOutcome::Converged)
        );

        // A pending change is waited out.
        let reach = SetRequest {
            values: BTreeMap::from([("frequency_hz".into(), 869_525_000.into())]),
            confirm_s: Some(60),
            ..SetRequest::default()
        };
        let _ = o.set(t, "radio", &reach, &Call::default());
        assert_eq!(
            o.converge(&doc(2, serde_json::json!({"tx": {"power": 1}}))),
            Converge::Wait
        );

        // Refused whole: the reach group, though tx is legal on its own.
        let mut o = rf();
        let d = doc(
            3,
            serde_json::json!({"tx": {"power": 1}, "radio": {"frequency_hz": 1}}),
        );
        let Converge::Refused(r) = o.converge(&d) else {
            panic!("refused")
        };
        assert_eq!(r.outcome, DesiredOutcome::Refused);
        assert_eq!(
            r.refusal,
            Some(DesiredRefusal {
                code: DesiredCode::Reach,
                group: "radio".into(),
                parameter: None
            })
        );
        o.report_desired(Some(r.clone()));
        assert_eq!(o.desired(), Some(&r));
        assert_eq!(o.view().desired, Some(r));
    }

    /// §2.18: a converging set refused is `failed`, with its code and group.
    #[test]
    fn a_converging_set_refused_is_failed() {
        let busy = Refusal::busy("the rate");
        let r = desired_failed(4, "tx", &busy);
        assert_eq!(
            (r.observed_revision, r.outcome),
            (4, DesiredOutcome::Failed)
        );
        assert_eq!(r.refusal.as_ref().map(|r| r.code), Some(DesiredCode::Busy));
        let refused = Refusal::app(ErrorCode::DeviceRefused, None, "no");
        let r = desired_failed(4, "tx", &refused);
        assert_eq!(
            r.refusal,
            Some(DesiredRefusal {
                code: DesiredCode::DeviceRefused,
                group: "tx".into(),
                parameter: None
            })
        );
    }

    /// §2.17, core §2.7: the events of the last hour carry to the next
    /// instance, and the restart keeps them.
    #[test]
    fn the_published_events_carry_to_the_next_instance() {
        let mut o = rf();
        let t = Time::from_millis(3_000_000);
        let req = SetRequest {
            values: BTreeMap::from([("power".into(), 3.into())]),
            ..SetRequest::default()
        };
        let _ = o.set(t, "tx", &req, &Call::default());
        let _ = o.finish(t, DeviceResult::Ok);
        assert_eq!(o.published(t), vec![Time::from_millis(0), t]);
        let later = Time::from_millis(3_600_000);
        assert_eq!(o.published(later), vec![t], "an hour on, the first is out");
        assert_eq!(o.restart("i2").published(later), vec![t]);
    }

    /// §2.12: a re-mint returns the device to its startup values first,
    /// each parameter whose running value is not one; a parameter set at
    /// runtime that starts unknown cannot be.
    #[test]
    fn a_restart_plan_returns_what_runs_off_its_startup_value() {
        let mut o = rf();
        let t = Time::from_millis(3_000_000);
        assert_eq!(o.restart_plan(), Ok(Vec::new()), "the startup values run");
        let set = |p: &str, v: Json| SetRequest {
            values: BTreeMap::from([(p.to_owned(), v)]),
            ..SetRequest::default()
        };
        let _ = o.set(t, "tx", &set("power", 3.into()), &Call::default());
        let _ = o.finish(t, DeviceResult::Ok);
        assert_eq!(
            o.restart_plan(),
            Ok(vec![Restore {
                group: "tx".into(),
                parameter: "power".into(),
                value: Value::Integer(14),
            }])
        );
        let _ = o.set(t, "sim", &set("pin", "1234".into()), &Call::default());
        let _ = o.finish(t, DeviceResult::Ok);
        assert_eq!(
            o.restart_plan(),
            Err(key("sim", "pin")),
            "pin starts unknown"
        );
        assert_eq!(o.restart("i2").restart_plan(), Ok(Vec::new()));
    }

    /// §2.15: the device's words about an act that sets a sensitive value,
    /// or restores one, are not logged.
    #[test]
    fn device_words_leave_a_sensitive_act_out() {
        let o = rf();
        let apply = |g: &str, p: &str, v: Value| Act::Apply {
            group: g.into(),
            values: BTreeMap::from([(p.into(), v)]),
        };
        let schema = o.schema();
        assert_eq!(
            device_words(schema, &apply("tx", "power", Value::Integer(1)), "no"),
            Some("no")
        );
        assert_eq!(
            device_words(
                schema,
                &apply("sim", "pin", Value::Text("1234".into())),
                "1234?"
            ),
            None
        );
        assert_eq!(
            device_words(schema, &apply("nope", "x", Value::Bool(true)), "x"),
            None,
            "unknown: it cannot tell"
        );
        let undo = Act::Undo {
            restore: vec![Restore {
                group: "sim".into(),
                parameter: "pin".into(),
                value: Value::Text("0000".into()),
            }],
        };
        assert!(undo.carries_sensitive(schema));
        assert_eq!(device_words(schema, &undo, "0000"), None);
    }
}