tilo-resource 0.5.0

The Tilo resource layer: typed, hierarchical app resources.
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
//! The resource contract: what any resource type provides so that it gets
//! history, undo, collaboration, permissions, palette/agent/script exposure,
//! search and replay without writing any of them.

use std::any::TypeId;
use std::collections::HashMap;
use std::sync::{Arc, Mutex, OnceLock};

use serde::Serialize;
use serde::de::DeserializeOwned;
use tilo_actions::{
    ActionArgs, ActionError, ActionNeed, ActionParam, ActionRegistry, ActionSpec, ActionType,
    EncodedAction, ExecutionLocus, OperationKind, ParamType, Target,
};

use crate::action::ActionKind;
use crate::delta::Delta;
use crate::model::{Doc, ModelError};
use crate::path::Edit;
use crate::reader::Demand;
use crate::vocabulary::{Builds, Built, Declaration, Vocabulary, vocabulary};
use tilo_lock::MutexRecover as _;

mod head;
pub use head::{HeadInputs, head_inputs, publish_head, publish_head_of};

mod search_entry;
pub use search_entry::{SearchBody, SearchEntry, SearchPiece, SearchText, SearchWeight};

/// A resource type. `#[resource]` implements it for a `#[derive(Model)]`
/// record, which is how every app declares its own. The SDK implements it by
/// hand for the shared types with a storage layout of their own (a rich-text
/// document, plain text), which apps hold as fields; an app never does
/// (docs/architecture/resources.md §8).
///
/// The contract is deliberately small:
///
/// * [`read`](Self::read) — materialise the state views render, from the live
///   document *or* from any historical version (time travel is just `read` on
///   an older document);
/// * [`refresh`](Self::refresh) — optionally, bring a state up to date after a
///   change by re-reading only what the change touched, so an edit costs as
///   much as the edit rather than as much as the resource;
/// * [`load`](Self::load) — optionally, read on demand the parts of a large
///   resource that views are looking at (the pages of a long document on
///   screen), so opening or refreshing it never reads all of it;
/// * [`Action`](Self::Action) — the replayable mutation vocabulary: a
///   serializable value whose `apply` is a pure function of the document;
/// * [`declarations`](Self::declarations) — which mutations are offered by
///   name to the palette, agents and scripts, with typed parameters.
///
/// Everything else has a default.
pub trait Resource: Sized + 'static {
    /// Stable kind of record this resource lives in, e.g. `"notes.notebook"`.
    const KIND: &'static str;
    /// Human name of one resource of this kind, e.g. `"Notebook"`, in the
    /// language the declaration is written in. What a person reads is
    /// [`label`](Self::label), which a host's catalogue translates.
    const LABEL: &'static str;
    /// The catalogue beside the crate that declares it, whose entry under
    /// the kind's [`message_key`](crate::label::message_key) names it in
    /// each language: `None` reads only the catalogues the host loaded.
    const CATALOGUE: Option<&'static crate::label::Catalogue> = None;
    /// The app that publishes records of this kind, e.g. `"so.tilo.notes"`:
    /// the framework app's id, or for a resource that names its app in its
    /// `#[resource(app = "…")]` declaration, that. It is part of the
    /// [`ActionKey`](tilo_actions::ActionKey) every typed reference of the
    /// resource names its actions by.
    const APP_ID: &'static str = crate::kind::DEFAULT_APP;
    /// The registry type id every action of this resource is replayed under.
    const ACTION_TYPE: &'static str = Self::KIND;

    /// The name a person reads this kind by, in their language: what
    /// [`LABEL`](Self::LABEL) declares, resolved through the catalogue a
    /// host installed ([`crate::label`]), so every kind is named in the
    /// language of the desktop it is published on.
    fn label() -> String {
        crate::label::localized(Self::KIND, Self::LABEL, Self::CATALOGUE)
    }

    /// What views render. For a record resource this is the record itself.
    type State: 'static;
    /// The replayable mutation. Must be deterministic: no clock, no RNG, no
    /// local state — use [`ActionCx`](crate::ActionCx) for ids and time.
    type Action: tilo_actions::Action + Serialize + DeserializeOwned + Clone + 'static;

    /// Read the state from a document.
    ///
    /// # Errors
    /// Returns [`ModelError`] when the document does not hold this resource.
    fn read(doc: &Doc) -> Result<Self::State, ModelError>;

    /// Bring `state`, read earlier from this document, up to date after the
    /// changes in `delta`. Re-read only what they touched: this runs on every
    /// keystroke, local or a member's. The default reads everything
    /// again, which is right for small resources.
    ///
    /// # Errors
    /// Returns [`ModelError`] when the document does not hold this resource.
    fn refresh(state: &mut Self::State, doc: &Doc, delta: &Delta) -> Result<(), ModelError> {
        if !delta.is_empty() {
            *state = Self::read(doc)?;
        }
        Ok(())
    }

    /// A copy of `state` for [`refresh`](Self::refresh) to bring up to date
    /// while the state the reader holds is shared (a view still holds the
    /// last one): refreshing a copy reads only what a change touched, where
    /// without one the state is read whole. `#[resource]` copies a `Clone`
    /// record; the default has none.
    fn copy_state(_state: &Self::State) -> Option<Self::State> {
        None
    }

    /// Opt in to reusing the document-owned publication between changes.
    ///
    /// Return an epoch for every non-document input used by declarations,
    /// children, views or local operations (for example the local date of a
    /// daily-note action). The framework also invalidates on state and locale
    /// revisions; surface bindings and effect availability remain live.
    /// `None` preserves publication on every request for dynamic resources.
    fn publication_cache_epoch(_state: &Self::State) -> Option<String> {
        None
    }

    /// Where `obj` sits in the document, when the state already knows: the
    /// path from the root to it. A change to an object the state has read
    /// (the paragraph being typed in) is then placed without asking the
    /// document, which for a large document is the costly part of reading a
    /// change. The default knows nothing, and the document is asked.
    fn locate(state: &Self::State, obj: &automerge::ObjId) -> Option<crate::delta::ObjPath> {
        let _ = (state, obj);
        None
    }

    /// Make sure the parts of the state views asked for are read, and drop
    /// parts nobody asks for any more. For a resource too large to read
    /// whole, [`read`](Self::read) reads a spine (the order of a document's
    /// paragraphs, the rows of a sheet) and this reads the parts on screen.
    /// Called after every read and refresh and whenever the demand changes,
    /// so it must be cheap when everything demanded is already there. The
    /// default reads nothing: the state is read whole.
    ///
    /// # Errors
    /// Returns [`ModelError`] when the document does not hold this resource.
    fn load(state: &mut Self::State, doc: &Doc, demand: &Demand) -> Result<(), ModelError> {
        let _ = (state, doc, demand);
        Ok(())
    }

    /// Write the initial content of a brand-new record: its genesis.
    ///
    /// The genesis is made under an actor derived from the record's identity,
    /// at time zero, so it is the same change byte for byte on every device:
    /// two people who each create the same record before they sync (a
    /// workspace's default record, the record of one file) converge on one
    /// record rather than two competing roots. It must therefore depend on
    /// nothing but the resource type — not on who creates it, the device, the
    /// clock or a file. Content that does depend on those (the creator as
    /// owner, a first-run import of settings that already exist) is the app's
    /// seed, applied as actions right after the genesis (`ResourceApp::seed`
    /// in `tilo-app`).
    fn initialize(_doc: &mut Doc) -> Result<(), ModelError> {
        Ok(())
    }

    /// Whether `next`, applied right after `previous` by the same person,
    /// continues it as one undo step — the characters of a word typed one
    /// keystroke at a time, the values a slider passes through in one drag.
    /// The default keeps every action its own step.
    ///
    /// Immediate edits (`Dispatcher::apply_now` in `tilo-app`) and native
    /// keyboard/IME edits from action-bound text fields may continue one
    /// another. Programmatic/agent invocations remain separate steps.
    /// A surface ends an immediate pointer gesture
    /// (`Dispatcher::settle`) when the pointer is let go, so the next drag
    /// of the same slider is a step of its own.
    fn coalesces(previous: &Self::Action, next: &Self::Action) -> bool {
        let _ = (previous, next);
        false
    }

    /// Whether a later action may continue `action` ([`coalesces`](Self::coalesces)),
    /// so its undo step stays open for it. One that never continues — a
    /// paragraph split after a typed word, a block moved — is a step of its
    /// own, recorded at once. The default keeps every step open for what may
    /// follow.
    fn continuable(action: &Self::Action) -> bool {
        let _ = action;
        true
    }

    /// Where `action`, just applied, leaves the member who took it, read
    /// off the state after it: the paragraph an append wrote and the caret
    /// at its end. Every member's view draws that member there,
    /// so one with no pointer or caret of its own (an agent) shows where it
    /// works. The default places it nowhere in particular.
    fn lands(state: &Self::State, action: &Self::Action) -> Option<Place> {
        let _ = (state, action);
        None
    }

    /// Whether [`Self::lands`] reads the state to place whoever took
    /// `action`: `false` where it places them nowhere whatever the state
    /// holds, so a host placing them after each action need not read a
    /// record of thousands of items to learn that. The default reads it.
    fn lands_on_state(action: &Self::Action) -> bool {
        let _ = action;
        true
    }

    /// The one field of the record `action` writes, when it writes only one:
    /// a reply or a note writes the `comments`, so a grant on that field
    /// (what someone who may only comment holds) reaches it. `None` by
    /// default. A declared action that builds it names the same field with
    /// [`ActionDecl::below_field`].
    fn field_of(action: &Self::Action) -> Option<&'static str> {
        let _ = action;
        None
    }

    /// The least any of the resource's actions is ([`kind_of`](Self::kind_of),
    /// [`field_of`](Self::field_of)): what the generic [`APPLY`] and group
    /// actions are offered under, each invocation then decided by what its
    /// value is. An undoable change of the record by default; an undoable
    /// change of its `comments` for a resource someone who may only comment
    /// can still reply in.
    fn least_need() -> ActionNeed {
        least_need_declared(&vocabulary::<Self>().declarations())
    }

    /// Mutations offered by name. The generic [`APPLY`] action is always
    /// offered in addition, so any typed value can reach the host.
    fn declarations() -> Vec<ActionDecl<Self>> {
        Vec::new()
    }

    /// The JSON Schema of [`Action`](Self::Action)'s serde form, published as
    /// the schema of the generic [`APPLY`] operation's argument, so agents
    /// and scripts can read the edit vocabulary from the descriptor and
    /// binding refuses a malformed edit by name. A variant that only
    /// restates a declaration is published as a reference to it. Return `Some(<Self::Action as
    /// JsonSchema>::json_schema())` for an action type deriving
    /// [`JsonSchema`](crate::JsonSchema); `#[resource]` describes its
    /// operations from their declarations. The default publishes no schema.
    fn action_schema() -> Option<serde_json::Value> {
        None
    }

    /// Resources nested inside this one (a track's clips, a list's items,
    /// a page's rich-text body), each exporting actions with their arguments
    /// already bound. Published beneath the root resource for the palette,
    /// agents and scripts — the same API as the root, not a second tree.
    fn children(_state: &Self::State) -> Vec<tilo_actions::ResourceSpec> {
        Vec::new()
    }

    /// The effects offered on the item `item` of the collection `field`,
    /// bound to it (`#[resource(effects = E)]` with `#[effect(item = field)]`
    /// variants): published on the item resource beside its item verbs.
    fn item_effects(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ActionSpec> {
        Vec::new()
    }

    /// The views the item `item` of the collection `field` offers
    /// (`#[resource(item_views = path)]`): published on the item resource,
    /// so a link to the item opens it in one, each opened by one of the
    /// item's own actions ([`item_effects`](Self::item_effects)).
    fn item_views(_field: &str, _item: &crate::Id) -> Vec<tilo_actions::ResourceViewSpec> {
        Vec::new()
    }

    /// [`children`](Self::children) split into the children that are not
    /// items and the items of the record's collections, so a publisher can
    /// keep the item children it built for an earlier version and build
    /// only those whose label changed. `others` followed by
    /// [`item_children`](crate::items::item_children) of the rest must be
    /// exactly `children`. The default puts every child in `others`;
    /// `#[resource]` splits off its item collections.
    fn children_parts(state: &Self::State) -> crate::items::ChildrenParts {
        crate::items::ChildrenParts {
            others: Self::children(state),
            kept: std::rc::Rc::default(),
            items: Vec::new(),
            item_actions: Vec::new(),
        }
    }

    /// The ids of the [`declarations`](Self::declarations) that
    /// [`children`](Self::children) offer on some child with arguments
    /// already bound (an item action on each item of a list), which the
    /// resource then publishes for scripts rather than the palette.
    ///
    /// [`publish_head`] asks this to publish the resource's own actions
    /// without building its children, so a resource with many children
    /// answers from what it knows about them: `#[resource]` from how many
    /// items each collection holds. The default builds the children and
    /// looks.
    fn children_offer_bound(state: &Self::State) -> Vec<&'static str> {
        offered_bound_ids(&Self::children(state), &vocabulary::<Self>().declarations())
    }

    /// The nested resource `id`, when [`children`](Self::children) leaves it
    /// out. A resource with more children than a published tree should carry
    /// (a book of contacts, a long history) publishes a bounded page from
    /// `children` and resolves the rest here, so an action addressed to any
    /// of them still reaches it through the same API. The default resolves
    /// nothing beyond `children`.
    fn child(_state: &Self::State, _id: &str) -> Option<tilo_actions::ResourceSpec> {
        None
    }

    /// View and effect operations on this resource: local presentation and
    /// jobs that have no document delta (show a week, start a sync drain,
    /// open a system file picker). They are published on the same tree as
    /// [`declarations`](Self::declarations). A document mutation does not
    /// belong here — it is a [`declarations`](Self::declarations) entry or
    /// [`APPLY`]. `publish` drops a `Document` spec so it cannot become a
    /// second write path.
    fn local_operations() -> Vec<tilo_actions::ActionSpec> {
        Vec::new()
    }

    /// Named presentations of this resource (editor, reader) with stable ids.
    /// Not an action called `open`: ordinary presentation toggles never become
    /// composable views by accident. Defaults to none.
    fn views(_state: &Self::State) -> Vec<tilo_actions::ResourceViewSpec> {
        Vec::new()
    }

    /// Entries for the system search index.
    fn search_scopes(_state: &Self::State) -> Vec<ScopeDecl> {
        Vec::new()
    }

    fn search(_state: &Self::State) -> Vec<SearchEntry> {
        Vec::new()
    }

    /// Whether [`read_content`](Self::read_content) answers. A resource that
    /// does is published with the framework's `read` operation, so a script,
    /// an agent or an assistive tool reads what it holds as typed data through
    /// the same API, permissions and audit as every other action — never
    /// from a screenshot.
    const READABLE: bool = false;

    /// Whether this exact child is part of the public document projection
    /// answered by `read_content`. Defaults to false even for readable parents.
    /// This is a structural declaration, not a permission check: it must not
    /// perform IO, inspect private view state, or probe by executing a read.
    /// Eligibility must remain stable while the child's identity exists.
    fn document_child(_state: &Self::State, _id: &str) -> bool {
        false
    }

    /// What the resource holds, as JSON a caller can act on: with no `item`,
    /// the resource itself (a notebook's pages); with `item`, the nested
    /// resource of that id from [`children`](Self::children) (one page's
    /// title and blocks). Read from `doc`, the committed document, so the
    /// answer is never older than the action that preceded it. Called only
    /// when [`READABLE`](Self::READABLE) is set.
    fn read_content(
        state: &Self::State,
        doc: &Doc,
        item: Option<&str>,
    ) -> Result<serde_json::Value, String> {
        let _ = (state, doc, item);
        Err(format!("a {} does not answer reads", Self::LABEL))
    }

    /// Whether [`facts`](Self::facts) answers. A resource that does is
    /// published with the framework's `facts` read, which an agent's host
    /// shows when it checks work done on the resource.
    const HAS_FACTS: bool = false;

    /// The record's own table, for a resource that is a record: what
    /// generic code reads a field's value through without the record's type
    /// (the framework, a window's [`Reactions`](crate::Reactions) with
    /// [`record_reactions`](crate::reactions::record_reactions)).
    /// `#[resource]` names the record's; none otherwise.
    const RESOURCE_TABLE: Option<&'static crate::table::ModelTable> = None;

    /// What the resource holds as a compact summary of plain values, meant
    /// for checking it against a request: names, times, counts and text as
    /// a person would state them (a cut's shots with their source, in and
    /// out points; a deck's slide titles), not ids or storage. Two answers
    /// compare field by field, so keep a list's order meaningful and its
    /// items' keys stable. Called only when [`HAS_FACTS`](Self::HAS_FACTS)
    /// is set.
    fn facts(state: &Self::State, doc: &Doc) -> Result<serde_json::Value, String> {
        let _ = (state, doc);
        Err(format!("a {} states no facts", Self::LABEL))
    }

    /// Whether [`Self::answer`] answers anything. Working out the changes it
    /// reads costs as much as the change is large, so a resource whose
    /// answer is the default's nothing is not asked. `#[resource]` sets it
    /// with `answer = path`.
    const ANSWERS: bool = false;

    /// What declared action `action` (one [`ActionDecl::answering`]) made,
    /// answered to its caller once it applied to `doc` as `changes`: the
    /// ids it minted, the area it selected, a warning that what it drew is
    /// hidden. A compact summary, so the caller needs no second read to
    /// see what happened. The default answers nothing.
    fn answer(
        _doc: &Doc,
        _action: &str,
        _changes: &[automerge::Patch],
    ) -> Option<serde_json::Value> {
        None
    }

    /// The stored layout of this resource's content, for services that act
    /// on it generically: History restores a past version through it, field
    /// by field and item by item. `#[resource]` returns the record's
    /// [`Model::SHAPE`](crate::Model::SHAPE); the default opts out.
    fn shape() -> Option<crate::Shape> {
        None
    }

    /// The state as its record's JSON ([`Model::to_json`](crate::Model::to_json)):
    /// what a field that weakens one way holds now. `#[resource]` returns
    /// the record's; the default knows none, so any change of such a field
    /// counts as weakening.
    fn state_json(state: &Self::State) -> Option<serde_json::Value> {
        let _ = state;
        None
    }

    /// The storage version documents of this resource are written at;
    /// `#[resource(version = N)]` raises it with each incompatible change
    /// and [`Self::migrate`] brings older documents up to it.
    const VERSION: u32 = 1;

    /// Who reads a record of this kind, when not every member of the
    /// workspace: `"author"`, `"author until <field>"` or a `Set<Actor>`
    /// field's name, as `#[resource(readers = "...")]` writes it
    /// ([`tilo_actions::surface::ReaderRule`]); empty for every member.
    const READERS: &'static str = "";

    /// Whether [`Self::migrate`] is registered (`#[resource(migrate = path)]`), so a change of
    /// the framework's migration is declared in its surface.
    const MIGRATES: bool = false;

    /// Bring a document stored at version `from` up to [`Self::VERSION`],
    /// reading its old shape with the model helpers. Called once per
    /// document by [`crate::evolution::migrate`].
    fn migrate(doc: &mut Doc, from: u32) -> Result<(), ModelError> {
        let _ = doc;
        Err(ModelError::invalid(format!(
            "{} has no migration from storage version {from}",
            Self::LABEL
        )))
    }

    /// The public surface: verbs, their parameters and kinds, and the
    /// stored fields ([`crate::surface`]).
    #[must_use]
    fn surface() -> crate::surface::Surface {
        crate::surface::surface_of::<Self>()
    }

    /// Whether the resource's actions include field edits ([`Edit`]),
    /// published as [`FIELD_EDIT`]. `#[resource]` records have them.
    const EDITS: bool = false;

    /// The action a field edit of this resource is, when it has field edits
    /// ([`Self::EDITS`]).
    fn edit_action(edit: Edit<Self>) -> Option<Self::Action> {
        let _ = edit;
        None
    }

    /// Stamp the origin's clock on an action as the API admits it. A caller
    /// never supplies the time an action carries.
    fn stamp(action: &mut Self::Action, now_ms: i64) {
        let _ = (action, now_ms);
    }

    /// The schemas of the own vocabularies of the record's fields
    /// ([`Operations`](crate::Operations)), by field path pattern (`*` for
    /// every item): what a field edit in that vocabulary carries.
    fn op_schemas() -> Vec<(String, serde_json::Value)> {
        Vec::new()
    }

    /// Whether the declared action `action` can be taken in `state`, and why
    /// not when it cannot. `#[resource(available = path)]` answers it.
    fn availability(state: &Self::State, action: &str) -> tilo_actions::Availability {
        let _ = (state, action);
        tilo_actions::Availability::Available
    }

    /// The first content of a new record, written by its creator once it is
    /// created: nobody's undo step. `#[resource(seed = path)]` provides it.
    fn seed() -> Option<Self::Action> {
        None
    }

    /// What kind of action `action` is: whether it only reads, changes only
    /// the document, or reaches outside it. Derived by `#[resource]` from
    /// what each verb is able to do, never declared.
    fn kind_of(action: &Self::Action) -> ActionKind {
        let _ = action;
        ActionKind::Undoable
    }

    /// Whether `action` is one only the app's own code applies
    /// (`#[action(by_app)]`): the app's bookkeeping of the record, such as
    /// what its engine listed. It has no declaration, so it is not
    /// published, nothing builds it by its id, and the generic [`APPLY`] and
    /// every API that decodes an action refuse it ([`by_app_refusal`]).
    /// The app applies it to a record it holds.
    fn by_app(action: &Self::Action) -> bool {
        let _ = action;
        false
    }

    /// The action `id` only the app's own code applies, built from
    /// `arguments` where the app invokes it
    /// ([`Invoke::build`](crate::Invoke::build)); `None` for any other id.
    /// `#[resource]` generates it.
    fn build_by_app(
        id: &str,
        arguments: &serde_json::Map<String, serde_json::Value>,
        now_ms: i64,
    ) -> Option<Result<Self::Action, String>> {
        let _ = (id, arguments, now_ms);
        None
    }

    /// The item of the resource's collections `action` acts on: an item verb's
    /// (its first parameter), or the one a field edit's path passes through.
    /// What a store keeping a collection's items in several resources routes
    /// the action by. `#[resource]` generates it; `None` by default.
    fn action_item(action: &Self::Action) -> Option<crate::Id> {
        let _ = action;
        None
    }

    /// The entries `action` lists that each name an item, in order: the
    /// item an entry names, or `None` for an entry that makes a new one
    /// (a message arriving). A verb declares the parameter it lists them in
    /// with `#[action(items = param)]`; `None` for any other action.
    fn listed_items(action: &Self::Action) -> Option<Vec<Option<crate::Id>>> {
        let _ = action;
        None
    }

    /// `action`, a verb listing items ([`listed_items`](Self::listed_items)),
    /// over only its entries at the positions `keep`: the share of it a
    /// resource holding those items carries out.
    fn keep_listed(action: &Self::Action, keep: &[usize]) -> Option<Self::Action> {
        let _ = (action, keep);
        None
    }

    /// Register this resource's replay decoder. Override to register an
    /// existing vocabulary under additional type ids.
    fn register(registry: &mut ActionRegistry) {
        registry.register::<Self::Action>(Self::ACTION_TYPE);
    }
}

/// An entry of a verb's list of items (`#[action(items = param)]`): the item
/// it names, or `None` when it makes a new one.
pub trait NamesItem: Clone {
    fn named_item(&self) -> Option<crate::Id>;
}

impl NamesItem for crate::Id {
    fn named_item(&self) -> Option<crate::Id> {
        Some(self.clone())
    }
}

impl NamesItem for String {
    fn named_item(&self) -> Option<crate::Id> {
        Some(crate::Id::from_raw(self.clone()))
    }
}

/// [`Resource::listed_items`] of the list `entries`.
#[doc(hidden)]
pub fn listed_of<E: NamesItem>(entries: &[E]) -> Vec<Option<crate::Id>> {
    entries.iter().map(NamesItem::named_item).collect()
}

/// The entries of `entries` at the positions `keep`, in order.
#[doc(hidden)]
#[must_use]
pub fn kept_of<E: NamesItem>(entries: &[E], keep: &[usize]) -> Vec<E> {
    keep.iter()
        .filter_map(|at| entries.get(*at).cloned())
        .collect()
}

/// The id of the action every resource publishes that applies one typed
/// [`Resource::Action`] given as JSON. It is how a custom surface, an agent or
/// a script submits an edit that has no named declaration (a drag with its
/// final geometry) through the same permission-checked, undoable path.
///
/// It is for agents ([`tilo_actions::Audience::Agents`]): never offered in
/// the palette or a menu, where a
/// person picks named actions. Its risk is the value's own
/// ([`tilo_actions::Action::risk`]), so a destructive value — deleting a clip —
/// needs the same confirmation a declared destructive action does, while an
/// ordinary edit applies directly.
pub const APPLY: &str = "apply";
/// The parameter of [`APPLY`] carrying the JSON-encoded action.
pub const APPLY_PARAM: &str = "action";

/// The id of the action a resource with field edits ([`Resource::EDITS`])
/// publishes for them: one [`Edit`] given as JSON, a path and an operation.
pub const FIELD_EDIT: &str = "field-edit";
/// The parameter of [`FIELD_EDIT`] carrying the edit.
pub const EDIT_PARAM: &str = "edit";

/// Read a field edit given as JSON into the action it is.
fn read_edit(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
    let edit = vocabulary.rooted_edit(Edit::<()>::from_json(value)?)?;
    match (vocabulary.edit)(edit) {
        Some(action) => Ok(action),
        None => Err(format!("{} has no field edits", vocabulary.label)),
    }
}

/// The schema of a field edit of `R`: one alternative per editable path of
/// its stored shape — the path's steps, the operations its type takes, the
/// value it holds, its title and flags — so an agent builds a valid edit
/// from the published descriptor alone. A resource without a shape gets
/// the generic one, with its fields' own operations named for `rich`.
pub(crate) fn edit_schema(vocabulary: &Vocabulary) -> serde_json::Value {
    let ops = (vocabulary.op_schemas)();
    if let Some(shape) = (vocabulary.shape)()
        && !shape.fields().is_empty()
    {
        let mut alternatives = Vec::new();
        edit_paths(shape, &[], "", &ops, &mut alternatives);
        if !alternatives.is_empty() {
            return described_edit(&alternatives, &ops);
        }
    }
    generic_edit_schema(&ops, |_| true)
}

/// The schema a field edit is checked against, with every editable path
/// described: its template, the operations it takes, the value's schema,
/// its title and flags (the description), and one example edit per path
/// (the examples) — what an agent builds a field edit from.
fn described_edit(
    alternatives: &[serde_json::Value],
    ops: &[(String, serde_json::Value)],
) -> serde_json::Value {
    // The operations some path of the record takes: the schema names only
    // those, and only their arguments.
    let taken: Vec<String> = alternatives
        .iter()
        .filter_map(|alternative| alternative.pointer("/properties/op/enum")?.as_array())
        .flatten()
        .filter_map(serde_json::Value::as_str)
        .map(str::to_owned)
        .collect();
    let mut schema = generic_edit_schema(ops, |op| taken.iter().any(|taken| taken == op));
    let mut lines = vec![
        "A field edit: `path` from the record (fields by name, items by id, map entries by key) and `op` with its arguments. Editable paths:".to_owned(),
    ];
    let mut examples = Vec::new();
    let mut shapes: Vec<Vec<String>> = Vec::new();
    // Each listed path, its line, and the fields named on that line when it
    // is a record stored field by field.
    let mut listed: Vec<(String, String, Vec<String>)> = Vec::new();
    let nexts = alternatives.iter().skip(1).map(Some).chain([None]);
    for (alternative, next) in alternatives.iter().zip(nexts) {
        let at = |pointer: &str| alternative.pointer(pointer).cloned().unwrap_or_default();
        let template = at("/properties/path/examples/0");
        let ops: Vec<String> = at("/properties/op/enum")
            .as_array()
            .map(|ops| {
                ops.iter()
                    .filter_map(serde_json::Value::as_str)
                    .map(str::to_owned)
                    .collect()
            })
            .unwrap_or_default();
        let value = at("/properties/value");
        let text = |key: &str| at(key).as_str().unwrap_or_default().to_owned();
        let title = text("/title");
        // One example per shape of path (a field, an item's field, an
        // entry): the listing names every path of each shape.
        let shape: Vec<String> = template
            .as_array()
            .map(|steps| {
                steps
                    .iter()
                    .filter_map(|step| step.as_object()?.keys().next().cloned())
                    .collect()
            })
            .unwrap_or_default();
        // A field of a record stored field by field, only ever set and with
        // no paths inside it, is named on its record's line: its meaning is
        // the record's, and a line of its own would repeat the record's
        // path for every field.
        let leaf = next.is_none_or(|next| {
            next.get("title")
                .and_then(serde_json::Value::as_str)
                .is_none_or(|next| !next.starts_with(&format!("{title}.")))
        });
        let in_resource = shape
            .iter()
            .rev()
            .take(2)
            .filter(|kind| *kind == "field")
            .count()
            == 2;
        let record = title
            .rsplit_once('.')
            .and_then(|(parent, key)| {
                listed
                    .iter_mut()
                    .find(|(path, ..)| path == parent)
                    .map(|(_, _, fields)| (fields, key))
            })
            .filter(|_| in_resource && leaf && ops == ["set"]);
        if let Some((fields, key)) = record {
            fields.push(format!("`{key}`"));
        } else {
            let kind = value_kind(&value);
            let usage: Vec<String> = ops.iter().map(|op| crate::path::op_usage(op)).collect();
            let line = format!(
                "- `{title}`: {} — {}{}",
                usage.join(", "),
                text("/description"),
                kind.map_or_else(String::new, |kind| format!(" ({kind})")),
            );
            listed.push((title.clone(), line, Vec::new()));
        }
        if shapes.contains(&shape) {
            continue;
        }
        shapes.push(shape);
        let mut example = serde_json::Map::new();
        example.insert("path".into(), template);
        if let Some(op) = ops.first() {
            example.insert("op".into(), op.clone().into());
        }
        examples.push(serde_json::Value::Object(example));
    }
    lines.extend(listed.into_iter().map(|(_, line, fields)| {
        if fields.is_empty() {
            line
        } else {
            format!("{line}; set one field of it: {}", fields.join(", "))
        }
    }));
    if let Some(object) = schema.as_object_mut() {
        object.insert("description".into(), lines.join("\n").into());
        object.insert("examples".into(), examples.into());
    }
    schema
}

/// The kind of value a schema describes, in a word or two, when it says one
/// (`string`, `number`, `one of a, b`): what a path's line in the field-edit
/// listing tells beside its operations. Objects are described by their own
/// paths.
fn value_kind(schema: &serde_json::Value) -> Option<String> {
    if let Some(options) = schema.get("enum").and_then(serde_json::Value::as_array) {
        let options: Vec<String> = options
            .iter()
            .map(|option| {
                option
                    .as_str()
                    .map_or_else(|| option.to_string(), str::to_owned)
            })
            .collect();
        return Some(format!("one of {}", options.join(", ")));
    }
    match schema.get("type")? {
        serde_json::Value::String(kind) if kind != "object" => Some(kind.clone()),
        serde_json::Value::Array(kinds) => Some(
            kinds
                .iter()
                .filter_map(serde_json::Value::as_str)
                .collect::<Vec<_>>()
                .join(" or "),
        ),
        _ => None,
    }
}

/// The generic field-edit schema, with the vocabularies of the record's
/// fields' own operations named for `rich`.
fn generic_edit_schema(
    ops: &[(String, serde_json::Value)],
    takes: impl Fn(&str) -> bool,
) -> serde_json::Value {
    let ops = ops.to_vec();
    let mut schema = crate::path::edit_schema_taking(&takes);
    if !ops.is_empty()
        && takes("rich")
        && let Some(properties) = schema
            .get_mut("properties")
            .and_then(serde_json::Value::as_object_mut)
    {
        // A field type's own vocabulary (rich text's) can outweigh the
        // whole listing: it is summarised by its operations and their
        // arguments, and checked when the edit applies. The summaries only
        // describe, so they are one alternative: several describing
        // alternatives (two drafts' bodies) would each match any edit.
        let description = ops
            .into_iter()
            .map(|(path, schema)| {
                format!(
                    "An edit of `{path}` in its own vocabulary, one of: {}",
                    crate::schema::summary(&schema)
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        properties.insert(
            "rich".into(),
            crate::schema::one_of(vec![serde_json::json!({ "description": description })]),
        );
    }
    schema
}

fn step_schema(kind: &str, value: serde_json::Value) -> serde_json::Value {
    let mut properties = serde_json::Map::new();
    properties.insert(kind.to_owned(), value);
    serde_json::json!({
        "type": "object",
        "properties": properties,
        "required": [kind],
    })
}

/// The operations a field of `field`'s type takes, by its stored shape and
/// type: a text stored whole (`#[model(atom)]`) is only ever set.
fn field_ops(field: &crate::FieldShape, rich: bool) -> Vec<&'static str> {
    let ty = field.ty;
    // Who reacted with what: each invoker adds and takes back their own.
    if ty.rsplit("::").next() == Some("Reactions") {
        return vec!["react", "unreact"];
    }
    match field.shape {
        crate::Shape::Collection(_) | crate::Shape::Keyed(_) => {
            vec![
                "upsert-item",
                "insert-item",
                "remove-item",
                "move-to",
                "set",
            ]
        }
        // Rich text is written whole as markdown, or edited in its own
        // vocabulary.
        _ if rich => vec!["replace", "rich"],
        _ if ty.starts_with("Counter") => vec!["add", "set"],
        _ if ty.starts_with("Set<") => vec!["insert", "remove", "set"],
        _ if ty.starts_with("Grid<") => vec![
            "set-cell",
            "insert-row",
            "insert-column",
            "remove-row",
            "remove-column",
        ],
        _ if ty.starts_with("Outbox") => vec!["settle", "forget"],
        crate::Shape::Map(_) => vec!["set", "remove-key"],
        _ if ty == "String" && !field.atom => vec!["set", "splice", "replace"],
        _ => vec!["set"],
    }
}

/// Whether a field's type takes edits of its own that a read-only field still
/// accepts: each invoker's own reaction, or the outside settling its outbox
/// entry, as the record's table allows them.
fn takes_own_verbs(field: &crate::FieldShape) -> bool {
    let ops = field_ops(field, false);
    ops.iter()
        .any(|op| matches!(*op, "react" | "unreact" | "settle" | "forget"))
}

/// The vocabulary the value at `at` has of its own (a rich text's), when it
/// has one.
fn rich_schema_at<'a>(
    rich: &'a [(String, serde_json::Value)],
    at: &str,
) -> Option<&'a serde_json::Value> {
    rich.iter()
        .find(|(path, _)| path == at)
        .map(|(_, schema)| schema)
}

#[allow(
    clippy::too_many_lines,
    reason = "one walk over the stored shape, an alternative per kind of path"
)]
fn edit_paths(
    shape: crate::Shape,
    steps: &[serde_json::Value],
    dotted: &str,
    rich: &[(String, serde_json::Value)],
    out: &mut Vec<serde_json::Value>,
) {
    let alternative = |steps: &[serde_json::Value],
                       open: bool,
                       ops: &[&str],
                       value: serde_json::Value,
                       rich: Option<&serde_json::Value>,
                       title: &str,
                       description: String| {
        // The path as an agent writes it, items by a placeholder id.
        let template: Vec<serde_json::Value> = steps
            .iter()
            .map(|step| {
                let properties = step.get("properties").and_then(serde_json::Value::as_object);
                match properties.and_then(|properties| properties.iter().next()) {
                    Some((kind, value)) if kind == "field" => {
                        serde_json::json!({ "field": value.get("const").cloned().unwrap_or_default() })
                    }
                    Some((kind, _)) => serde_json::json!({ kind.clone(): format!("<{kind}>") }),
                    None => serde_json::Value::Null,
                }
            })
            .collect();
        let dotted: Vec<String> = template
            .iter()
            .map(
                |step| match step.get("field").and_then(serde_json::Value::as_str) {
                    Some(field) => field.to_owned(),
                    None => "*".to_owned(),
                },
            )
            .collect();
        let mut path = serde_json::json!({
            "type": "array",
            "prefixItems": steps,
            "minItems": steps.len(),
            "examples": [template],
        });
        if let Some(path) = path.as_object_mut() {
            if open {
                // What is inside the entry or cell, by any steps.
                path.insert("items".into(), serde_json::json!({ "type": "object" }));
            } else {
                path.insert("maxItems".into(), steps.len().into());
            }
        }
        let mut properties = serde_json::Map::new();
        properties.insert("path".into(), path);
        properties.insert("op".into(), serde_json::json!({ "enum": ops }));
        properties.insert("value".into(), value);
        if ops.contains(&"upsert-item") {
            properties.insert(
                "match".into(),
                serde_json::json!({
                    "type": "object",
                    "description": "upsert-item: the fields that identify the item, e.g. {\"name\": \"Ana\"}; it updates the one item holding them with `value`'s fields, else appends `value` as a new item"
                }),
            );
            properties.insert(
                "at".into(),
                serde_json::json!({
                    "description": "insert-item, move-to: \"end\" (the default), {\"after\": id} or {\"before\": id}",
                    "anyOf": [
                        { "const": "end" },
                        { "type": "object", "properties": { "after": { "type": "string" } }, "required": ["after"] },
                        { "type": "object", "properties": { "before": { "type": "string" } }, "required": ["before"] },
                        { "type": "integer", "minimum": 0 }
                    ]
                }),
            );
        }
        if let Some(rich) = rich {
            properties.insert("rich".into(), rich.clone());
        }
        serde_json::json!({
            "title": dotted.join("."),
            "description": if description.is_empty() {
                title.to_owned()
            } else {
                format!("{title}; {description}")
            },
            "type": "object",
            "properties": properties,
            "required": ["path", "op"],
        })
    };
    let item = step_schema("item", serde_json::json!({ "type": "string" }));
    // A read-only field is changed only by the record's verbs: no path an
    // edit could take, save the verbs its own type keeps that a field edit
    // still applies (a reaction, a settled outbox entry).
    for field in shape
        .fields()
        .iter()
        .filter(|field| !field.readonly || takes_own_verbs(field))
    {
        let mut here = steps.to_vec();
        here.push(step_schema(
            "field",
            serde_json::json!({ "const": field.key }),
        ));
        let path = format!("{dotted}{}", field.key);
        let rich_schema = rich_schema_at(rich, &path);
        let ops = field_ops(field, rich_schema.is_some());
        let collection = matches!(
            field.shape,
            crate::Shape::Collection(_) | crate::Shape::Keyed(_)
        );
        // A value field's `set` takes its value; containers' operations
        // carry items, elements or keys of their own.
        let simple = ops.first() == Some(&"set") && !collection;
        let value = if simple {
            (field.schema)()
        } else {
            serde_json::json!({})
        };
        let mut flags = Vec::new();
        if field.unit {
            flags.push("its own storage unit".to_owned());
        }
        match field.trust {
            crate::Trust::Ordinary => {}
            crate::Trust::Sensitive => flags.push("changing it asks for confirmation".to_owned()),
            crate::Trust::Weakens(_) => flags.push(
                "making it weaker can weaken security: such a change asks for confirmation and needs the person's own grant; making it stricter does not"
                    .to_owned(),
            ),
            crate::Trust::Weakening => flags.push(
                "changing it can weaken security: it asks for confirmation and needs the person's own grant"
                    .to_owned(),
            ),
        }
        if collection {
            // A field edit changes only the record, so Undo takes a removed
            // item back and nobody is asked first.
            flags.push(if field.quiet_remove {
                "removing an item asks nothing".to_owned()
            } else {
                "removing an item asks nothing; Undo takes it back".to_owned()
            });
        }
        let description = flags.join("; ");
        out.push(alternative(
            &here,
            false,
            &ops,
            value,
            rich_schema,
            field.title,
            description,
        ));
        match field.shape {
            crate::Shape::Record(_) => {
                edit_paths(field.shape, &here, &format!("{path}."), rich, out);
            }
            crate::Shape::Collection(inner) | crate::Shape::Keyed(inner) => {
                let mut items = here.clone();
                items.push(item.clone());
                let item_value = (field.schema)().get("items").map_or_else(
                    || serde_json::json!({}),
                    |items| {
                        // A collection's JSON lists `{id, value}` entries.
                        items
                            .get("properties")
                            .and_then(|properties| properties.get("value"))
                            .cloned()
                            .unwrap_or_else(|| items.clone())
                    },
                );
                // A collection of text items takes the text operations at each item, not only
                // the whole-value `set` a record item takes.
                let item_ops: &[&str] = match *inner {
                    crate::Shape::Value => &["set", "splice", "replace", "rich"],
                    _ => &["set"],
                };
                out.push(alternative(
                    &items,
                    false,
                    item_ops,
                    item_value,
                    None,
                    field.title,
                    "one item, by its id".to_owned(),
                ));
                edit_paths(*inner, &items, &format!("{path}.*."), rich, out);
            }
            crate::Shape::Value if field.ty.starts_with("Grid<") => {
                let mut cells = here.clone();
                cells.push(step_schema(
                    "cell",
                    serde_json::json!({
                        "type": "object",
                        "properties": {
                            "row": { "type": "string" },
                            "column": { "type": "string" },
                        },
                        "required": ["row", "column"],
                    }),
                ));
                out.push(alternative(
                    &cells,
                    true,
                    &[
                        "set", "splice", "replace", "add", "insert", "remove", "rich",
                    ],
                    serde_json::json!({}),
                    None,
                    field.title,
                    "a cell, by its row and column ids, and what is inside it".to_owned(),
                ));
            }
            crate::Shape::Map(_) => {
                let mut entries = here.clone();
                entries.push(step_schema("key", serde_json::json!({ "type": "string" })));
                // An entry whose type has its own vocabulary (a text) is edited in it.
                let entry_rich = rich_schema_at(rich, &format!("{path}.*"));
                let mut ops = vec!["set", "splice", "replace", "add", "insert", "remove"];
                if entry_rich.is_some() {
                    ops.push("rich");
                }
                out.push(alternative(
                    &entries,
                    true,
                    &ops,
                    serde_json::json!({}),
                    entry_rich,
                    field.title,
                    "an entry, by its key, and what is inside it".to_owned(),
                ));
            }
            crate::Shape::Value => {}
        }
    }
}

mod field_edit;
use field_edit::rooted_edit_spec;

/// The published spec of [`FIELD_EDIT`], where `now` holds the values of
/// the fields that weaken one way ([`weakening_now`]).
pub(crate) fn field_edit_spec(
    vocabulary: &'static Vocabulary,
    now: Vec<(String, String)>,
) -> ActionSpec {
    // Built once per type: it describes every editable path, which only
    // the type decides.
    let schema = per_type(vocabulary, TypeSchema::Edit, &|| {
        Some(edit_schema(vocabulary))
    })
    .unwrap_or_else(|| Arc::new(edit_schema(vocabulary)));
    rooted_edit_spec(
        vocabulary,
        (vocabulary.shape)(),
        schema,
        format!("Edit a {} field", vocabulary.label),
        "The path of the field from the record's root, and the operation",
        now,
    )
}

/// The values now, as JSON text by dotted path, of `R`'s fields that weaken
/// one way ([`Trust::Weakens`](crate::Trust::Weakens)) outside any item:
/// whether a change of one weakens depends on them.
fn weakening_now<R: Resource>(state: &R::State) -> Vec<(String, String)> {
    weakening_in(R::shape(), &|| R::state_json(state))
}

/// [`weakening_now`] of the resource whose stored layout is `shape` and
/// whose state's JSON `json` reads. Not generic, so it is compiled once
/// rather than for every resource type.
#[inline(never)]
fn weakening_in(
    shape: Option<crate::Shape>,
    json: &dyn Fn() -> Option<serde_json::Value>,
) -> Vec<(String, String)> {
    let Some(shape) = shape else {
        return Vec::new();
    };
    let fields: Vec<String> = shape
        .guarded_fields()
        .into_iter()
        .filter(|(path, trust)| {
            matches!(trust, crate::Trust::Weakens(_)) && !path.split('.').any(|key| key == "*")
        })
        .map(|(path, _)| path)
        .collect();
    if fields.is_empty() {
        return Vec::new();
    }
    let Some(json) = json() else {
        return Vec::new();
    };
    fields
        .into_iter()
        .filter_map(|path| {
            let value = path
                .split('.')
                .try_fold(&json, |value, key| value.get(key))?
                .to_string();
            Some((path, value))
        })
        .collect()
}

/// The field edit offered on the item `item` of the collection `field`:
/// paths from the item, its editable paths described as the record's are.
#[must_use]
pub fn item_field_edit_spec<R: Resource>(field: &str, item: &crate::Id) -> Option<ActionSpec> {
    item_field_edit_spec_of(vocabulary::<R>(), field, item)
}

/// [`item_field_edit_spec`] of the resource `vocabulary`.
pub(crate) fn item_field_edit_spec_of(
    vocabulary: &'static Vocabulary,
    field: &str,
    item: &crate::Id,
) -> Option<ActionSpec> {
    field_edit_spec_at_of(
        vocabulary,
        vec![
            crate::Segment::Field(field.to_owned()),
            crate::Segment::Item(item.clone()),
        ],
    )
}

/// The field edit offered on the item at `prefix` (fields and item ids from
/// the record, ending at an item): paths from the item, its editable paths
/// described as the record's are.
#[must_use]
pub fn field_edit_spec_at<R: Resource>(prefix: Vec<crate::Segment>) -> Option<ActionSpec> {
    field_edit_spec_at_of(vocabulary::<R>(), prefix)
}

/// [`field_edit_spec_at`] of the resource `vocabulary`.
pub(crate) fn field_edit_spec_at_of(
    vocabulary: &'static Vocabulary,
    prefix: Vec<crate::Segment>,
) -> Option<ActionSpec> {
    let mut shape = (vocabulary.shape)()?;
    let mut dotted = String::new();
    let mut readonly = false;
    for segment in &prefix {
        match (shape, segment) {
            (crate::Shape::Record(fields), crate::Segment::Field(key)) => {
                let field = fields.iter().find(|candidate| candidate.key == key)?;
                readonly |= field.readonly;
                shape = field.shape;
                dotted.push_str(key);
                dotted.push('.');
            }
            (
                crate::Shape::Collection(inner) | crate::Shape::Keyed(inner),
                crate::Segment::Item(_),
            ) => {
                shape = *inner;
                dotted.push_str("*.");
            }
            _ => return None,
        }
    }
    if shape.fields().is_empty() || readonly {
        return None;
    }
    // The same for every item: kept once per type and path, bound to the
    // item's.
    thread_local! {
        static KEPT: std::cell::RefCell<crate::kept::KeptByPath> = std::cell::RefCell::default();
    }
    let key = ((vocabulary.type_id)(), dotted.clone());
    crate::kept::kept_type(&KEPT, key, || item_edit_type(vocabulary, shape, &dotted))
        .map(|ty| ty.bind(Target::new(prefix)))
}

/// The type of the field edit of the items at the dotted path `dotted`, of
/// shape `shape`, or `None` when nothing there is editable.
fn item_edit_type(
    vocabulary: &'static Vocabulary,
    shape: crate::Shape,
    dotted: &str,
) -> Option<Arc<ActionType>> {
    let schema = per_type_at(vocabulary, TypeSchema::Edit, dotted, &|| {
        let ops: Vec<(String, serde_json::Value)> = (vocabulary.op_schemas)()
            .into_iter()
            .filter_map(|(path, schema)| {
                path.strip_prefix(dotted)
                    .map(|rest| (rest.to_owned(), schema))
            })
            .collect();
        let mut alternatives = Vec::new();
        edit_paths(shape, &[], "", &ops, &mut alternatives);
        (!alternatives.is_empty()).then(|| described_edit(&alternatives, &ops))
    })?;
    let spec = rooted_edit_spec(
        vocabulary,
        Some(shape),
        schema,
        "Edit a field of this item".to_owned(),
        "The path of the field from the item, and the operation",
        Vec::new(),
    );
    Some(Arc::clone(spec.action_type()))
}

/// The edits of a resource whose document holds nothing. An app whose data
/// lives entirely outside any document — credentials in this device's
/// encrypted vault, a device's hardware — publishes that data as live rows
/// and effects, and its resource is only the API they are published on.
/// No value exists, so nothing is ever applied, undone or synced.
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize)]
pub enum NoAction {}

impl tilo_actions::Action for NoAction {
    // No value exists to apply.
    fn apply(&self, _doc: &mut tilo_actions::Doc) -> Result<(), tilo_actions::ActionError> {
        Ok(())
    }
}

/// Where a member is inside a resource, in the resource's own terms:
/// the same on every member's screen whatever its layout.
///
/// Also what an action is told to act at (`#[param(place)] at:
/// Option<Place>`): it travels as `{"item": id}`, `{"item": id, "at": n}` or
/// `{"item": id, "start": n, "end": n}`.
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
#[serde(into = "tilo_actions::SelectionPlace")]
pub enum Place {
    /// An item (a paragraph, a clip, a row).
    Item(String),
    /// A caret at a character position inside an item.
    Caret { item: String, at: usize },
    /// Characters `start..end` of an item.
    Range {
        item: String,
        start: usize,
        end: usize,
    },
}

impl Place {
    /// The item the place is in.
    #[must_use]
    pub fn item(&self) -> &str {
        match self {
            Self::Item(item) | Self::Caret { item, .. } | Self::Range { item, .. } => item,
        }
    }
}

// Decoded through a JSON value whatever the deserializer, by one function.
//
// Validating on every read is safe while every stored place names a generated
// id (today only code-editor's recorded `replace-range` action stores a
// `Place`, its item is always a UUID, and it declares no undo). A later action
// that has an undo and takes items from outside data would fail to decode on
// undo.
impl<'de> serde::Deserialize<'de> for Place {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = <serde_json::Value as serde::Deserialize>::deserialize(deserializer)?;
        match place_from_json(value) {
            Ok(place) => Ok(place),
            Err(error) => Err(serde::de::Error::custom(error)),
        }
    }
}

/// The place in `value`, its JSON form.
fn place_from_json(value: serde_json::Value) -> Result<Place, String> {
    match serde_json::from_value::<tilo_actions::SelectionPlace>(value) {
        Ok(wire) => Place::try_from(wire),
        Err(error) => Err(error.to_string()),
    }
}

impl crate::JsonSchema for Place {
    fn json_schema() -> serde_json::Value {
        tilo_actions::place_schema()
    }
}

// A selection carried to an agent is the place an action takes, in the
// same wire form, so the agent can hand it back unchanged.
impl From<Place> for tilo_actions::SelectionPlace {
    fn from(place: Place) -> Self {
        match place {
            Place::Item(item) => Self::item(item),
            Place::Caret { item, at } => Self::caret(item, at),
            Place::Range { item, start, end } => Self::range(item, start, end),
        }
    }
}

impl TryFrom<tilo_actions::SelectionPlace> for Place {
    type Error = String;

    fn try_from(place: tilo_actions::SelectionPlace) -> Result<Self, String> {
        match place.validated_span()? {
            tilo_actions::selection::SelectionSpan::Item => Ok(Self::Item(place.item)),
            tilo_actions::selection::SelectionSpan::Caret(at) => Ok(Self::Caret {
                item: place.item,
                at,
            }),
            tilo_actions::selection::SelectionSpan::Range { start, end } => Ok(Self::Range {
                item: place.item,
                start,
                end,
            }),
        }
    }
}

/// Builds a resource's action from arguments already bound against the
/// declaration's parameters. `now_ms` is the origin's clock, captured once so
/// replay is deterministic.
pub type BuildAction<R> =
    Arc<dyn Fn(&ActionArgs, i64) -> Result<<R as Resource>::Action, String> + Send + Sync>;

/// One mutation offered by name: a [`Declaration`] of the resource `R`,
/// whose fields it derefs to.
pub struct ActionDecl<R: Resource> {
    decl: Declaration,
    marker: std::marker::PhantomData<fn() -> R>,
}

impl<R: Resource> Clone for ActionDecl<R> {
    fn clone(&self) -> Self {
        Self {
            decl: self.decl.clone(),
            marker: std::marker::PhantomData,
        }
    }
}

impl<R: Resource> std::ops::Deref for ActionDecl<R> {
    type Target = Declaration;

    fn deref(&self) -> &Declaration {
        &self.decl
    }
}

impl<R: Resource> AsRef<Declaration> for ActionDecl<R> {
    fn as_ref(&self) -> &Declaration {
        &self.decl
    }
}

impl<R: Resource> std::ops::DerefMut for ActionDecl<R> {
    fn deref_mut(&mut self) -> &mut Declaration {
        &mut self.decl
    }
}

impl<R: Resource> ActionDecl<R> {
    /// A field edit whose one value its caller supplies, offered as the
    /// action `id` labelled `label`: the parameter `param` (described by
    /// `description`, typed by `V`'s schema) becomes the edit `make(value)`.
    /// What a row offers when the edit is bound to it but its value is not
    /// ("Rename playlist", "Add a song to this playlist").
    pub fn edit_asking<V>(
        id: &'static str,
        label: impl Into<String>,
        param: &'static str,
        description: &'static str,
        make: impl Fn(V) -> crate::Edit<R> + Send + Sync + 'static,
    ) -> Self
    where
        V: DeserializeOwned + crate::JsonSchema,
    {
        let schema = V::json_schema();
        let declared = ActionParam::required_owned(
            param,
            crate::__private::param_type_of(&schema),
            description,
        )
        .with_schema(schema);
        let vocabulary = vocabulary::<R>();
        let build: Builds = Arc::new(move |args, now_ms| {
            let value = taken_arg(args, param)?;
            let value: V = match serde_json::from_value(value) {
                Ok(value) => value,
                Err(error) => return Err(format!("`{param}`: {error}")),
            };
            stamped_edit(vocabulary, make(value).retyped(), now_ms)
        });
        Self::declared(Declaration::new(
            vocabulary,
            id,
            label.into(),
            vec![declared],
            build,
        ))
    }

    /// The field edit `edit` offered as the action `id` labelled `label`,
    /// its value bound: what a place or a live row offers ("Use Proton for
    /// Adobe Reader"), checked and recorded as the edit itself.
    pub fn edit(id: &'static str, label: impl Into<String>, edit: crate::Edit<R>) -> Self
    where
        crate::Edit<R>: Send + Sync,
    {
        Self::declared(edit_declaration(
            vocabulary::<R>(),
            id,
            label.into(),
            edit.retyped(),
        ))
    }

    pub fn new(
        id: &'static str,
        label: impl Into<String>,
        params: Vec<ActionParam>,
        build: impl Fn(&ActionArgs, i64) -> Result<R::Action, String> + Send + Sync + 'static,
    ) -> Self {
        let build: Builds = Arc::new(move |args, now_ms| match build(args, now_ms) {
            Ok(action) => Ok(Built::of::<R>(action)),
            Err(reason) => Err(reason),
        });
        Self::declared(Declaration::new(
            vocabulary::<R>(),
            id,
            label.into(),
            params,
            build,
        ))
    }

    pub(crate) fn declared(decl: Declaration) -> Self {
        Self {
            decl,
            marker: std::marker::PhantomData,
        }
    }

    /// This action with `arguments` as a caller sent them over a call that names the action by
    /// its id: what a dispatch hands the record, which binds them as it binds any.
    #[must_use]
    pub fn with_arguments(
        &self,
        arguments: serde_json::Map<String, serde_json::Value>,
    ) -> crate::Invoke<R> {
        crate::Invoke::bound(self.decl.id, Ok(arguments))
    }

    /// The declaration, of whichever resource.
    #[must_use]
    pub fn into_declaration(self) -> Declaration {
        self.decl
    }

    /// The action it builds from `args` at `now_ms`.
    pub fn build_action(&self, args: &ActionArgs, now_ms: i64) -> Result<R::Action, String> {
        typed::<R>(crate::content::invoking(|| {
            (self.decl.build)(args, now_ms)
        })?)
    }

    /// Mark a bound edit as refining the resource's declared action of the
    /// same id ([`bind_declaration`]).
    #[must_use]
    pub fn refining(mut self) -> Self {
        self.decl.refines = true;
        self
    }

    /// Declare who listings offer it to ([`tilo_actions::Audience`]), as
    /// `#[action(audience = ..)]` declares it for a verb: a bound edit that
    /// names entries by path is for agents and scripts, not a row a person
    /// picks.
    #[must_use]
    pub fn for_audience(mut self, audience: tilo_actions::Audience) -> Self {
        self.decl.tags.retain(|tag| {
            tag != tilo_actions::AGENTS_AUDIENCE_TAG && tag != tilo_actions::PEOPLE_AUDIENCE_TAG
        });
        if let Some(tag) = audience.tag() {
            self.decl.tags.push(tag.to_owned());
        }
        self
    }

    /// Tag the action's contract (`ContextRequirement::Caret.tag()`, an
    /// incremental-text declaration) for the callers that read it.
    #[must_use]
    pub fn tagged(mut self, tag: impl Into<String>) -> Self {
        self.decl.tag(tag.into());
        self
    }

    #[must_use]
    pub fn describe(mut self, description: impl Into<String>) -> Self {
        self.decl.description = Some(description.into());
        self
    }

    /// Declare what the action answers its caller with (an outline of the
    /// state it left), which the hosting surface supplies after it applies.
    #[must_use]
    pub fn returns(mut self, result: tilo_actions::ResultSpec) -> Self {
        self.decl.result = Some(result);
        self
    }

    /// Set what the action is able to do.
    #[must_use]
    pub fn of_kind(mut self, kind: ActionKind) -> Self {
        self.decl.kind = kind;
        self
    }

    /// Place the action below the one field it writes.
    #[must_use]
    pub fn below_field(mut self, field: &'static str) -> Self {
        self.decl.field = Some(field);
        self
    }

    #[must_use]
    pub fn destructive(mut self) -> Self {
        self.decl.destructive = true;
        self
    }

    /// The units the action writes, as the surface lists them
    /// ([`crate::footprint`]).
    #[must_use]
    pub fn writing(mut self, units: Vec<String>) -> Self {
        self.decl.writes = units;
        self
    }

    /// Answer the caller with what the action made, from
    /// [`Resource::answer`].
    #[must_use]
    pub fn answering(mut self) -> Self {
        self.decl.answer();
        self
    }
}

impl Declaration {
    fn tag(&mut self, tag: String) {
        if !self.tags.contains(&tag) {
            self.tags.push(tag);
        }
    }

    fn answer(&mut self) {
        self.result = Some(tilo_actions::ResultSpec::Json {
            schema: serde_json::json!({"type": "object"}),
        });
    }
}

/// The action of `R` that `built` is.
fn typed<R: Resource>(built: Built) -> Result<R::Action, String> {
    built
        .into_action::<R>()
        .ok_or_else(|| format!("not an action of a {}", R::LABEL))
}

/// The argument `param` of `args`, taken out.
fn taken_arg(args: &ActionArgs, param: &str) -> Result<serde_json::Value, String> {
    match args.to_json().remove(param) {
        Some(value) => Ok(value),
        None => Err(format!("`{param}` is missing")),
    }
}

/// The action the field edit `edit` of the resource `vocabulary` is,
/// stamped at `now_ms`.
pub(crate) fn stamped_edit(
    vocabulary: &Vocabulary,
    edit: Edit<()>,
    now_ms: i64,
) -> Result<Built, String> {
    let Some(mut action) = (vocabulary.edit)(edit) else {
        return Err(format!("{} has no field edits", vocabulary.label));
    };
    action.stamp(now_ms);
    Ok(action)
}

/// [`ActionDecl::edit`] of the resource `vocabulary`.
fn edit_declaration(
    vocabulary: &'static Vocabulary,
    id: &'static str,
    label: String,
    edit: Edit<()>,
) -> Declaration {
    let destructive = (vocabulary.edit)(edit.clone())
        .is_some_and(|action| action.risk() == tilo_actions::RiskLevel::Destructive);
    let invokes = serde_json::to_value(&edit).ok().map(|edit| {
        (
            FIELD_EDIT.to_owned(),
            serde_json::Map::from_iter([(EDIT_PARAM.to_owned(), edit)]),
        )
    });
    let build: Builds = Arc::new(move |_, now_ms| stamped_edit(vocabulary, edit.clone(), now_ms));
    let mut decl = Declaration::new(vocabulary, id, label, Vec::new(), build);
    decl.destructive = destructive;
    decl.invokes = invokes;
    decl
}

thread_local! {
    /// The origin clock of a [`Replica`](crate::Replica) applying an action
    /// on this thread, in place of the machine's.
    static ORIGIN_CLOCK: std::cell::Cell<Option<i64>> = const { std::cell::Cell::new(None) };
}

/// Milliseconds since the Unix epoch on this machine (or the clock of the
/// replica applying an action here). Only ever read on the origin, when an
/// action is built; never inside `apply`.
#[must_use]
pub fn origin_now_ms() -> i64 {
    ORIGIN_CLOCK
        .with(std::cell::Cell::get)
        .unwrap_or_else(tilo_clock::unix_now_ms_i64)
}

/// Run `f` with the origin clock reading `now_ms`: every action built
/// inside it is stamped with that time, so encoding the same invocation
/// twice (once to ask for confirmation, once to check it) gives the same
/// action.
pub fn with_origin_clock<T>(now_ms: i64, f: impl FnOnce() -> T) -> T {
    struct Restore(Option<i64>);
    impl Drop for Restore {
        fn drop(&mut self) {
            ORIGIN_CLOCK.with(|clock| clock.set(self.0));
        }
    }
    let _restore = Restore(ORIGIN_CLOCK.with(|clock| clock.replace(Some(now_ms))));
    f()
}

/// Encode a resource action under its registry type id.
///
/// # Errors
/// Returns [`ActionError::Encode`] when the action does not serialize.
pub fn encode<R: Resource>(action: &R::Action) -> Result<EncodedAction, ActionError> {
    EncodedAction::encode(R::ACTION_TYPE, action)
}

/// The encoded form of a built action, or a refusal carrying why it does
/// not encode.
pub(crate) fn encoded(action: &Built) -> EncodedAction {
    match action.encode() {
        Ok(encoded) => encoded,
        Err(error) => refused(&error.to_string()),
    }
}

/// The encoded form of a builder's result: the action, or a refusal that
/// carries the builder's reason.
pub(crate) fn encode_built(built: Result<Built, String>) -> EncodedAction {
    match built {
        Ok(action) => encoded(&action),
        Err(reason) => refused(&reason),
    }
}

/// The nested resource `id` of `state`, read from `doc` with `id` demanded
/// when `state` has not loaded it: an item past what a view shows or a
/// tree pages still resolves by id ([`Resource::child`], [`Resource::load`]).
pub fn child_by_id<R: Resource>(
    state: &R::State,
    doc: &Doc,
    id: &str,
) -> Option<tilo_actions::ResourceSpec> {
    if let Some(child) = R::child(state, id) {
        return Some(child);
    }
    let mut fresh = R::read(doc).ok()?;
    R::load(&mut fresh, doc, &child_demand(id)).ok()?;
    R::child(&fresh, id)
}

/// What reading the child published at `id` demands: compiled once rather
/// than for every resource.
#[inline(never)]
fn child_demand(id: &str) -> Demand {
    // A child is published as `<kind>/<field>/<key>`; its record knows
    // it by the key.
    let key = id.rsplit('/').next().unwrap_or(id);
    Demand::none().with_keys([id, key])
}

/// An action whose payload cannot be decoded, so the host refuses it with
/// the builder's reason instead of applying anything.
pub(crate) fn refused(reason: &str) -> EncodedAction {
    EncodedAction {
        type_id: tilo_actions::resource::INVALID_ARGUMENTS_TYPE.to_owned(),
        payload: reason.as_bytes().to_vec(),
    }
}

/// The ids of `declarations` some child among `children` offers bound.
fn offered_bound_ids(
    children: &[tilo_actions::ResourceSpec],
    declarations: &[Declaration],
) -> Vec<&'static str> {
    let mut ids = Vec::new();
    for decl in declarations {
        if crate::items::offered_bound(children, decl) {
            ids.push(decl.id);
        }
    }
    ids
}

/// The least a caller needs to take any of `declarations`.
fn least_need_declared(declarations: &[Declaration]) -> ActionNeed {
    least_need_of(declarations.iter().map(|decl| decl.kind))
}

/// The least a caller needs to take any of the actions of the kinds `needs`:
/// the least kind, at no field.
///
/// A group and a typed edit are offered to whoever may take the resource's
/// least demanding kind, and each invocation is what its own arguments say it
/// is ([`ActionSpec::with_need_of`]). One declaration's field is not that
/// offer's: it is that declaration's, and a chat whose `remove-message` writes
/// its `moderation` field would offer every `group` and `apply` only to
/// whoever may moderate, though the members of a group write their own
/// fields.
#[must_use]
pub fn least_need_of(needs: impl IntoIterator<Item = ActionKind>) -> ActionNeed {
    needs.into_iter().min().map_or_else(
        || tilo_actions::ActionContract::default().need(),
        |kind| ActionNeed {
            kind,
            field: None,
            privileged: false,
        },
    )
}

/// The published spec of one declared or bound mutation: what the palette,
/// agents and scripts invoke, building the resource's action from their
/// arguments.
///
/// The action is built when it is invoked, never when it is published: one
/// that takes no arguments still mints its ids and reads the clock at the
/// moment it is taken, so two invocations make two distinct actions.
#[must_use]
pub fn declaration_spec<D: AsRef<Declaration> + ?Sized>(decl: &D) -> ActionSpec {
    spec_of_declaration(decl.as_ref())
}

/// [`declaration_spec`] of a declaration of whichever resource.
fn spec_of_declaration(decl: &Declaration) -> ActionSpec {
    let build = Arc::clone(&decl.build);
    spec_of_declaration_on(decl, move |_, args, now_ms| build(args, now_ms))
}

/// The spec of `decl` as a type whose target `build` reads: what every item
/// offering the declared action shares ([`Target`]).
pub(crate) fn spec_of_declaration_on(
    decl: &Declaration,
    build: impl Fn(&Target, &ActionArgs, i64) -> Result<Built, String> + Send + Sync + 'static,
) -> ActionSpec {
    let build = Arc::new(build);
    let label = decl.shown_label();
    let encoded = move |target: &Target, args: &tilo_actions::ActionArgs| {
        encode_built(crate::content::invoking(|| {
            build(target, args, origin_now_ms())
        }))
    };
    let spec = if let Some(prompt) = &decl.content {
        let param = ActionParam::required_owned(
            tilo_actions::PROMPTED_PARAM,
            ParamType::Text,
            prompt.clone(),
        );
        ActionSpec::prompted_content_on(
            decl.id,
            label,
            prompt.clone(),
            "content hash",
            ExecutionLocus::ClientLocal,
            move |target, hash| {
                let supplied = [(
                    tilo_actions::PROMPTED_PARAM.to_owned(),
                    tilo_actions::ArgValue::Text(hash.to_owned()),
                )];
                match ActionArgs::bind(std::slice::from_ref(&param), supplied) {
                    Ok(args) => encoded(target, &args),
                    Err(error) => refused(&error.to_string()),
                }
            },
        )
    } else if decl.params.is_empty() {
        // Built when taken, so it reads the clock and mints its ids then; a
        // destructive one is held for confirmation as the same verb of the
        // same kind of record.
        let domain = format!("{}#{}", decl.resource, decl.id);
        let action_type = decl.action_type;
        ActionSpec::deferred_on(
            decl.id,
            label,
            ExecutionLocus::ClientLocal,
            action_type,
            move |target| encoded(target, &tilo_actions::ActionArgs::none()),
        )
        .with_continuation_identity(move |query| match query {
            tilo_actions::ContinuationQuery::Draft => {
                Some(tilo_actions::ContinuationEvidence::Draft {
                    resolution_domain: tilo_actions::ContinuationKey::new(
                        "verb",
                        [domain.as_bytes()],
                    ),
                    handler: tilo_actions::ContinuationKey::new(
                        "action-type",
                        [action_type.as_bytes()],
                    ),
                })
            }
            tilo_actions::ContinuationQuery::Exact(_) => None,
        })
    } else {
        ActionSpec::typed_on(
            decl.id,
            label.clone(),
            label,
            ExecutionLocus::ClientLocal,
            decl.shown_params(),
            encoded,
        )
    };
    let mut spec = spec.of_kind(decl.kind);
    // One whose arguments decide whether it reaches outside is what the
    // action built from them is; arguments that build none are taken as
    // reaching outside.
    if decl.by_arguments {
        let classify = Arc::clone(&decl.build);
        spec = spec.with_need_of(move |args| match classify(args, 0) {
            Ok(action) => action.need(),
            Err(_) => tilo_actions::ActionNeed::of(ActionKind::Outside),
        });
    }
    if let Some(field) = decl.field {
        spec = spec.below_field(field);
    }
    if let Some(description) = &decl.description {
        spec = spec.with_description(description.clone());
    }
    if !decl.keywords.is_empty() {
        spec = spec.with_keywords(decl.keywords.iter().cloned());
    }
    spec = with_declared_words(spec, decl);
    if decl.destructive {
        spec = spec.destructive();
    }
    let contract = &mut spec.type_mut().contract;
    (contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
    if let Some(result) = &decl.result {
        contract.result = result.clone();
    }
    for tag in &decl.tags {
        if !contract.tags.contains(tag) {
            contract.tags.push(tag.clone());
        }
    }
    // A compensated undo arrives as a tag: once it is there, a deletion it
    // takes back is no longer asked about.
    contract.settle_confirmation();
    spec
}

/// `spec` carrying the declared action's own picture and the past-tense words
/// its app says it did, where it declares them.
pub(crate) fn with_declared_words(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
    spec.type_mut().icon.clone_from(&decl.icon);
    spec.type_mut().did = decl.did.clone().filter(|did| !did.trim().is_empty());
    spec
}

/// Each declared action's arguments object, as serde reads it.
fn declared_args(
    declarations: &[Declaration],
) -> std::collections::BTreeMap<&'static str, serde_json::Value> {
    let mut args = std::collections::BTreeMap::new();
    for decl in declarations {
        args.insert(decl.id, crate::schema::args_schema(&decl.params));
    }
    args
}

/// The parameter of [`APPLY`]: one action value, described by
/// [`Resource::action_schema`] when the resource has one, with what only
/// restates a named action folded into a reference to it.
pub(crate) fn apply_param(vocabulary: &Vocabulary) -> ActionParam {
    let param = ActionParam::required_owned(
        APPLY_PARAM,
        ParamType::Object,
        format!("A {} action, as JSON", vocabulary.label),
    );
    let schema = per_type(vocabulary, TypeSchema::Apply, &|| {
        let schema = (vocabulary.action_schema)()?;
        Some(crate::schema::fold_declared(
            &schema,
            &declared_args(&vocabulary.declarations()),
        ))
    });
    match schema {
        Some(schema) => param.with_shared_schema(schema),
        None => param,
    }
}

/// The schemas a publication derives from the resource type alone.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum TypeSchema {
    Apply,
    Group,
    /// The field edit's, at the paths under a dotted prefix (`""` for the
    /// record's root, `notes.*.` for an item of `notes`).
    Edit,
}

#[derive(Default)]
struct CompiledSchemas {
    epoch: u64,
    entries: HashMap<(TypeId, TypeSchema, String), Option<Arc<serde_json::Value>>>,
}

static SCHEMAS: OnceLock<Mutex<CompiledSchemas>> = OnceLock::new();

/// Forget schemas derived by the previous app code before an in-place reload.
/// Hosts also call this when a reload is rejected, so the retained app rebuilds
/// its own definitions. Document and view changes do not invalidate type schemas.
#[doc(hidden)]
pub fn reset_type_schemas() {
    if let Some(cache) = SCHEMAS.get() {
        let mut store = cache.lock_recover();
        store.epoch = store.epoch.wrapping_add(1);
        store.entries.clear();
    }
}

/// Which generation of app code built what is cached from the resource
/// types: it changes when [`reset_type_schemas`] forgets them.
pub(crate) fn type_epoch() -> u64 {
    SCHEMAS.get().map_or(0, |cache| cache.lock_recover().epoch)
}

/// [`type_epoch`] and the language the words resolve in on this thread: what
/// a cache of published actions, whose labels are read in that language, is
/// kept for.
pub(crate) fn words_epoch() -> u64 {
    type_epoch() ^ crate::label::revision().rotate_left(32)
}

/// `build`'s schema for the resource `vocabulary`, retained for this
/// generation of app code.
fn per_type(
    vocabulary: &Vocabulary,
    schema: TypeSchema,
    build: &dyn Fn() -> Option<serde_json::Value>,
) -> Option<Arc<serde_json::Value>> {
    per_type_at(vocabulary, schema, "", build)
}

/// [`per_type`] for the paths under the dotted prefix `at`.
fn per_type_at(
    vocabulary: &Vocabulary,
    schema: TypeSchema,
    at: &str,
    build: &dyn Fn() -> Option<serde_json::Value>,
) -> Option<Arc<serde_json::Value>> {
    let cache = SCHEMAS.get_or_init(Mutex::default);
    cached_schema(
        cache,
        ((vocabulary.type_id)(), schema, at.to_owned()),
        build,
    )
}

fn cached_schema(
    cache: &Mutex<CompiledSchemas>,
    key: (TypeId, TypeSchema, String),
    build: &dyn Fn() -> Option<serde_json::Value>,
) -> Option<Arc<serde_json::Value>> {
    let epoch = {
        let store = cache.lock_recover();
        if let Some(found) = store.entries.get(&key) {
            let _phase = crate::profiling::Phase::start("schema.cached_clone");
            return found.clone();
        }
        store.epoch
    };
    // Build outside the lock: a schema may publish another resource's.
    let value = build().map(Arc::new);
    let mut store = cache.lock_recover();
    // A build started before a code reload cannot repopulate the new cache.
    if store.epoch == epoch {
        store.entries.insert(key, value.clone());
    }
    value
}

/// Why an action only the app's own code applies ([`Resource::by_app`]) is
/// refused where a caller sent it: one sentence for every API.
#[must_use]
pub fn by_app_refusal(label: &str) -> String {
    format!("{label} keeps this itself: it is not an action to invoke")
}

/// A JSON action value as [`APPLY`] reads it. A value naming a declared
/// action is checked against that declaration first, so it is refused with
/// the reason the named action would give. A value of an action only the
/// app's own code applies is refused: it is no caller's to send.
fn read_apply(vocabulary: &Vocabulary, value: serde_json::Value) -> Result<Built, String> {
    let declarations = vocabulary.declarations();
    let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
    for decl in declarations.iter() {
        ids.push(decl.id);
    }
    if let Some((id, fields)) = crate::schema::declared_invocation(&value, &ids)
        && let Some(decl) = declarations.iter().find(|decl| decl.id == id)
        && let Err(error) = ActionArgs::bind_json(&decl.params, &fields)
    {
        return Err(format!("{id}: {error}"));
    }
    // Group members refer to this schema instead of copying it into the
    // group's parameter. Validate here as well as at the direct apply API,
    // including constraints stricter than the action's serde representation.
    if let Some(schema) = apply_param(vocabulary).schema {
        tilo_actions::validate_json_schema(&value, &schema)?;
    }
    let action = (vocabulary.read)(value)?;
    if action.by_app() {
        return Err(by_app_refusal(vocabulary.label));
    }
    Ok(action)
}

/// The parameter of [`GROUP`](crate::GROUP): invocations of the resource's
/// declared actions and of [`APPLY`]. A declared member's arguments are
/// checked against its own action's schema when the group is built, so this
/// names those actions rather than repeating their schemas. An `apply`
/// member is read exactly as [`APPLY`] reads its value when the group is
/// built, so it refers to `apply`'s schema rather than copying it: a
/// resource with a large action vocabulary (rich text's) published that
/// schema twice in every surface.
pub(crate) fn group_param(vocabulary: &Vocabulary) -> ActionParam {
    let schema = per_type(vocabulary, TypeSchema::Group, &|| {
        let declarations = vocabulary.declarations();
        let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
        for decl in declarations.iter() {
            ids.push(decl.id);
        }
        Some(group_schema(&ids, vocabulary.edits))
    })
    .unwrap_or_else(|| Arc::new(serde_json::json!({"type": "array"})));
    ActionParam::required_owned(
        crate::GROUP_PARAM,
        ParamType::Array,
        format!(
            "{} actions to apply in order as one step, each {{\"action\": id, \"args\": {{..}}}}. \
             A member names an item an earlier member of the same group makes by its place, \
             {{\"$made\": {{\"member\": 0, \"item\": 0}}}}: the member counted from 0, then which \
             of the ids it made, which the group fills in as it applies",
            vocabulary.label
        ),
    )
    .with_shared_schema(schema)
}

/// What the value of an `apply` member of a group is: the schema it is
/// checked against is published once, on `apply` itself.
pub const APPLY_MEMBER: &str =
    "One action value, as the `apply` action's `apply` parameter describes it";

/// What the value of a `field-edit` member of a group is: the schema it is
/// checked against is published once, on `field-edit` itself.
pub const FIELD_EDIT_MEMBER: &str =
    "A field edit, as the `field-edit` action's `edit` parameter describes it";

/// The schema of a group of the actions `ids`, `apply`, and field edits when
/// `edits`: one function for every resource.
fn group_schema(ids: &[&str], edits: bool) -> serde_json::Value {
    use crate::schema::{array, constant, describe, nullable, object, one_of, string_enum};
    let mut members = Vec::new();
    if !ids.is_empty() {
        members.push(describe(
            object(vec![
                ("action", string_enum(ids), true),
                (
                    "args",
                    nullable(serde_json::json!({"type": "object"})),
                    false,
                ),
            ]),
            "A named action, args as it takes them",
        ));
    }
    let action = describe(serde_json::json!({"type": "object"}), APPLY_MEMBER);
    if edits {
        members.push(describe(
            object(vec![
                ("action", constant(FIELD_EDIT), true),
                (
                    "args",
                    object(vec![(
                        EDIT_PARAM,
                        describe(serde_json::json!({"type": "object"}), FIELD_EDIT_MEMBER),
                        true,
                    )]),
                    true,
                ),
            ]),
            "A field edit",
        ));
    }
    members.push(object(vec![
        ("action", constant(APPLY), true),
        ("args", object(vec![(APPLY_PARAM, action, true)]), true),
    ]));
    array(one_of(members))
}

/// The JSON object of the argument `param` of `args`.
fn object_arg(
    args: &tilo_actions::ActionArgs,
    param: &str,
) -> Option<serde_json::Map<String, serde_json::Value>> {
    match args.get(param) {
        Some(tilo_actions::ArgValue::Object(value)) => Some(value.clone()),
        _ => None,
    }
}

pub(crate) fn apply_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
    #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
    let _phase = crate::profiling::Phase::start("resource.apply_spec");
    let read = move |args: &tilo_actions::ActionArgs| match object_arg(args, APPLY_PARAM) {
        Some(value) => read_apply(vocabulary, serde_json::Value::Object(value)),
        None => Err("missing action".to_owned()),
    };
    ActionSpec::typed(
        APPLY,
        format!("Apply {} edit", vocabulary.label),
        "Action as JSON",
        ExecutionLocus::ClientLocal,
        vec![apply_param(vocabulary)],
        move |args| match crate::content::invoking(|| read(args)) {
            Ok(mut action) => {
                action.stamp(origin_now_ms());
                encoded(&action)
            }
            Err(reason) => refused(&reason),
        },
    )
    .with_description(
        "One edit as a typed JSON value: {action: id, ...its params}. The named action does the same and says more.",
    )
    // A typed edit is how a surface, an agent or a script says what should
    // happen without a named declaration; a person picks named actions.
    .for_audience(tilo_actions::Audience::Agents)
    // History records the edit it carried, not `apply`.
    .carrying()
    // Offered to whoever may take the least of its edits; each value is
    // what that edit is.
    .with_need((vocabulary.least_need)())
    .of_kind((vocabulary.least_need)().kind)
    .with_need_of(move |args| match read(args) {
        Ok(action) => action.need(),
        Err(_) => tilo_actions::ActionContract::default().need(),
    })
    // Each value is classified: deleting is destructive, trimming is not, so
    // a destructive value gets the confirmation a declared one would.
    .with_risk(move |args| {
        let value = object_arg(args, APPLY_PARAM).map(serde_json::Value::Object);
        match value.map(vocabulary.read) {
            Some(Ok(action)) => action.risk(),
            _ => tilo_actions::RiskLevel::Low,
        }
    })
    // Undo takes a value back when it takes back the edit it carries, so a
    // deleting value Undo does take back applies without asking, and one its
    // declaration says Undo cannot bring back asks first, exactly as its
    // named declaration does. The declaration says which its edits are, so
    // nothing is built to ask.
    .with_undo_of(move |args| {
        let Some(value) = object_arg(args, APPLY_PARAM) else {
            return false;
        };
        let value = serde_json::Value::Object(value);
        let declarations = vocabulary.declarations();
        let mut ids: Vec<&str> = Vec::with_capacity(declarations.len());
        for decl in declarations.iter() {
            ids.push(decl.id);
        }
        let carried = crate::schema::declared_invocation(&value, &ids)
            .and_then(|(id, _)| declarations.iter().find(|decl| decl.id == id));
        tilo_actions::undo_takes_back(
            carried.map_or(tilo_actions::ActionKind::Outside, |decl| decl.kind),
            tilo_actions::ChangeKind::Content,
            carried.is_some_and(|decl| {
                decl.tags
                    .iter()
                    .any(|tag| tag == tilo_actions::IRREVERSIBLE_TAG)
            }),
        )
    })
}

/// What kind of action a published spec is: the kind its contract carries,
/// which the code that built it derived (a view only reads, a document
/// action changes only the document when the host's undo reverts it, else it
/// reaches outside).
#[must_use]
pub fn spec_kind(spec: &ActionSpec) -> ActionKind {
    spec.contract.kind
}

/// What `action` is, for the grants deciding it.
pub fn need_of<R: Resource>(action: &R::Action) -> ActionNeed {
    ActionNeed {
        kind: R::kind_of(action),
        field: R::field_of(action).map(str::to_owned),
        privileged: false,
    }
}

/// What several actions applied as one are: the strongest kind among them,
/// below a field only when every one writes that same field. Nothing to
/// apply is an undoable change of the record.
pub(crate) fn group_need(needs: impl IntoIterator<Item = ActionNeed>) -> ActionNeed {
    let mut needs = needs.into_iter();
    let Some(mut group) = needs.next() else {
        return tilo_actions::ActionContract::default().need();
    };
    for need in needs {
        group = ActionNeed {
            kind: group.kind.max(need.kind),
            field: group
                .field
                .filter(|field| need.field.as_ref() == Some(field)),
            privileged: group.privileged || need.privileged,
        };
    }
    group
}

/// The encoded group of the built `members`, of the resource `vocabulary`:
/// what [`ActionGroup`](crate::ActionGroup) of them encodes as. A group of
/// one action is that action, as `Dispatcher::group` submits it: a control
/// whose gesture is sometimes several actions (create a draft, then edit
/// it) and usually one edit records that edit, which continues the undo
/// step of the edit before it as the edit alone would.
pub(crate) fn encode_group(vocabulary: &Vocabulary, members: &[Built]) -> EncodedAction {
    if let [only] = members {
        return encoded(only);
    }
    let mut payload = Vec::with_capacity(128);
    payload.push(b'[');
    for (index, member) in members.iter().enumerate() {
        if index > 0 {
            payload.push(b',');
        }
        if let Err(error) = member.write_json(&mut payload) {
            return refused(&error.to_string());
        }
    }
    payload.push(b']');
    EncodedAction::written(crate::group::group_type_of(vocabulary.action_type), payload)
}

pub(crate) fn group_spec(vocabulary: &'static Vocabulary) -> ActionSpec {
    #[cfg(all(feature = "test-support", not(target_arch = "wasm32")))]
    let _phase = crate::profiling::Phase::start("resource.group_spec");
    let build = move |args: &tilo_actions::ActionArgs, now_ms: i64| {
        crate::group::build_members(vocabulary, &args.to_json(), now_ms)
    };
    ActionSpec::typed(
        crate::GROUP,
        format!("Apply several {} edits as one", vocabulary.label),
        "Invocations as JSON",
        ExecutionLocus::ClientLocal,
        vec![group_param(vocabulary)],
        move |args| match build(args, origin_now_ms()) {
            Ok(members) => encode_group(vocabulary, &members),
            Err(reason) => refused(&reason),
        },
    )
    .with_description(
        "Several actions as one all-or-nothing step: one undo, and if any member refuses nothing is applied. actions: [{action: id, args: {..}}].",
    )
    // A gesture's edits, from a surface, a script or an agent; a person picks
    // the named actions it is made of.
    .for_audience(tilo_actions::Audience::Agents)
    // History records the members, not the group.
    .carrying()
    // Is what its most demanding member is.
    .with_need((vocabulary.least_need)())
    .with_need_of(move |args| match build(args, 0) {
        Ok(members) => group_need(members.iter().map(Built::need)),
        Err(_) => tilo_actions::ActionContract::default().need(),
    })
    // As consequential as its most consequential member.
    .with_risk(move |args| match build(args, 0) {
        Ok(members) => crate::group::group_risk(members.iter().map(Built::risk)),
        Err(_) => tilo_actions::RiskLevel::Low,
    })
    // Undo takes it back only when it takes back every member: one that
    // reaches outside the document makes a deleting group ask.
    .with_undo_of(move |args| match build(args, 0) {
        Ok(members) => members.iter().all(Built::undoable),
        Err(_) => false,
    })
}

/// The default search entries of a record ([`crate::search_default`]).
pub use crate::search_default::default_search;

/// The resource tree published for one open resource: every declared and
/// state-bound action, the generic [`APPLY`] and [`GROUP`](crate::GROUP)
/// actions, the named [`Resource::views`], and the nested resources.
///
/// This is the only bridge from a [`Resource`] type to the
/// [`tilo_actions::ResourceSpec`] tree the palette, agents, scripts and the shell
/// API see. Apps do not construct a second tree for the same state.
///
/// An action offered on the items of a collection (see [`crate::items`])
/// stays published on the record, with its id parameter, for scripts and
/// agents; a person picks it on the item, so it is not a palette row here.
pub fn publish<R: Resource>(id: &str, label: &str, state: &R::State) -> tilo_actions::ResourceSpec {
    publish_parts::<R>(id, label, Some(state))
}

/// A record's state from the reading a document host publishes for it
/// ([`Resource::state_json`](Resource::state_json), [`crate::Model::to_json`]):
/// what an app's process reads when the record lives in the session's
/// document host and it holds no document of its own (`docs/architecture/apps.md`
/// §2–§3).
///
/// The host answers the reading, and the app's own view reads its fields
/// through its own model types: the state a reading names is the state the
/// host read from its document, so what the view shows is what the host
/// holds.
///
/// # Errors
/// Returns [`ModelError`] when the type keeps no JSON form
/// ([`Resource::RESOURCE_TABLE`](Resource::RESOURCE_TABLE) is `None`) or
/// `reading` is not one of it.
pub fn state_from_reading<R: Resource>(
    reading: &serde_json::Value,
) -> Result<R::State, ModelError> {
    let table = R::RESOURCE_TABLE.ok_or_else(|| {
        ModelError::invalid(format!("{} keeps no reading a host answers", R::LABEL))
    })?;
    crate::table::Run(table).from_json(reading)
}

/// [`publish`], or without a state only what does not depend on one: the
/// declared actions, [`APPLY`], [`GROUP`](crate::GROUP) and the local
/// operations.
pub(crate) fn publish_parts<R: Resource>(
    id: &str,
    label: &str,
    state: Option<&R::State>,
) -> tilo_actions::ResourceSpec {
    let vocabulary = vocabulary::<R>();
    let Some(state) = state else {
        let own = Own {
            availability: None,
            views: Vec::new(),
            local_operations: R::local_operations(),
            now: Vec::new(),
        };
        return publish_own(vocabulary, id, label, own, &|_| false);
    };
    let children = R::children(state);
    let own = Own {
        availability: Some(&|action| R::availability(state, action)),
        views: R::views(state),
        local_operations: R::local_operations(),
        now: weakening_now::<R>(state),
    };
    publish_own(vocabulary, id, label, own, &|decl| {
        crate::items::offered_bound(&children, decl)
    })
    .with_children(children)
}

/// The resource tree published for one open document ([`publish`]) whose
/// state its holder could not read: its declared actions, [`APPLY`],
/// [`GROUP`](crate::GROUP) and the field edit, each unavailable for
/// `reason`, so a caller learns why they do not apply instead of finding a
/// hole in the surface. What a state would offer — its children, its views,
/// which actions can be taken now — is not published: there is no state to
/// read it from.
pub fn unreadable_parts<R: Resource>(
    id: &str,
    label: &str,
    reason: &str,
) -> tilo_actions::ResourceSpec {
    let label = crate::label::published(R::KIND, label, R::LABEL, R::CATALOGUE);
    crate::unreadable::parts::<R>(id, &label, reason)
}

/// What a resource's own publication reads of its state.
struct Own<'a> {
    /// Whether each declared action can be taken now; without a state,
    /// none is decided.
    availability: Option<&'a dyn Fn(&str) -> tilo_actions::Availability>,
    views: Vec<tilo_actions::ResourceViewSpec>,
    local_operations: Vec<ActionSpec>,
    /// The values now of the fields that weaken one way ([`weakening_now`]).
    now: Vec<(String, String)>,
}

/// The resource's own part of [`publish_parts`]: everything but its
/// children, with `offered_bound` saying which declarations a child offers
/// with arguments bound.
fn publish_own(
    vocabulary: &'static Vocabulary,
    id: &str,
    label: &str,
    own: Own<'_>,
    offered_bound: &dyn Fn(&Declaration) -> bool,
) -> tilo_actions::ResourceSpec {
    let _phase = crate::profiling::Phase::start("resource.published");
    // The name the person reads, in their language: the kind's catalogue
    // entry while the publisher kept the name the declaration gave it.
    let label = crate::label::published(
        vocabulary.kind,
        label,
        vocabulary.label,
        vocabulary.catalogue,
    );
    let mut resource = tilo_actions::ResourceSpec::new(id, vocabulary.kind, &label);
    // Describe the declared domain ID before any host dispatch alias projection.
    resource.semantic_identity = tilo_actions::ResourceSemanticIdentity::new(vocabulary.kind, id);
    // The app it publishes under: what an action's `ActionKey` names, and
    // what a control bound by key is checked against.
    resource.app_id = Some(vocabulary.app.to_owned());
    // What it is, as people name it: its type's noun, its app's name and
    // whether it is that app's root. Exactly a tilolang type's, so the one
    // search matches a Rust and a tilolang type alike. Its noun is the
    // *type's* (`vocabulary.label`), never the record's own title: a channel
    // called "MKBHD" is a `channel`, not an `m k b h d`.
    resource = resource.with_type(crate::words::type_words(vocabulary.kind, vocabulary.label));
    let kept = own_specs(vocabulary);
    for (decl, declared) in vocabulary.declarations().iter().zip(kept.declared.iter()) {
        let _phase = crate::profiling::Phase::start("resource.declaration_spec");
        // Another declaration a child offers with some of its arguments
        // bound ([`items::bound`](crate::items::bound)) needs nothing in
        // hand, and stays here for scripts, out of the palette's way.
        let mut spec = if decl.item.is_none() && offered_bound(decl) {
            declared.for_agents.clone()
        } else {
            declared.offered.clone()
        };
        // Whether it can be taken now is the resource's own: its type is
        // copied only where that differs from what the kept one says.
        if let Some(availability) = own.availability {
            let now = availability(decl.id);
            if spec.contract.availability != now {
                spec.type_mut().contract.availability = now;
            }
        }
        resource = resource.with_action(spec);
    }
    for view in own.views {
        resource = resource.with_view(view);
    }
    crate::share::offer(&mut resource);
    for spec in own.local_operations {
        if spec.kind == OperationKind::Document {
            continue;
        }
        resource = resource.with_action(spec);
    }
    resource = resource
        .with_action(kept.apply.clone())
        .with_action(kept.group.clone());
    if vocabulary.edits {
        resource = resource.with_action(field_edit_spec(vocabulary, own.now));
    }
    resource
}

/// The actions every resource of a vocabulary offers as its own, the same
/// on each: its declarations, its typed edit and its group.
struct OwnSpecs {
    /// Each declaration's spec, in [`Vocabulary::declarations`]' order.
    declared: Box<[DeclaredSpec]>,
    apply: ActionSpec,
    group: ActionSpec,
}

/// One declaration's spec as a resource offers it, and as it offers it to
/// agents alone where a child offers the declaration bound.
struct DeclaredSpec {
    offered: ActionSpec,
    for_agents: ActionSpec,
}

/// [`OwnSpecs`] of `vocabulary`, kept like every type the items of a kind
/// share ([`crate::kept`]): building a declaration's spec builds its
/// parameters and schema, and publishing each of a tracker's thousands of
/// issues built every one of them again for each issue.
fn own_specs(vocabulary: &'static Vocabulary) -> std::rc::Rc<OwnSpecs> {
    thread_local! {
        static KEPT: std::cell::RefCell<crate::kept::KeptTypes<TypeId, std::rc::Rc<OwnSpecs>>> =
            std::cell::RefCell::default();
    }
    crate::kept::kept_type(&KEPT, (vocabulary.type_id)(), || {
        let declared = vocabulary
            .declarations()
            .iter()
            .map(|decl| {
                let mut offered = spec_of_declaration(decl);
                // An item verb stays published here for a caller that names
                // the item, saying it needs one: a listing holding no item
                // leaves it to the items, which offer it bound.
                if let Some(item) = decl.item {
                    offered.type_mut().contract.item = Some(item.to_owned());
                }
                let for_agents = offered.clone().for_audience(tilo_actions::Audience::Agents);
                DeclaredSpec {
                    offered,
                    for_agents,
                }
            })
            .collect();
        std::rc::Rc::new(OwnSpecs {
            declared,
            apply: apply_spec(vocabulary),
            group: group_spec(vocabulary),
        })
    })
}

/// Build the action a declaration produces for JSON arguments, validating them
/// against its parameters exactly as the host does.
pub fn build_action<R: Resource>(
    id: &str,
    arguments: &serde_json::Map<String, serde_json::Value>,
    now_ms: i64,
) -> Result<R::Action, String> {
    typed::<R>(build_action_of(vocabulary::<R>(), id, arguments, now_ms)?)
}

/// [`build_action`] of the resource `vocabulary`, on the side invoking it
/// ([`crate::content::invoking`]).
pub(crate) fn build_action_of(
    vocabulary: &Vocabulary,
    id: &str,
    arguments: &serde_json::Map<String, serde_json::Value>,
    now_ms: i64,
) -> Result<Built, String> {
    crate::content::invoking(|| build_invoked(vocabulary, id, arguments, now_ms))
}

fn build_invoked(
    vocabulary: &Vocabulary,
    id: &str,
    arguments: &serde_json::Map<String, serde_json::Value>,
    now_ms: i64,
) -> Result<Built, String> {
    if id == crate::GROUP {
        return Err("a group is several actions; build it with `group::build_group`".into());
    }
    let read = if id == APPLY {
        Some((APPLY_PARAM, "missing action"))
    } else if id == FIELD_EDIT && vocabulary.edits {
        Some((EDIT_PARAM, "missing edit"))
    } else {
        None
    };
    if let Some((param, missing)) = read {
        let Some(value) = arguments.get(param).cloned() else {
            return Err(missing.to_owned());
        };
        let mut action = if id == APPLY {
            read_apply(vocabulary, value)?
        } else {
            read_edit(vocabulary, value)?
        };
        action.stamp(now_ms);
        return Ok(action);
    }
    let declarations = vocabulary.declarations();
    let Some(decl) = declarations.iter().find(|decl| decl.id == id) else {
        return Err(format!("{} has no action `{id}`", vocabulary.label));
    };
    let args = match ActionArgs::bind_json(&decl.params, arguments) {
        Ok(args) => args,
        Err(error) => return Err(error.to_string()),
    };
    (decl.build)(&args, now_ms)
}

/// `resource` with the bound edit `decl` published on it.
///
/// An id the resource does not declare is added. One it declares is kept,
/// unless `decl` says it refines it ([`ActionDecl::refining`]) and takes the
/// same parameters with the same permission and risk: then it builds the
/// same edit from the same arguments and only adds where it was invoked from
/// (an append that leaves its writer's caret after the text), and replaces
/// the declared spec while the binding lasts.
#[must_use]
pub fn bind_declaration(
    resource: tilo_actions::ResourceSpec,
    decl: &Declaration,
) -> tilo_actions::ResourceSpec {
    let spec = spec_of_declaration(decl);
    let mut resource = resource;
    match resource
        .actions
        .iter_mut()
        .find(|existing| existing.id == decl.id)
    {
        Some(declared) => {
            if decl.refines && same_shape(&spec, declared) {
                *declared = spec;
            }
            resource
        }
        None => resource.with_action(spec),
    }
}

fn same_shape(bound: &ActionSpec, declared: &ActionSpec) -> bool {
    let shape = |spec: &ActionSpec| {
        spec.params()
            .iter()
            .map(|param| (param.name.to_string(), param.ty, param.required))
            .collect::<Vec<_>>()
    };
    bound.kind == declared.kind
        && shape(bound) == shape(declared)
        && bound.contract.kind == declared.contract.kind
        && bound.contract.field == declared.contract.field
        && bound.contract.risk == declared.contract.risk
}

/// A resource that one app keeps for every app of the workspace: its
/// accounts, which Settings keeps and Mail signs in to; the people it knows,
/// which Contacts keeps and Mail, Calendar and Messages address. Opened as
/// the workspace's record, at the keeper's route (`ViewCx::shared_workspace`
/// in `tilo-app`): one record for every member, its changes decided by the
/// workspace's grants on the keeper's resource.
pub trait SharedResource: Resource {
    /// The app that keeps the record: whose route holds it, and whose surface
    /// its changes are decided against.
    const OWNER: &'static str;
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SearchRow {
    /// The dimmer line under the title (an address, a path, a date).
    pub subtitle: Option<String>,
    /// A named icon from the icon set (`"mail"`, `"calendar"`); `None` draws
    /// the app's own.
    pub icon: Option<String>,
    /// What the hit is, for the row's shape.
    pub shape: SearchRowShape,
}

impl SearchRow {
    /// A generic row with `subtitle` under the title.
    pub fn subtitle(subtitle: impl Into<String>) -> Self {
        Self {
            subtitle: Some(subtitle.into()),
            ..Self::default()
        }
    }

    /// A row of `shape`.
    #[must_use]
    pub fn shaped(shape: SearchRowShape) -> Self {
        Self {
            shape,
            ..Self::default()
        }
    }

    /// The row's named icon.
    #[must_use]
    pub fn icon(mut self, name: impl Into<String>) -> Self {
        self.icon = Some(name.into());
        self
    }
}

#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub enum SearchRowShape {
    /// Icon, title and subtitle.
    #[default]
    Plain,
    /// A message: who sent it, a snippet, when, and whether it is unread.
    Message {
        sender: String,
        snippet: Option<String>,
        date: Option<String>,
        unread: bool,
    },
    /// A video, track or other media item: who made it and how long it
    /// runs. (A provider with artwork answers its own rows, with
    /// `AppImage::from_image_store` thumbnails.)
    Media {
        byline: Option<String>,
        duration: Option<String>,
    },
    /// A match inside a file: the path, the line and the matched line.
    FileHit {
        path: String,
        line: Option<u32>,
        snippet: String,
    },
}

pub use tilo_actions::{ScopeDecl, scope_contains};

#[cfg(test)]
mod schema_sharing_tests;

#[cfg(test)]
mod selection_place_tests {
    use super::Place;
    use tilo_actions::SelectionPlace;
    use tilo_actions::selection::MAX_PLACE_ITEM_BYTES;

    #[test]
    fn a_selection_place_is_the_place_an_action_takes() {
        for (place, expected_json) in [
            (Place::Item("p1".into()), r#"{"item":"p1"}"#),
            (
                Place::Caret {
                    item: "p1".into(),
                    at: 3,
                },
                r#"{"item":"p1","at":3}"#,
            ),
            (
                Place::Range {
                    item: "p1".into(),
                    start: 2,
                    end: 7,
                },
                r#"{"item":"p1","start":2,"end":7}"#,
            ),
            (
                Place::Item("a".repeat(MAX_PLACE_ITEM_BYTES)),
                &format!(r#"{{"item":"{}"}}"#, "a".repeat(MAX_PLACE_ITEM_BYTES)),
            ),
        ] {
            let wire = serde_json::to_string(&place).unwrap();
            assert_eq!(wire, expected_json, "valid places serialise as before");
            let selection = SelectionPlace::from(place.clone());
            assert_eq!(
                serde_json::to_string(&selection).unwrap(),
                wire,
                "both travel in one wire form"
            );
            assert_eq!(serde_json::from_str::<Place>(&wire).unwrap(), place);
            assert_eq!(Place::try_from(selection).unwrap(), place);
        }

        let overlong_ascii = "a".repeat(MAX_PLACE_ITEM_BYTES + 1);
        let overlong_utf8 = "界".repeat(MAX_PLACE_ITEM_BYTES / 3 + 1);
        assert!(overlong_utf8.len() > MAX_PLACE_ITEM_BYTES);

        for bad_item in [
            String::new(),
            overlong_ascii,
            overlong_utf8,
            "p\n1".to_owned(),
            "p\u{0}1".to_owned(),
            "p\x1b1".to_owned(),
            "p\t1".to_owned(),
        ] {
            for selection in [
                SelectionPlace::item(bad_item.clone()),
                SelectionPlace::caret(bad_item.clone(), 0),
                SelectionPlace::range(bad_item.clone(), 0, 1),
            ] {
                assert!(
                    Place::try_from(selection.clone()).is_err(),
                    "Place::try_from accepted invalid SelectionPlace: {selection:?}"
                );
                let json = serde_json::to_value(&selection).unwrap();
                assert!(
                    serde_json::from_value::<Place>(json.clone()).is_err(),
                    "Place::deserialize accepted invalid JSON: {json}"
                );
            }
        }

        for malformed in [
            serde_json::json!({"item": "p1", "at": 1, "start": 0, "end": 2}),
            serde_json::json!({"item": "p1", "start": 2}),
            serde_json::json!({"item": "p1", "end": 2}),
            serde_json::json!({"item": "p1", "start": 5, "end": 2}),
        ] {
            let wire: SelectionPlace = serde_json::from_value(malformed.clone()).unwrap();
            let from_selection = Place::try_from(wire).unwrap_err();
            let from_json = serde_json::from_value::<Place>(malformed)
                .unwrap_err()
                .to_string();
            for error in [&from_selection, &from_json] {
                assert!(
                    error.contains("at") && error.contains("start") && error.contains("end"),
                    "malformed-shape error should name `at` and `start`/`end`: {error}"
                );
            }
        }
        assert!(
            serde_json::from_value::<Place>(serde_json::json!({"item": "p1", "extra": true}))
                .is_err()
        );
    }
}