mahbot 0.10.5

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

use crate::docgen;
use crate::tools::path::PathAccess;
use crate::{Tool, Workspace};
use anyhow::{Context as _, Result};
use async_trait::async_trait;
use chrono::{Datelike as _, Timelike as _};
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use super::GENERATED_DIR;

/// The marker every produced file reaches a caller through: `[FILE:<path>]`.
pub(crate) const FILE_MARKER: &str = "[FILE:";

/// Longest base name kept from `file_name`; the extension and the uniqueness
/// suffix are added on top.
const MAX_BASE_CHARS: usize = 80;

/// Most files ONE `pdf_split` call may produce: the selection list is the
/// model's, and more than this is more than a reply can carry.
const MAX_SPLIT_PARTS: usize = 50;

/// Upper bound on the files ONE `pdf_merge` call may take; more is refused.
const MAX_MERGE_INPUTS: usize = 50;

/// Most one `pdf_merge` may load in total — the kit reads every input at once,
/// so without a total a large merge ends as a killed run blamed on the product.
const MAX_MERGE_BYTES: u64 = 200 * 1024 * 1024;

/// Most uncovered characters the "missing from the file" note names; the kit's
/// own `unsupported` array still carries every one.
const UNSUPPORTED_NOTE_MAX: usize = 10;

/// The fixed operation set, in the schema's order: the `oneOf` entries, the
/// unknown-action hint and the dispatch `match` all come from it.
const ACTIONS: [&str; 13] = [
    "create",
    "fill_template",
    "docx_edit",
    "xlsx_edit",
    "pptx_edit",
    "pdf_merge",
    "pdf_split",
    "pdf_rotate",
    "pdf_crop",
    "pdf_resize",
    "pdf_text",
    "pdf_image",
    "pdf_form_fill",
];

/// One family's edit vocabulary, in the order the description states it: the `op`
/// enum, the fields text and both field refusals read this one table, and the
/// rules a field list cannot carry are stated in the family's `edits_arg`.
#[expect(clippy::too_many_lines)] // the one table every family's vocabulary lives in
fn edit_op_fields(
    family: crate::ooxml::Family,
) -> &'static [(&'static str, &'static [&'static str])] {
    match family {
        crate::ooxml::Family::Docx => &[
            ("replace_text", &["find", "replace"]),
            ("insert_text", &["find", "insert", "position"]),
            ("remove_text", &["find"]),
            ("remove_paragraph", &["find"]),
            (
                "format_text",
                &[
                    "find",
                    "bold",
                    "italic",
                    "underline",
                    "strike",
                    "size",
                    "color",
                ],
            ),
            (
                "format_paragraph",
                &[
                    "find",
                    "align",
                    "style",
                    "indent_left",
                    "indent_right",
                    "indent_first_line",
                    "spacing_before",
                    "spacing_after",
                    "line_spacing",
                    "list",
                    "level",
                ],
            ),
            ("add_paragraph", &["text", "after"]),
            ("add_image", &["after", "image", "width", "height"]),
            ("add_table", &["after", "headers", "rows"]),
        ],
        crate::ooxml::Family::Xlsx => &[
            ("set_cell", &["sheet", "cell", "value", "number_format"]),
            ("clear_cell", &["sheet", "cell"]),
            (
                "format_cells",
                &[
                    "sheet",
                    "range",
                    "column",
                    "row",
                    "font",
                    "size",
                    "bold",
                    "italic",
                    "underline",
                    "strike",
                    "color",
                    "fill",
                    "border",
                    "align",
                    "vertical",
                    "wrap",
                    "number_format",
                    "width_chars",
                    "height_points",
                ],
            ),
            ("insert_row", &["sheet", "row"]),
            ("delete_row", &["sheet", "row"]),
            ("insert_column", &["sheet", "column"]),
            ("delete_column", &["sheet", "column"]),
            ("merge_cells", &["sheet", "range"]),
            ("unmerge_cells", &["sheet", "range"]),
            ("add_sheet", &["name"]),
            ("rename_sheet", &["sheet", "name"]),
            ("delete_sheet", &["sheet"]),
            ("move_sheet", &["sheet", "to"]),
            ("add_image", &["sheet", "cell", "image", "width", "height"]),
        ],
        crate::ooxml::Family::Pptx => &[
            ("replace_text", &["slide", "find", "replace"]),
            ("remove_text", &["slide", "find"]),
            (
                "format_text",
                &[
                    "slide",
                    "find",
                    "bold",
                    "italic",
                    "underline",
                    "strike",
                    "size",
                    "color",
                    "align",
                ],
            ),
            ("add_paragraph", &["slide", "text", "after", "level"]),
            ("remove_paragraph", &["slide", "find"]),
            (
                "add_image",
                &[
                    "slide",
                    "image",
                    "x_fraction",
                    "y_fraction",
                    "width_fraction",
                    "height_fraction",
                ],
            ),
            (
                "add_table",
                &[
                    "slide",
                    "headers",
                    "rows",
                    "x_fraction",
                    "y_fraction",
                    "width_fraction",
                    "height_fraction",
                ],
            ),
            ("add_slide", &["after", "title", "bullets"]),
            ("delete_slide", &["slide"]),
            ("move_slide", &["slide", "to"]),
            ("duplicate_slide", &["slide"]),
            ("replace_notes", &["slide", "find", "replace"]),
            ("remove_notes", &["slide", "find"]),
            ("add_notes", &["slide", "text"]),
        ],
    }
}

fn op_fields(family: crate::ooxml::Family, op: &str) -> &'static [&'static str] {
    edit_op_fields(family)
        .iter()
        .find(|(name, _)| *name == op)
        .map(|(_, fields)| *fields)
        .expect("the op was checked against the family's vocabulary")
}

/// The pptx edits that look text up on the slide itself, and so are the only ones
/// whose refusal can name a diagram's text; a notes op searches the notes part.
const PPTX_SLIDE_TEXT_OPS: [&str; 5] = [
    "replace_text",
    "remove_text",
    "format_text",
    "add_paragraph",
    "remove_paragraph",
];

/// The formats `create` understands; the value doubles as the extension.
const SUPPORTED_FORMATS: [&str; 4] = [
    crate::ooxml::Family::Docx.name(),
    crate::ooxml::Family::Xlsx.name(),
    crate::ooxml::Family::Pptx.name(),
    "pdf",
];

/// A closed numeric range from [`RULES`], `min_exclusive` marking a low end to
/// exceed rather than reach.
#[derive(serde::Deserialize)]
struct Span {
    min: f64,
    max: f64,
    #[serde(default)]
    min_exclusive: bool,
}

impl Span {
    fn contains(&self, value: f64) -> bool {
        let above_min = if self.min_exclusive {
            value > self.min
        } else {
            value >= self.min
        };
        above_min && value <= self.max
    }

    fn bounds(&self) -> String {
        if self.min_exclusive {
            format!("greater than {} and at most {}", self.min, self.max)
        } else {
            format!("between {} and {}", self.min, self.max)
        }
    }
}

#[derive(serde::Deserialize)]
struct Rules {
    heading_levels: Vec<f64>,
    scalar_kinds: Vec<String>,
    image_extensions: Vec<String>,
    /// The most columns a Word table may hold — Word refuses a row of more than 63
    /// cells; a presentation's or a PDF's table has no such bound.
    table_columns_max: usize,
    /// A length in points where zero is not a length: a placed picture's width or
    /// height and a `pdf_text` font size, one bound wherever a page measure is stated.
    dimension_points: Span,
    slide_position_fraction: Span,
    slide_size_fraction: Span,
    /// A docx `format_text` size in points; `<w:sz>` counts half-points and caps at
    /// 1638 (819 points), so the kit writes the doubled number.
    text_size_points: Span,
    paragraph_alignments: Vec<(String, String)>,
    paragraph_lists: Vec<(String, String)>,
    /// A docx `format_paragraph` indent in points, which the kit writes to Word's
    /// twips; below zero it is a `<w:hanging>` first line.
    paragraph_indent_points: Span,
    paragraph_spacing_points: Span,
    /// A docx `format_paragraph` line height in points, written in whole twips by
    /// rounding: the floor is a round 0.05 above the 0.025 that would round to zero.
    paragraph_line_points: Span,
    /// The longest docx `format_paragraph` `style` name — a length, not a check that
    /// the style exists.
    paragraph_style_max: usize,
    /// A pptx `format_text` size in points; `<a:rPr sz>` counts hundredths, unlike
    /// Word's half-points.
    slide_text_size_points: Span,
    /// A xlsx `format_cells` font size in points; Excel's own box holds 1 to 409.
    cell_font_points: Span,
    column_width_chars: Span,
    row_height_points: Span,
    /// The longest xlsx `format_cells` font name — Excel's own limit.
    font_name_max: usize,
    /// The most cells one `format_cells` range may address: the kit writes it out cell
    /// by cell, so a whole-column spelling would write a sheet-sized body.
    format_cells_max: usize,
    max_pages_per_request: usize,
    pdf_point_abs_max: f64,
    /// The fraction of a page's visible area a `pdf_crop` names per side, from the
    /// displayed top-left; zero is a legal edge, an area with no width or height is not.
    pdf_page_fraction: Span,
    /// The slack a `pdf_crop` area may reach past [`Self::pdf_page_fraction`]'s top
    /// end, so a computed `1/3`-wide area is not refused for a bit a double cannot hold.
    pdf_fraction_slack: f64,
    pdf_opacity: Span,
    color_digits: usize,
    slide_alignments: Vec<(String, String)>,
    cell_alignments: Vec<String>,
    cell_verticals: Vec<String>,
    cell_border_sides: Vec<String>,
    degrees_step: i64,
    sheet_name_max: usize,
    sheet_name_forbidden: String,
    edit_text_max: usize,
    edits_max: usize,
    bullets_max: usize,
    paragraph_level_max: u32,
    sheet_row_max: u32,
    sheet_column_max: u32,
    /// The longest `set_cell`/`format_cells` `number_format`: text inside the shared cap.
    number_format_max: usize,
    /// The slide sizes a created presentation may name, in the prompt's order.
    pptx_sizes: Vec<PptxSize>,
    /// The deck this tool wrote before a size could be named — 10 × 5.625 in
    /// (`LAYOUT_16x9`), every kit-placed measurement's reference, and what an unnamed
    /// `create` still writes.
    pptx_default_size: DeckSize,
}

/// A slide size in EMU, the unit `<p:sldSz>` states and every deck measure scales from.
#[derive(serde::Deserialize)]
struct DeckSize {
    width_emu: u64,
    height_emu: u64,
}

impl DeckSize {
    /// The size in inches to a thousandth, integer arithmetic with no rounding, so
    /// 13.333… in is truncated where 10 × 5.625 in is exact.
    fn inches(&self) -> String {
        const EMU_PER_INCH: u64 = 914_400;
        let side = |emu: u64| {
            let fraction = format!("{:03}", emu % EMU_PER_INCH * 1000 / EMU_PER_INCH);
            let fraction = fraction.trim_end_matches('0');
            let dot = if fraction.is_empty() { "" } else { "." };
            format!("{}{dot}{fraction}", emu / EMU_PER_INCH)
        };
        format!("{} × {} in", side(self.width_emu), side(self.height_emu))
    }
}

/// One size [`Rules::pptx_sizes`] states: the word and the deck it means, in EMU.
#[derive(serde::Deserialize)]
struct PptxSize {
    name: String,
    #[serde(flatten)]
    deck: DeckSize,
}

/// [`crate::docgen::rules`] parsed into this tool's shape: a file this shape cannot
/// be taken from is caught by the test below, not by a call.
static RULES: LazyLock<Rules> = LazyLock::new(|| {
    serde::Deserialize::deserialize(crate::docgen::rules())
        .expect("assets/docgen/rules.json must state the rules the document tool enforces")
});

/// Create and edit office documents and PDFs. See the module docs.
///
/// `access` decides where *inputs* come from; output always lands in the caller's
/// own `generated/` ([`crate::agent::tool_output_dir`]).
pub(crate) struct DocumentTool {
    access: PathAccess,
}

impl DocumentTool {
    #[must_use]
    pub(crate) const fn new(access: PathAccess) -> Self {
        Self { access }
    }

    /// Where inputs may be read from, in the access level's own wording: only the
    /// admin's and a guest's levels reach this tool, the allowlisted one being worded
    /// as the workspace it certainly covers.
    const fn input_location(&self) -> &'static str {
        match self.access {
            PathAccess::Unrestricted => {
                "readable from anywhere on this machine (the product's own live databases excepted)"
            }
            PathAccess::Workspace | PathAccess::Allowlisted => "confined to your workspace",
        }
    }
}

#[async_trait]
impl Tool for DocumentTool {
    fn name(&self) -> &'static str {
        "document"
    }

    /// Hidden while the managed runtime is missing — the tool cannot work without it,
    /// and `execute` still refuses honestly if the runtime vanishes mid-run.
    fn is_advertised(&self) -> bool {
        crate::tools::bun::bun_binary_path().is_some()
    }

    /// Advertises the `[FILE:…]` marker kind: the reply must name it to deliver the file, and
    /// the marker this result carries is what mentions the file to the media sweep.
    fn media_marker(&self) -> Option<&'static str> {
        Some(FILE_MARKER)
    }

    /// A reply can carry many markers (`pdf_split` lists one per range), so the list is
    /// never truncated.
    fn preserve_full_output(&self) -> bool {
        true
    }

    /// The prompt asset with the rules the schema cannot state — the safety promise,
    /// the losses and refusals no argument carries; bounds stay in the schema.
    fn description(&self) -> String {
        let ppt = crate::reader_output::ppt_description_substitutions();
        let input_mb = megabytes(crate::util::FILE_MAX_BYTES).to_string();
        let edit_text_max = RULES.edit_text_max.to_string();
        let docx_inline_marks = spelled_docx_marks(true);
        let docx_label_marks = spelled_docx_marks(false);
        let mut pairs: Vec<(&str, &str)> = vec![
            ("{{input_location}}", self.input_location()),
            ("{{input_mb}}", &input_mb),
            ("{{edit_text_max}}", &edit_text_max),
            ("{{docx_inline_marks}}", &docx_inline_marks),
            ("{{docx_label_marks}}", &docx_label_marks),
        ];
        pairs.extend(ppt.iter().map(|(key, value)| (*key, value.as_str())));
        crate::prompt::substitute(&crate::prompt::load_prompt("tool/document.md"), &pairs)
    }

    /// The per-action contract, in `chrome`'s shape: `action` is a `oneOf` with one
    /// [`super::action_entry_schema`] entry per action, so the arguments taken,
    /// required and allowed are the schema's own statement rather than prose.
    fn parameters_schema(&self) -> Value {
        super::tool_params_schema(
            &json!({
                "action": {
                    "oneOf": ACTIONS.iter().map(|action| action_schema(action)).collect::<Vec<_>>()
                },
                "file_name": file_name_arg(),
                "metadata": metadata_arg(),
            }),
            &["action"],
        )
    }

    async fn execute(&self, ws: &Workspace, args: Value) -> Result<String> {
        Ok(self.dispatch(ws, args).await?.text)
    }

    async fn execute_answer(&self, ws: &Workspace, args: Value) -> Result<super::ToolAnswer> {
        self.dispatch(ws, args).await
    }
}

/// A call's arguments flattened for the dispatch: the nested
/// `{"action": {"pdf_rotate": {…}}}` shape and the chrome-shaped one both land here,
/// with the shared `file_name` merged in; anything else is refused.
fn normalize_call(args: &Value) -> Result<Value> {
    let nested_shape = || {
        anyhow::anyhow!(
            "usage: \"action\" must name one of {} as a string with the action's own arguments \
             beside it, or as an object naming one action — hint: like {{\"action\": \"pdf_rotate\", \
             \"path\": \"…\", \"degrees\": 90}} or {{\"action\": {{\"pdf_rotate\": {{…}}}}}}",
            ACTIONS.join(", ")
        )
    };
    let flattened = |name: &str, fields: &serde_json::Map<String, Value>| {
        // The caller's other top-level keys come along; one the action does not take is
        // refused by name afterwards.
        let object = args
            .as_object()
            .expect("a call whose action matched is an object");
        let mut flat = object
            .iter()
            .filter(|(key, _)| key.as_str() != "action" && key.as_str() != name)
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect::<serde_json::Map<String, Value>>();
        flat.extend(fields.clone());
        flat.insert("action".to_owned(), json!(name));
        if let Some(file_name) = args.get("file_name") {
            flat.insert("file_name".to_owned(), file_name.clone());
        }
        Value::Object(flat)
    };
    match args.get("action") {
        // The flat call, and the chrome-shaped one whose arguments sit under the
        // action's key.
        Some(Value::String(name)) => match args.get(name.as_str()) {
            Some(Value::Object(fields)) => Ok(flattened(name, fields)),
            _ => Ok(args.clone()),
        },
        // The nested call the schema describes: the one key names the action.
        Some(Value::Object(action)) if action.len() == 1 => {
            let (name, fields) = action.iter().next().expect("one key");
            match fields {
                Value::Object(fields) => Ok(flattened(name, fields)),
                _ => Err(nested_shape()),
            }
        }
        _ => Err(nested_shape()),
    }
}

/// Refuse an argument the action does not take: the interface is the contract, so a
/// key with no place for it is named rather than ignored. `action` and `file_name` are
/// every action's own, and a `null` value is not stated.
fn require_declared_arguments(action: &str, args: &Value) -> Result<()> {
    let entry = action_schema(action);
    let declared = entry["properties"][action]["properties"]
        .as_object()
        .expect("every action's entry declares its arguments");
    let accepted = std::iter::once("action")
        .chain(std::iter::once("file_name"))
        .chain(declared.keys().map(String::as_str))
        .collect::<Vec<_>>();
    let Some(object) = args.as_object() else {
        return Ok(());
    };
    let unknown = object
        .keys()
        .map(String::as_str)
        .filter(|key| !accepted.contains(key) && stated(object, key))
        .collect::<Vec<_>>();
    if !unknown.is_empty() {
        let named = listed(
            &unknown
                .iter()
                .map(|key| format!("\"{key}\""))
                .collect::<Vec<_>>(),
        );
        anyhow::bail!(
            "usage: {action} takes no argument {named} — hint: it takes {}",
            listed(&accepted)
        );
    }
    Ok(())
}

fn text_arg(description: &str) -> Value {
    json!({ "type": "string", "description": description })
}

fn number_arg(description: &str) -> Value {
    json!({ "type": "number", "description": description })
}

fn integer_arg(description: &str) -> Value {
    json!({ "type": "integer", "description": description })
}

fn toggle_arg() -> Value {
    json!({ "type": "boolean" })
}

fn bool_arg(description: &str) -> Value {
    json!({ "type": "boolean", "description": description })
}

fn choice_arg<S: AsRef<str>>(values: &[S], description: &str) -> Value {
    let values: Vec<&str> = values.iter().map(AsRef::as_ref).collect();
    json!({ "type": "string", "enum": values, "description": description })
}

fn array_arg(items: &Value, description: &str) -> Value {
    json!({ "type": "array", "items": items, "description": description })
}

fn scalar_arg() -> Value {
    json!({ "type": RULES.scalar_kinds })
}

/// `file_name`: the produced file's base name, capped at [`MAX_BASE_CHARS`].
fn file_name_arg() -> Value {
    text_arg(&format!(
        "Base name for the produced file (max {MAX_BASE_CHARS} chars); the tool appends the \
         extension, puts the file in the workspace's generated/ directory and makes the name \
         unique."
    ))
}

/// `metadata`: the PDF's own description, which every PDF-writing action takes; a
/// field left out is left as the file has it (an edit advances `modified`).
fn metadata_arg() -> Value {
    let properties = crate::docgen::pdf_metadata_fields()
        .iter()
        .map(|field| (field.key.clone(), text_arg(&field.description)))
        .collect::<serde_json::Map<_, _>>();
    json!({
        "type": "object",
        "minProperties": 1,
        "additionalProperties": false,
        "description": format!(
            "The PDF's own description. A field left out stays as the file has it — except an \
             existing modified date, which advances to a write; an empty string clears one; \
             keywords is the single text the file carries. A date is {}.",
            crate::docgen::pdf_date_format()
        ),
        "properties": properties,
    })
}

/// `metadata` as a PDF action declares it: it opts into the tool-level argument
/// rather than restating its fields per action.
fn metadata_entry() -> Value {
    json!({ "type": "object" })
}

/// `path`: the one input document every action but `pdf_merge` takes — never
/// modified, and its own bytes decide the format.
fn path_arg() -> Value {
    text_arg("The document to work on.")
}

/// `pdf_image`: the picture to place; a PDF holds pictures in its own two encodings.
fn pdf_image_arg() -> Value {
    picture_arg(pdf_pictures().names)
}

/// `image`: a PNG, JPEG or WebP by its content, and the one sizing rule every
/// placement shares.
///
/// Every field built here NAMES A FILE, which is the tie the command line reads to
/// resolve each one in the caller's own directory.
fn image_arg() -> Value {
    picture_arg(embedded_pictures().names)
}

/// `image` inside a `create` block: [`image_arg`]'s picture with the narrower PDF set.
fn content_image_arg() -> Value {
    picture_arg(&format!(
        "{}; a PDF takes {}",
        embedded_pictures().names,
        pdf_pictures().names
    ))
}

/// The picture arguments [`image_arg`] and its two siblings build; every one names a file.
#[cfg(test)]
pub(crate) fn image_args() -> Vec<Value> {
    vec![image_arg(), content_image_arg(), pdf_image_arg()]
}

/// What a picture argument states, with `names` the formats its target takes.
fn picture_arg(names: &str) -> Value {
    text_arg(&format!(
        "The picture to place ({names}); naming one side's size alone keeps its own proportions."
    ))
}

/// `paths`: a merge's inputs — the count as `minItems`/`maxItems`, the total size only
/// the description can state.
fn paths_arg() -> Value {
    json!({
        "type": "array",
        "items": text_arg("Path of one PDF."),
        "minItems": 2,
        "maxItems": MAX_MERGE_INPUTS,
        "description": format!(
            "The PDFs to merge, in order: at most {} MB in total.",
            megabytes(MAX_MERGE_BYTES)
        ),
    })
}

/// `values`: the name-keyed map both fills take; at least one entry, as `minProperties`
/// and the boundary alike require.
fn values_arg(kind: &str) -> Value {
    json!({
        "type": "object",
        "minProperties": 1,
        "description": format!(
            "One entry per {kind}, keyed by its name; a value is text, a number or a boolean."
        ),
    })
}

/// `pages`: the one page grammar every PDF action takes — `"all"` or a
/// comma-separated list of `N` and `N-M`; a split cuts one file per element, the other
/// actions act on their union.
fn pages_arg(split: bool) -> Value {
    let element = text_arg(
        "An entry: \"all\", a page, a range, or a comma list like \"1-3,5\"; \"all\" stands alone.",
    );
    if split {
        json!({
            "type": "array",
            "items": element,
            "minItems": 1,
            "maxItems": MAX_SPLIT_PARTS,
            "description": format!(
                "One output file per entry, in order: [\"1-3\", \"5\"] makes two files, and \
                 [\"1-3,5\"] one file holding those four pages. At most {MAX_SPLIT_PARTS} files \
                 and {} pages.",
                RULES.max_pages_per_request
            ),
        })
    } else {
        array_arg(
            &element,
            &format!(
                "The pages to act on, as [\"1-3\", \"5\"]; absent means all pages. At most \
                 {} pages.",
                RULES.max_pages_per_request
            ),
        )
    }
}

/// A row of a table or a sheet: the scalars the shared rules name (a sheet cell may
/// also be a formula object).
fn row_arg() -> Value {
    json!({ "type": "array", "items": scalar_arg() })
}

/// The one statement of a placed picture's size: the unit, the bound, and the derived
/// side held to it too.
fn picture_size_rule() -> String {
    format!(
        "in points, {}; a side derived from the other one is held to the same bound",
        RULES.dimension_points.bounds()
    )
}

/// A size a picture is placed at, in points — a content-block or `add_image` height,
/// and a `pdf_image`'s placed size.
fn placed_size_arg(what: &str) -> Value {
    number_arg(&format!("{what} {}.", picture_size_rule()))
}

/// With neither side named, a laid-out block's picture keeps its own size, fitted whole
/// into the page's or slide's text column; one in a sheet has no column.
const BLOCK_IMAGE_FIT: &str = "with neither side named the picture keeps its own size, fitted \
                                whole into the page's or slide's own text column.";

/// A placed picture's width: the shared placement rule, then `fallback` — the one part a
/// laid-out block's picture and one in a sheet do not share.
fn picture_width_arg(what: &str, fallback: &str) -> Value {
    number_arg(&format!("{what} {}; {fallback}", picture_size_rule()))
}

/// A `format_cells` `border`: the sides to set, each a boolean; an object naming no
/// side states nothing and is refused, which a declaration cannot say.
fn border_arg() -> Value {
    let sides = RULES
        .cell_border_sides
        .iter()
        .map(|side| (side.clone(), bool_arg("Set this side.")))
        .collect::<serde_json::Map<String, Value>>();
    json!({
        "type": "object",
        "additionalProperties": false,
        "properties": sides,
        "description": "The sides to set — true draws a thin border on that side, false takes its \
                        own away — at least one of them.",
    })
}

/// A colour in the shared rules' hex digits, with the optional leading `#`.
fn color_arg(what: &str) -> Value {
    text_arg(&format!("{what}: {} hex digits.", RULES.color_digits))
}

/// A `format_paragraph` `list`: a word from `RULES.paragraph_lists`, or `false` taking
/// the paragraph's numbering away.
fn list_arg() -> Value {
    let mut values = pair_words(&RULES.paragraph_lists)
        .into_iter()
        .map(|word| json!(word))
        .collect::<Vec<_>>();
    values.push(json!(false));
    json!({
        "type": ["string", "boolean"],
        "enum": values,
        "description": "The list kind, or false to take the paragraph's list away; absent keeps \
                        its numbering.",
    })
}

/// A `format_cells` `fill`: a colour, or `false` taking the fill away — no colour means
/// "no fill".
fn fill_arg() -> Value {
    json!({
        "anyOf": [
            { "type": "string" },
            { "enum": [false] },
        ],
        "description": format!(
            "Background: {} hex digits, or false to take the cell's fill away.",
            RULES.color_digits
        ),
    })
}

/// The block kinds `create`'s `content` accepts: each kind's fields and the ones it
/// requires — one table the declaration and the boundary's refusal both read.
const CONTENT_BLOCKS: &[(&str, &[&str], &[&str])] = &[
    // kind, its fields, the fields it requires
    ("heading", &["text", "level"], &["text"]),
    ("paragraph", &["text", "footnote"], &["text"]),
    ("notes", &["text"], &["text"]),
    ("list", &["items", "ordered"], &["items"]),
    ("table", &["headers", "rows"], &[]),
    ("image", &["image", "width", "height"], &["image"]),
    ("link", &["text", "url"], &["text", "url"]),
    ("page_break", &[], &[]),
    ("contents", &[], &[]),
];

/// What a block kind's own `type` declaration says, for the kinds a name alone does not carry.
fn block_kind_note(kind: &str) -> Option<String> {
    match kind {
        "page_break" => Some("A page break: the next block starts a new page.".to_owned()),
        "link" => Some("A paragraph holding a link: its text and the address it opens.".to_owned()),
        "contents" => Some(format!(
            "A table of contents over the document's headings (levels {}), with the page numbers \
             already written in; one per document.",
            listed(&RULES.heading_levels)
        )),
        _ => None,
    }
}

fn block_field(name: &str) -> Value {
    match name {
        "text" => text_arg("The block's text."),
        "level" => integer_arg(&format!("Level {}.", listed(&RULES.heading_levels))),
        "items" => array_arg(&scalar_arg(), "The bullets."),
        "ordered" => bool_arg("Number them."),
        "headers" => array_arg(
            &scalar_arg(),
            &format!(
                "The header cells; a .docx table holds at most {} columns.",
                RULES.table_columns_max
            ),
        ),
        "rows" => array_arg(
            &row_arg(),
            &format!(
                "The rows, each an array of cells; a .docx table holds at most {} columns.",
                RULES.table_columns_max
            ),
        ),
        "image" => content_image_arg(),
        "width" => picture_width_arg("Placed width", BLOCK_IMAGE_FIT),
        "height" => placed_size_arg("Placed height"),
        "footnote" => text_arg(
            "A footnote attached to this paragraph: its text is printed at the foot of the \
             page the paragraph lands on.",
        ),
        "url" => text_arg(
            "The address the link opens: an http, https, mailto or tel address, e.g. \
             https://example.com; another scheme is refused.",
        ),
        other => unreachable!("every block field has a declaration: {other}"),
    }
}

/// `content`: the blocks a docx/pptx/pdf create lays out, in order — one variant per
/// kind, declaring the fields the boundary refuses a block of another kind against.
fn content_arg() -> Value {
    let variants = CONTENT_BLOCKS
        .iter()
        .map(|(kind, fields, required)| {
            let mut properties = serde_json::Map::new();
            properties.insert(
                "type".to_owned(),
                match block_kind_note(kind) {
                    Some(note) => json!({ "enum": [kind], "description": note }),
                    None => json!({ "enum": [kind] }),
                },
            );
            properties.extend(
                fields
                    .iter()
                    .map(|name| ((*name).to_owned(), block_field(name))),
            );
            json!({
                "type": "object",
                "additionalProperties": false,
                "required": std::iter::once("type").chain(required.iter().copied()).collect::<Vec<_>>(),
                "properties": properties,
            })
        })
        .collect::<Vec<_>>();
    json!({
        "type": "array",
        "minItems": 1,
        "items": { "oneOf": variants },
        "description": "The blocks, in order, each with its own \"type\"; \"notes\" is pptx speaker \
                        notes, a table needs a row or a header, and a link, a page break, a \
                        footnote and a table of contents are a .docx's own.",
    })
}

/// The fields `create` declares for a sheet and the one it cannot do without: the one
/// owner, read by [`sheets_arg`] and by the boundary's refusal alike.
const SHEET_FIELDS: &[(&str, bool)] = &[
    // field, required
    ("name", false),
    ("rows", true),
    ("merges", false),
];

fn sheet_field_names() -> Vec<&'static str> {
    SHEET_FIELDS.iter().map(|(name, _)| *name).collect()
}

/// `sheets`: a workbook's sheets, each with a name, its rows and the ranges it merges;
/// the characters a name may not hold are stated inline.
fn sheets_arg() -> Value {
    let properties = SHEET_FIELDS
        .iter()
        .map(|(name, _)| ((*name).to_owned(), sheet_field(name)))
        .collect::<serde_json::Map<String, Value>>();
    let required = SHEET_FIELDS
        .iter()
        .filter(|(_, required)| *required)
        .map(|(name, _)| *name)
        .collect::<Vec<_>>();
    json!({
        "type": "array",
        "minItems": 1,
        "items": {
            "type": "object",
            "additionalProperties": false,
            "required": required,
            "properties": properties,
        },
        "description": "The workbook's sheets, in order.",
    })
}

fn sheet_field(name: &str) -> Value {
    match name {
        "name" => text_arg(&format!(
            "Sheet name: at most {} characters, none of {:?}, unique ignoring case; without one it \
             becomes Sheet<n>.",
            RULES.sheet_name_max, RULES.sheet_name_forbidden,
        )),
        "rows" => array_arg(&sheet_row_arg(), "The rows, top to bottom."),
        "merges" => array_arg(
            &text_arg("A range like A1:C1, corners in either order."),
            "Ranges to merge, each covering at least two cells; a merge never clears what its cells \
             hold.",
        ),
        other => unreachable!("every sheet field has a declaration: {other}"),
    }
}

/// A cell's value: text (a string starting with `=` stays text), a number, a boolean, or
/// a formula object, written as a formula and never evaluated.
fn cell_arg() -> Value {
    json!({
        "anyOf": [
            scalar_arg(),
            {
                "type": "object",
                "additionalProperties": false,
                "properties": { "formula": text_arg("The formula, without a leading =.") },
                "required": ["formula"],
            },
        ],
        "description": "Text (a string starting with `=` stays text), a number, a boolean, or \
                        {\"formula\": \"SUM(A1:A2)\"}; a number is written as the cell stores it, \
                        not as a reading displayed it.",
    })
}

fn sheet_row_arg() -> Value {
    array_arg(
        &cell_arg(),
        "One row, one cell after another, left to right.",
    )
}

/// What the four run toggles mean in every family's formatting path: one statement, not twelve.
const TOGGLE_RULE: &str = "bold, italic, underline and strike are toggles: true sets the \
                            property, false switches it off.";

/// `edits`: one edit object per family, declaring that family's `op` enum and the union
/// of its fields; the `op` description carries the mapping and the family's rules.
fn edits_arg(family: crate::ooxml::Family, fields: &Value, rules: &str) -> Value {
    let op_fields = edit_op_fields(family);
    let ops: Vec<&str> = op_fields.iter().map(|(op, _)| *op).collect();
    let mut properties = fields.clone();
    let fields_by_op = op_fields
        .iter()
        .map(|(op, taken)| format!("{op}: {}", taken.join(", ")))
        .collect::<Vec<_>>()
        .join("; ");
    let statements = [
        rules,
        TOGGLE_RULE,
        &format!("Fields by op: {fields_by_op}."),
    ];
    let description = statements
        .iter()
        .filter(|part| !part.is_empty())
        .copied()
        .collect::<Vec<_>>()
        .join(" ");
    properties["op"] = choice_arg(&ops, &description);
    json!({
        "type": "array",
        "minItems": 1,
        "maxItems": RULES.edits_max,
        "items": {
            "type": "object",
            "additionalProperties": false,
            "properties": properties,
            "required": ["op"],
        },
        "description": format!(
            "The edits, in order, at most {}. Applied whole or not at all: an edit whose fields \
             do not fit its op is refused by name rather than partly applied.",
            RULES.edits_max
        ),
    })
}

/// The schema's `oneOf` entry for one action: what it does with the refusal a caller
/// would otherwise learn by calling, the arguments it requires and those it takes.
#[expect(clippy::too_many_lines)] // the one place every action's arguments are stated
fn action_schema(action: &str) -> Value {
    match action {
        "create" => super::action_entry_schema(
            "create",
            "Write a new file: blocks for docx/pptx/pdf, sheets for xlsx. A PDF is laid out as a \
             simple stream: blocks follow one another down the page, and columns, floating objects \
             and exact page placement are not attempted. A .docx may carry a running header and \
             footer, page numbers, a table of contents over its headings, links, footnotes and \
             explicit page breaks.",
            &["format"],
            &json!({
                "format": choice_arg(&SUPPORTED_FORMATS, "The format to write."),
                "content": content_arg(),
                "sheets": sheets_arg(),
                "metadata": metadata_entry(),
                "size": choice_arg(
                    &pptx_size_words(),
                    &format!(
                        "A pptx slide size: {}. Unnamed is the {} deck this tool has always \
                         written.",
                        pptx_size_list(),
                        RULES.pptx_default_size.inches()
                    ),
                ),
                "header": text_arg(
                    "A running header, one paragraph per line: {page} is the page number and \
                     {pages} the document's page count.",
                ),
                "footer": text_arg(
                    "A running footer, one paragraph per line: {page} is the page number and \
                     {pages} the document's page count.",
                ),
            }),
        ),
        "fill_template" => super::action_entry_schema(
            "fill_template",
            "Fill a copy of the user's own .docx/.pptx/.xlsx sample's placeholders.",
            &["path", "values"],
            &json!({ "path": path_arg(), "values": values_arg("placeholder") }),
        ),
        "docx_edit" => super::action_entry_schema(
            "docx_edit",
            "Edit a .docx/.docm; a .docx package is required. Rewrite and format its text, and \
             add paragraphs, pictures and tables.",
            &["path", "edits"],
            &json!({
                "path": path_arg(),
                "edits": edits_arg(
                    crate::ooxml::Family::Docx,
                    &json!({
                        "find": text_arg("Text to find."),
                        "replace": text_arg("Text to write."),
                        "insert": text_arg("Text to insert."),
                        "position": choice_arg(&["before", "after"], "Where it lands."),
                        "text": text_arg("The paragraph's text."),
                        "after": text_arg("The paragraph to land after."),
                        "bold": toggle_arg(),
                        "italic": toggle_arg(),
                        "underline": toggle_arg(),
                        "strike": toggle_arg(),
                        "size": number_arg(&format!(
                            "Font size, {} points.",
                            RULES.text_size_points.bounds()
                        )),
                        "color": color_arg("Text colour"),
                        "align": choice_arg(
                            &pair_words(&RULES.paragraph_alignments),
                            "Paragraph alignment."
                        ),
                        "style": text_arg(&format!(
                            "A paragraph style the document defines, at most {} characters; \
                             Normal, Heading 1, Heading 2 and Heading 3 always work.",
                            RULES.paragraph_style_max
                        )),
                        "indent_left": number_arg(&format!(
                            "Left indent, {} points.",
                            RULES.paragraph_indent_points.bounds()
                        )),
                        "indent_right": number_arg(&format!(
                            "Right indent, {} points.",
                            RULES.paragraph_indent_points.bounds()
                        )),
                        "indent_first_line": number_arg(&format!(
                            "First-line indent, {} points; a negative one hangs.",
                            RULES.paragraph_indent_points.bounds()
                        )),
                        "spacing_before": number_arg(&format!(
                            "Space above, {} points.",
                            RULES.paragraph_spacing_points.bounds()
                        )),
                        "spacing_after": number_arg(&format!(
                            "Space below, {} points.",
                            RULES.paragraph_spacing_points.bounds()
                        )),
                        "line_spacing": number_arg(&format!(
                            "Line height, {} points.",
                            RULES.paragraph_line_points.bounds()
                        )),
                        "list": list_arg(),
                        "level": integer_arg(&format!("List level, 0 to {}.", RULES.paragraph_level_max)),
                        "image": image_arg(),
                        "width": picture_width_arg("Picture width", BLOCK_IMAGE_FIT),
                        "height": placed_size_arg("Picture height"),
                        "headers": array_arg(
                            &scalar_arg(),
                            &format!(
                                "add_table: the headings row; the table holds at most {} columns, \
                                 headings included.",
                                RULES.table_columns_max
                            ),
                        ),
                        "rows": array_arg(
                            &array_arg(&scalar_arg(), "A row of cells."),
                            &format!(
                                "add_table: the table's rows, each an array of cells — a table \
                                 holds at most {} columns; a headings row alone makes a table.",
                                RULES.table_columns_max
                            ),
                        ),
                    }),
                    "format_text and format_paragraph need one property beyond find. add_image and \
                     add_table land after the first paragraph that holds their after text — a \
                     table cell's anchor means after the whole table — and are refused, never \
                     appended, when no paragraph holds it.",
                ),
            }),
        ),
        "xlsx_edit" => super::action_entry_schema(
            "xlsx_edit",
            "Edit an .xlsx/.xlsm; an .xlsx package is required. Rewrite cells and formatting, shift \
             rows and columns, merge and unmerge a range, add, rename, move or delete a sheet, and \
             place a picture in a sheet.",
            &["path", "edits"],
            &json!({
                "path": path_arg(),
                "edits": edits_arg(
                    crate::ooxml::Family::Xlsx,
                    &json!({
                        "sheet": text_arg("Sheet name, as a reading prints it."),
                        "name": text_arg(&format!(
                            "A sheet name: at most {} characters, none of {:?}, unique ignoring \
                             case.",
                            RULES.sheet_name_max, RULES.sheet_name_forbidden
                        )),
                        "to": integer_arg(
                            "The 1-based position the sheet takes, counting the sheets as a reading \
                             prints them."
                        ),
                        "cell": text_arg("A1 address, like B7."),
                        "value": cell_arg(),
                        "number_format": text_arg(&format!(
                            "An Excel format code, at most {} characters.",
                            RULES.number_format_max
                        )),
                        "range": text_arg(&format!(
                            "Cells, like B2:D2, corners in either order; a format_cells range \
                             holds at most {} cells.",
                            RULES.format_cells_max
                        )),
                        "column": text_arg(&format!(
                            "Column letters, up to the {}th column.",
                            RULES.sheet_column_max
                        )),
                        "row": integer_arg(&format!(
                            "The 1-based row, up to {}.",
                            RULES.sheet_row_max
                        )),
                        "width_chars": number_arg(&format!(
                            "Column width, {} characters (as Excel shows one).",
                            RULES.column_width_chars.bounds()
                        )),
                        "height_points": number_arg(&format!(
                            "Row height, {} points.",
                            RULES.row_height_points.bounds()
                        )),
                        "font": text_arg(&format!(
                            "Font name, at most {} characters.",
                            RULES.font_name_max
                        )),
                        "size": number_arg(&format!(
                            "Font size, {} points.",
                            RULES.cell_font_points.bounds()
                        )),
                        "bold": toggle_arg(),
                        "italic": toggle_arg(),
                        "underline": toggle_arg(),
                        "strike": toggle_arg(),
                        "color": color_arg("Text colour"),
                        "fill": fill_arg(),
                        "border": border_arg(),
                        "align": choice_arg(&RULES.cell_alignments, "Horizontal alignment."),
                        "vertical": choice_arg(&RULES.cell_verticals, "Vertical alignment."),
                        "wrap": bool_arg("Wrap the text."),
                        "image": image_arg(),
                        "width": picture_width_arg(
                            "Picture width",
                            "with neither side named the picture keeps its own size.",
                        ),
                        "height": placed_size_arg("Picture height"),
                    }),
                    "An edit names one sheet unless it adds one. One target only: range, column or \
                     row, with at least one of its own properties. An inserted row or column may be \
                     one past the sheet's used range; a deleted one must be inside it.",
                ),
            }),
        ),
        "pptx_edit" => super::action_entry_schema(
            "pptx_edit",
            "Edit a .pptx/.pptm; a slide is its 1-based number.",
            &["path", "edits"],
            &json!({
                "path": path_arg(),
                "edits": edits_arg(
                    crate::ooxml::Family::Pptx,
                    &json!({
                        "slide": integer_arg("Slide number, as a reading prints it, 1-based."),
                        "find": text_arg("Text to find on the slide."),
                        "replace": text_arg("Text to write."),
                        "text": text_arg("The text to write."),
                        "after": {
                            "type": ["string", "integer"],
                            "description": "add_paragraph: the text it follows; add_slide: the slide number.",
                        },
                        "level": integer_arg(&format!("Outline level, 0 to {}.", RULES.paragraph_level_max)),
                        "bold": toggle_arg(),
                        "italic": toggle_arg(),
                        "underline": toggle_arg(),
                        "strike": toggle_arg(),
                        "size": number_arg(&format!(
                            "Font size, {} points.",
                            RULES.slide_text_size_points.bounds()
                        )),
                        "color": color_arg("Text colour"),
                        "align": choice_arg(&pair_words(&RULES.slide_alignments), "Alignment."),
                        "image": image_arg(),
                        "headers": array_arg(
                            &scalar_arg(),
                            "add_table: the headings row; a presentation's table has no column bound.",
                        ),
                        "rows": array_arg(
                            &array_arg(&scalar_arg(), "A row of cells."),
                            "add_table: the table's rows, each an array of cells — a headings row alone makes a table.",
                        ),
                        "x_fraction": number_arg(&format!(
                            "Across the slide, {} of its width; an unnamed place is the slide's \
                             middle, an unnamed size a picture's largest fit or a table's own, and \
                             a place named without a size can push either past the slide's edge.",
                            RULES.slide_position_fraction.bounds()
                        )),
                        "y_fraction": number_arg(&format!(
                            "Down the slide, {} of its height.",
                            RULES.slide_position_fraction.bounds()
                        )),
                        "width_fraction": number_arg(&format!(
                            "Width, {} of the slide's width.",
                            RULES.slide_size_fraction.bounds()
                        )),
                        "height_fraction": number_arg(&format!(
                            "Height, {} of the slide's height.",
                            RULES.slide_size_fraction.bounds()
                        )),
                        "title": text_arg("The slide's title."),
                        "bullets": array_arg(
                            &scalar_arg(),
                            &format!("The slide's bullets, at most {}.", RULES.bullets_max),
                        ),
                        "to": integer_arg("The slide it moves to."),
                    }),
                    "format_text needs one property beyond find.",
                ),
            }),
        ),
        "pdf_merge" => super::action_entry_schema(
            "pdf_merge",
            "Merge PDFs into one new file.",
            &["paths"],
            &json!({ "paths": paths_arg(), "metadata": metadata_entry() }),
        ),
        "pdf_split" => super::action_entry_schema(
            "pdf_split",
            "Split a PDF, one output file per page entry.",
            &["path", "pages"],
            &json!({ "path": path_arg(), "pages": pages_arg(true), "metadata": metadata_entry() }),
        ),
        "pdf_rotate" => super::action_entry_schema(
            "pdf_rotate",
            "Add a rotation to a PDF's pages.",
            &["path", "degrees"],
            &json!({ "path": path_arg(), "degrees": degrees_arg(), "pages": pages_arg(false),
                     "metadata": metadata_entry() }),
        ),
        "pdf_crop" => super::action_entry_schema(
            "pdf_crop",
            "Crop a PDF page's visible area.",
            &["path", "area"],
            &json!({ "path": path_arg(), "area": page_area_arg(), "pages": pages_arg(false),
                     "metadata": metadata_entry() }),
        ),
        "pdf_resize" => super::action_entry_schema(
            "pdf_resize",
            "Resize a PDF page, scaling its content to fit.",
            &["path", "width", "height"],
            &json!({
                "path": path_arg(),
                "width": number_arg(&format!(
                    "Page width, {} points.",
                    RULES.dimension_points.bounds()
                )),
                "height": number_arg(&format!(
                    "Page height, {} points.",
                    RULES.dimension_points.bounds()
                )),
                "pages": pages_arg(false),
                "metadata": metadata_entry(),
            }),
        ),
        "pdf_text" => super::action_entry_schema(
            "pdf_text",
            "Draw text on a PDF's pages, as page content rather than an annotation.",
            &["path", "text"],
            &json!({
                "path": path_arg(),
                "text": text_arg("The text to draw."),
                "pages": pages_arg(false),
                "x": point_arg("X position on the page as it reads, from its left edge"),
                "y": point_arg("Y position on the page as it reads, from its bottom edge"),
                "size": number_arg(&format!(
                    "Font size, {} points.",
                    RULES.dimension_points.bounds()
                )),
                "color": color_arg("Text colour"),
                "stamp": bool_arg("Draw a box around the text."),
                "opacity": number_arg(&format!(
                    "Opacity of the drawn text and its stamp box, {}; unstated draws them solid.",
                    RULES.pdf_opacity.bounds()
                )),
                "rotate": number_arg(&format!(
                    "Rotation in degrees, within ±{}.",
                    RULES.pdf_point_abs_max
                )),
                "metadata": metadata_entry(),
            }),
        ),
        "pdf_image" => super::action_entry_schema(
            "pdf_image",
            "Place a PNG or JPEG on a PDF's pages, as page content rather than an annotation.",
            &["path", "image"],
            &json!({
                "path": path_arg(),
                "image": pdf_image_arg(),
                "pages": pages_arg(false),
                "x": point_arg("X position on the page as it reads, from its left edge"),
                "y": point_arg("Y position on the page as it reads, from its bottom edge"),
                "width": placed_size_arg("Placed width"),
                "height": placed_size_arg("Placed height"),
                "metadata": metadata_entry(),
            }),
        ),
        "pdf_form_fill" => super::action_entry_schema(
            "pdf_form_fill",
            "Fill a PDF's form fields into a copy.",
            &["path", "values"],
            &json!({
                "path": path_arg(),
                "values": values_arg("form field"),
                "flatten": bool_arg("Bake the fields into the page content and remove them."),
                "metadata": metadata_entry(),
            }),
        ),
        other => unreachable!("the schema lists exactly the dispatched actions: {other}"),
    }
}

/// A PDF position in points, bounded by the shared rules.
fn point_arg(what: &str) -> Value {
    number_arg(&format!(
        "{what} in points, within ±{}.",
        RULES.pdf_point_abs_max
    ))
}

fn degrees_arg() -> Value {
    integer_arg(&format!(
        "A multiple of {}, not a whole turn.",
        RULES.degrees_step
    ))
}

/// `area`: the fraction of what a page currently shows a `pdf_crop` keeps.
fn page_area_arg() -> Value {
    let side = |what: &str| {
        number_arg(&format!(
            "{what}, as a fraction of the page ({}).",
            RULES.pdf_page_fraction.bounds()
        ))
    };
    json!({
        "type": "object",
        "additionalProperties": false,
        "required": ["x", "y", "width", "height"],
        "properties": {
            "x": side("The left edge"),
            "y": side("The top edge"),
            "width": side("The width"),
            "height": side("The height"),
        },
        "description": "The area to keep, in fractions of the page's current visible area, \
                        measured from the displayed top-left and reaching down and right.",
    })
}

impl DocumentTool {
    /// The one dispatch both faces go through: `execute` renders it, and
    /// [`Tool::execute_answer`] hands it over with the partiality flag.
    async fn dispatch(&self, ws: &Workspace, args: Value) -> Result<super::ToolAnswer> {
        let args = normalize_call(&args)?;
        let action = super::get_str(&args, "action")?;
        // Only a real action is checked against its schema entry; an unknown one keeps
        // its own refusal below.
        if ACTIONS.contains(&action) {
            require_declared_arguments(action, &args)?;
        }
        let output = super::output_directory(ws, GENERATED_DIR);
        match action {
            "create" => self.create(ws, &args, &output).await,
            "fill_template" => self.fill_template(ws, &args, &output).await,
            "docx_edit" => {
                self.edit(ws, &args, &output, crate::ooxml::Family::Docx)
                    .await
            }
            "xlsx_edit" => {
                self.edit(ws, &args, &output, crate::ooxml::Family::Xlsx)
                    .await
            }
            "pptx_edit" => {
                self.edit(ws, &args, &output, crate::ooxml::Family::Pptx)
                    .await
            }
            "pdf_merge" => self.pdf_merge(ws, &args, &output).await,
            "pdf_split" => self.pdf_split(ws, &args, &output).await,
            "pdf_rotate" => self.pdf_rotate(ws, &args, &output).await,
            "pdf_crop" => self.pdf_crop(ws, &args, &output).await,
            "pdf_resize" => self.pdf_resize(ws, &args, &output).await,
            "pdf_text" => self.pdf_text(ws, &args, &output).await,
            "pdf_image" => self.pdf_image(ws, &args, &output).await,
            "pdf_form_fill" => self.pdf_form_fill(ws, &args, &output).await,
            other => anyhow::bail!(
                "usage: unknown action \"{other}\" — hint: use {}",
                ACTIONS.join(", ")
            ),
        }
    }

    /// `create` — a fresh document from content blocks or sheets.
    async fn create(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let format = super::get_str(args, "format")?;
        if !SUPPORTED_FORMATS.contains(&format) {
            anyhow::bail!(
                "usage: unknown format \"{format}\" — hint: use {}",
                SUPPORTED_FORMATS.join(", ")
            );
        }
        let metadata = opt_metadata(args)?;
        if metadata.is_some() && format != "pdf" {
            anyhow::bail!(
                "usage: a {format} file carries no PDF description — hint: pass \"metadata\" only \
                 for format \"pdf\""
            );
        }
        let mut request = json!({ "op": "create", "format": format });
        set_metadata(&mut request, metadata);
        // A running header or footer is a document's own — a presentation, a workbook and
        // this tool's PDF have none, so one named for them is refused rather than dropped.
        for (key, what) in [
            ("header", "a running header"),
            ("footer", "a running footer"),
        ] {
            let Some(text) = super::get_opt_str_strict(args, key)? else {
                continue;
            };
            if format != "docx" {
                anyhow::bail!(
                    "usage: \"{key}\" is {what}, and only a .docx has one — hint: leave it out \
                     for format \"{format}\""
                );
            }
            // A blank one is a header the reader never sees: refused, as a blank link text
            // and a blank footnote are.
            require_visible(
                &format!("\"{key}\""),
                text,
                &format!("give its text, or leave \"{key}\" out"),
            )?;
            request[key] = json!(text);
        }
        // A slide size is a presentation's own; the page of a document or a PDF is not
        // choosable, so a `size` named for one is refused rather than dropped.
        let size = super::get_opt_str_strict(args, "size")?;
        if let Some(size) = size {
            if format != "pptx" {
                anyhow::bail!(
                    "usage: \"size\" is a slide size, and only format \"pptx\" has slides — \
                     hint: pass \"size\" only for format \"pptx\""
                );
            }
            let sizes = pptx_size_words();
            if !sizes.contains(&size) {
                anyhow::bail!(
                    "usage: unknown slide size \"{size}\" — hint: use {}",
                    listed(&sizes)
                );
            }
            request["size"] = json!(size);
        }
        if format == "xlsx" {
            // Content blocks passed beside a workbook's `sheets` would be dropped in silence,
            // so they are refused.
            if args.get("content").is_some_and(|value| !value.is_null()) {
                anyhow::bail!(
                    "usage: \"content\" is not used for format \"xlsx\" — hint: pass \"sheets\" to \
                     write a spreadsheet"
                );
            }
            request["sheets"] = resolve_sheets(args)?;
        } else {
            if args.get("sheets").is_some_and(|value| !value.is_null()) {
                anyhow::bail!(
                    "usage: \"sheets\" is not used for format \"{format}\" — hint: pass \"content\" \
                     to write a {format} document"
                );
            }
            request["content"] = resolve_content(ws, args, format, self.access).await?;
        }
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &format!("{}_{}", default_base(format), crate::util::unix_millis()),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), format).await?;
        request["output"] = json!(outputs[0].to_string_lossy());
        self.deliver(request, &outputs, "created").await
    }

    /// `fill_template` — a copy of the user's own sample with `{name}` placeholders replaced.
    async fn fill_template(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (sample, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let values = require_values(args, "placeholder")?;
        require_scalar_values(&values)?;
        // The kit's `format` is the sample's FAMILY — a workbook has its own cell-wise
        // filler, a document and a presentation go through the template library — and the
        // sample's own bytes must hold it: another family, an old binary or an encrypted
        // package is refused here, before a runtime is spawned.
        let family = require_sample_family(&sample).await?;
        let extension = copy_extension(&sample, family);
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&sample, "filled"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), &extension).await?;
        let request = json!({
            "op": "fill_template",
            // The kit's own field name for the sample it fills.
            "template": sample.to_string_lossy(),
            "format": family.name(),
            "values": values,
            "output": outputs[0].to_string_lossy(),
        });
        self.deliver(request, &outputs, "filled the sample into")
            .await
    }

    /// `docx_edit`/`xlsx_edit`/`pptx_edit` — a surgical edit of one family's package
    /// into a new file.
    async fn edit(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
        family: crate::ooxml::Family,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        // The bytes decide what the file is, never its name: another family, a PDF, a
        // container that is no document and an old binary `.doc`/`.xls`/`.ppt` are each
        // refused naming what they are, and a genuinely encrypted package is the password verdict.
        require_edit_family(&input, family).await?;
        let mut edits = validate_edits(family, args)?;
        // Every family's `add_image` resolves its picture path before the kit sees it; only
        // a presentation also needs the diagram text a refusal may name, read under the
        // conversion bound — a notes edit or a slide reshape reads none.
        let mut diagram_text = HashMap::new();
        resolve_edit_images(ws, &mut edits, self.access).await?;
        if family == crate::ooxml::Family::Pptx && edits_search_slide_text(&edits) {
            diagram_text = crate::document::read_pptx_diagram_text(&input).await;
        }
        let extension = copy_extension(&input, family);
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "edited"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), &extension).await?;
        let mut request = json!({
            "op": format!("{}_edit", family.name()),
            "input": input.to_string_lossy(),
            "edits": edits,
            "output": outputs[0].to_string_lossy(),
        });
        // A deck showing no diagram text sends no field: there is nothing a refusal could name.
        if !diagram_text.is_empty() {
            request["diagram_text"] = json!(diagram_text);
        }
        self.deliver(request, &outputs, "edited").await
    }

    /// `pdf_merge` — every input's pages, in order, in one file.
    async fn pdf_merge(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let paths = super::get_str_array(args, "paths")?;
        let metadata = opt_metadata(args)?;
        if paths.len() < 2 {
            anyhow::bail!(
                "usage: `paths` needs at least 2 PDFs to merge, got {} — hint: pass two or \
                 more PDF paths",
                paths.len()
            );
        }
        if paths.len() > MAX_MERGE_INPUTS {
            anyhow::bail!(
                "usage: `paths` holds {} files, more than one merge takes (limit \
                 {MAX_MERGE_INPUTS}) — hint: merge them in batches",
                paths.len()
            );
        }
        let mut inputs = Vec::with_capacity(paths.len());
        // The kit decodes every input at once, so the size of the whole call is bounded.
        let mut total = 0u64;
        for path in &paths {
            let (resolved, size) = resolve_input(ws, path, self.access).await?;
            total += size;
            inputs.push(resolved);
        }
        if total > MAX_MERGE_BYTES {
            anyhow::bail!(
                "usage: `paths` totals {} MB, more than one merge takes (limit {} MB) — hint: \
                 merge them in batches",
                megabytes(total),
                megabytes(MAX_MERGE_BYTES)
            );
        }
        // Every argument is read before anything is reserved, and the content
        // verdict comes with them: a merge of anything but PDFs is refused here,
        // naming what each input really holds.
        for input in &inputs {
            require_pdf(input).await?;
        }
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&inputs[0], "merged"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        let mut request = json!({
            "op": "pdf_merge",
            "inputs": path_strings(&inputs),
            "output": outputs[0].to_string_lossy(),
        });
        set_metadata(&mut request, metadata);
        self.deliver(request, &outputs, "merged the files into")
            .await
    }

    /// `pdf_split` — one file per page selection.
    async fn pdf_split(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let groups = split_groups(args)?;
        let metadata = opt_metadata(args)?;
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            crate::util::name_stem(&file_name_of(&input)),
        );
        let bases: Vec<String> = (0..groups.len())
            .map(|index| format!("{base}_part{}", index + 1))
            .collect();
        let outputs = reserve(output, &bases, "pdf").await?;
        let mut request = json!({
            "op": "pdf_split",
            "input": input.to_string_lossy(),
            "groups": groups,
            "outputs": path_strings(&outputs),
        });
        set_metadata(&mut request, metadata);
        self.deliver(request, &outputs, "split the file into").await
    }

    async fn pdf_rotate(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let degrees = match super::get_opt_i64(args, "degrees")? {
            // Reduced here so the request carries a bounded value: a rotation IS its angle
            // modulo 360, and a caller can send one as large as an i64 allows.
            Some(degrees) if degrees % RULES.degrees_step == 0 && degrees.rem_euclid(360) != 0 => {
                degrees.rem_euclid(360)
            }
            Some(degrees) if degrees % RULES.degrees_step == 0 => anyhow::bail!(
                "usage: {degrees} degrees would leave the pages as they are — hint: use a \
                 multiple of {} below a full turn",
                RULES.degrees_step
            ),
            Some(_) => anyhow::bail!(
                "usage: \"degrees\" must be a multiple of {}",
                RULES.degrees_step
            ),
            None => anyhow::bail!(
                "usage: missing required argument \"degrees\" — hint: pass a multiple of {} below a \
                 full turn",
                RULES.degrees_step
            ),
        };
        // Every argument is checked before anything is reserved: a call the tool
        // refuses must not leave an empty output file behind.
        let mut request = json!({
            "op": "pdf_rotate",
            "input": input.to_string_lossy(),
            "degrees": degrees,
        });
        request["pages"] = opt_pages(args)?.kit_value();
        set_metadata(&mut request, opt_metadata(args)?);
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "rotated"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        request["output"] = json!(outputs[0].to_string_lossy());
        self.deliver(request, &outputs, "rotated").await
    }

    async fn pdf_crop(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let area = require_page_area(args)?;
        let mut request = json!({
            "op": "pdf_crop",
            "input": input.to_string_lossy(),
            "area": area,
        });
        request["pages"] = opt_pages(args)?.kit_value();
        set_metadata(&mut request, opt_metadata(args)?);
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "cropped"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        request["output"] = json!(outputs[0].to_string_lossy());
        self.deliver(request, &outputs, "cropped").await
    }

    async fn pdf_resize(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let mut request = json!({
            "op": "pdf_resize",
            "input": input.to_string_lossy(),
        });
        set_positive_number(&mut request, args, "width", &RULES.dimension_points)?;
        set_positive_number(&mut request, args, "height", &RULES.dimension_points)?;
        // A side left out is not "keep the page's own": a resize always names the page it makes.
        if let Some(missing) = ["width", "height"]
            .into_iter()
            .find(|side| request.get(*side).is_none())
        {
            anyhow::bail!(
                "usage: missing required argument \"{missing}\" — a resize names both sides — \
                 hint: give both \"width\" and \"height\" in points"
            );
        }
        request["pages"] = opt_pages(args)?.kit_value();
        set_metadata(&mut request, opt_metadata(args)?);
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "resized"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        request["output"] = json!(outputs[0].to_string_lossy());
        self.deliver(request, &outputs, "resized").await
    }

    /// `pdf_text` — draw text (optionally stamped and rotated) on the pages.
    async fn pdf_text(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let text = super::get_str(args, "text")?;
        let mut request = json!({
            "op": "pdf_text",
            "input": input.to_string_lossy(),
            "text": text,
        });
        request["pages"] = opt_pages(args)?.kit_value();
        set_number(&mut request, args, "x")?;
        set_number(&mut request, args, "y")?;
        set_positive_number(&mut request, args, "size", &RULES.dimension_points)?;
        set_bounded_number(
            &mut request,
            args,
            "opacity",
            &RULES.pdf_opacity,
            "give a fraction just above zero",
        )?;
        set_number(&mut request, args, "rotate")?;
        if let Some(color) = super::get_opt_str_strict(args, "color")? {
            // A pdf argument is named quoted, as the neighbouring refusals do.
            require_hex_color("\"color\"", color)?;
            request["color"] = json!(color);
        }
        if let Some(stamp) = super::get_opt_bool(args, "stamp")? {
            request["stamp"] = json!(stamp);
        }
        set_metadata(&mut request, opt_metadata(args)?);
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "text"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        request["output"] = json!(outputs[0].to_string_lossy());
        self.deliver(request, &outputs, "stamped text into").await
    }

    /// `pdf_image` — place a PNG/JPEG on the pages.
    async fn pdf_image(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let (image, _) = resolve_input(ws, super::get_str(args, "image")?, self.access).await?;
        ensure_picture(&image, &pdf_pictures())?;
        let mut request = json!({
            "op": "pdf_image",
            "input": input.to_string_lossy(),
            "image": image.to_string_lossy(),
        });
        request["pages"] = opt_pages(args)?.kit_value();
        set_number(&mut request, args, "x")?;
        set_number(&mut request, args, "y")?;
        set_positive_number(&mut request, args, "width", &RULES.dimension_points)?;
        set_positive_number(&mut request, args, "height", &RULES.dimension_points)?;
        set_metadata(&mut request, opt_metadata(args)?);
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "image"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        request["output"] = json!(outputs[0].to_string_lossy());
        self.deliver(request, &outputs, "inserted the image into")
            .await
    }

    /// `pdf_form_fill` — fill a PDF's AcroForm fields.
    async fn pdf_form_fill(
        &self,
        ws: &Workspace,
        args: &Value,
        output: &Path,
    ) -> Result<super::ToolAnswer> {
        let (input, _) = resolve_input(ws, super::get_str(args, "path")?, self.access).await?;
        let values = require_values(args, "form field")?;
        require_scalar_values(&values)?;
        // Every argument is read before anything is reserved: a call the tool
        // refuses must not leave an empty output file behind.
        let flatten = super::get_bool(args, "flatten", false)?;
        let metadata = opt_metadata(args)?;
        require_pdf(&input).await?;
        let base = sanitize_base(
            super::get_opt_str_strict(args, "file_name")?,
            &input_base(&input, "filled"),
        );
        let outputs = reserve(output, std::slice::from_ref(&base), "pdf").await?;
        let mut request = json!({
            "op": "pdf_form_fill",
            "input": input.to_string_lossy(),
            "values": values,
            "flatten": flatten,
            "output": outputs[0].to_string_lossy(),
        });
        set_metadata(&mut request, metadata);
        self.deliver(request, &outputs, "filled the form into")
            .await
    }

    /// Run one prepared operation and turn its result into the reply: verify every
    /// reserved output exists, describe it and list its `[FILE:…]` markers; a failed run
    /// removes the reservations.
    async fn deliver(
        &self,
        request: Value,
        outputs: &[PathBuf],
        prefix: &str,
    ) -> Result<super::ToolAnswer> {
        // The runtime's absence and a failing probe are mahbot-side faults `probe` reports
        // with that token, so a broken runtime never looks like a broken request. It runs
        // once the call's arguments are checked and its outputs reserved.
        if let Err(e) = docgen::probe().await {
            remove_files(outputs).await;
            return Err(e);
        }
        let outcome = match docgen::run(request).await {
            Ok(outcome) => outcome,
            Err(e) => {
                remove_files(outputs).await;
                return Err(e);
            }
        };
        let mut sizes = Vec::with_capacity(outputs.len());
        for path in outputs {
            // The kit echoes the paths it wrote; a reservation it did not report back is a
            // kit that wrote somewhere else.
            if !outcome
                .outputs
                .iter()
                .any(|reported| reported.as_path() == path.as_path())
            {
                remove_files(outputs).await;
                return Err(super::internal_fault(&format!(
                    "the document kit did not report writing {}",
                    path.display()
                )));
            }
            match tokio::fs::metadata(path).await {
                Ok(meta) if meta.len() > 0 => sizes.push(meta.len()),
                _ => {
                    remove_files(outputs).await;
                    return Err(super::internal_fault(&format!(
                        "the document kit reported success but wrote nothing to {}",
                        path.display()
                    )));
                }
            }
        }

        let names: Vec<String> = outputs.iter().map(|path| file_name_of(path)).collect();
        let mut text = describe(prefix, &names, &sizes);
        if !outcome.missing.is_empty() {
            text = super::with_note(
                &text,
                &format!(
                    "[no values for these placeholders, left unchanged: {}]",
                    outcome.missing.join(", ")
                ),
            );
        }
        // The embedded font draws an unknown character as a blank box, so the answer says
        // what the kit could not draw is missing from the file.
        if !outcome.unsupported.is_empty() {
            let listed = outcome
                .unsupported
                .iter()
                .take(UNSUPPORTED_NOTE_MAX)
                .map(|character| format!("'{}'", character.escape_debug()))
                .collect::<Vec<_>>()
                .join(" ");
            let more = outcome
                .unsupported
                .len()
                .saturating_sub(UNSUPPORTED_NOTE_MAX);
            let characters = if more == 0 {
                listed
            } else {
                format!("{listed} and {more} more")
            };
            text = super::with_note(
                &text,
                &format!("[missing from the file, the embedded font cannot draw: {characters}]"),
            );
        }
        // Only a template fill can say this, and the kit's own count is what makes it a
        // fact: a copy cannot be compared with its sample, the kit re-serialising parts. The
        // count covers only the parts the filler rewrites — a chart label, a comment or a
        // footnote is outside it.
        if outcome.placeholders == Some(0) {
            text = super::with_note(
                &text,
                "[no {name} placeholders in the parts this operation rewrites — nothing was \
                 substituted; the copy is unchanged]",
            );
        }
        // Each note is the kit's own already-bracketed caveat about the input or about how
        // a part was carried over, appended verbatim; whether work is MISSING is the kit's
        // `lossy` flag, never this text.
        for note in &outcome.notes {
            text = super::with_note(&text, note);
        }
        for path in outputs {
            text.push('\n');
            text.push_str(&self.format_media_result(path));
        }
        // `missing`, `unsupported`, `placeholders == Some(0)` and `outcome.lossy` are what
        // make part of the answer a shortfall.
        let partial = outcome.lossy
            || !outcome.missing.is_empty()
            || !outcome.unsupported.is_empty()
            || outcome.placeholders == Some(0);
        Ok(if partial {
            super::ToolAnswer::partial(text)
        } else {
            super::ToolAnswer::done(text)
        })
    }
}

/// Resolve a model-supplied input path under `access`, requiring a regular file the kit
/// can load whole; its length comes back too, so no caller stats it twice.
async fn resolve_input(ws: &Workspace, path: &str, access: PathAccess) -> Result<(PathBuf, u64)> {
    let resolved = super::path::resolve_read_target(ws.as_path(), path, access).await?;
    let meta = tokio::fs::metadata(&resolved)
        .await
        .with_context(|| format!("cannot read {}", resolved.display()))?;
    if !meta.is_file() {
        anyhow::bail!(
            "usage: {} is not a file — hint: pass the path of a file",
            resolved.display()
        );
    }
    // The product's own conversion limit, not a transfer limit: the kit loads an input
    // whole, and an oversized one would end as a killed run blamed on the product.
    if meta.len() > crate::util::FILE_MAX_BYTES {
        anyhow::bail!(
            "usage: {} is over the {} MB limit for a document operation, got {} — hint: shrink \
             the file and retry",
            resolved.display(),
            megabytes(crate::util::FILE_MAX_BYTES),
            super::listing::human_readable_size(meta.len())
        );
    }
    Ok((resolved, meta.len()))
}

/// The leading bytes of `path`: the five-byte PDF magic [`real_family_of`] settles a PDF
/// with, without reading a whole file.
async fn head_of(path: &Path) -> Result<[u8; 8]> {
    use tokio::io::AsyncReadExt as _;
    let mut magic = [0u8; 8];
    let mut file = tokio::fs::File::open(path)
        .await
        .with_context(|| format!("cannot read {}", path.display()))?;
    // A file shorter than the magic reads what it has; the bytes it could not read stay zero.
    let _ = file.read(&mut magic).await;
    Ok(magic)
}

/// What the file really is, from its own bytes — the head settles a PDF or bytes that are
/// no container, so a PDF is never read whole; a container goes to [`container_family`].
async fn real_family_of(path: &Path) -> Result<crate::document::RealFamily> {
    let head = head_of(path).await?;
    if !crate::document::is_zip_container(&head) && !head.starts_with(crate::document::CFB_MAGIC) {
        return Ok(crate::document::real_family(&head));
    }
    let owned = path.to_owned();
    // The whole-file read and the legacy parse run on a blocking thread under the document
    // bound: a third-party reader's panic must cost the call, not the caller's turn.
    match crate::document::run_document_parse(move || container_family(&owned)).await {
        Some(checked) => checked,
        None => anyhow::bail!(
            "usage: {} could not be read — hint: retry it, or check the file is intact",
            file_name_of(path)
        ),
    }
}

/// What a container really holds: the whole-file read already checked by
/// [`resolve_input`], then the family parse that has to see past the head.
fn container_family(path: &Path) -> Result<crate::document::RealFamily> {
    use crate::document::RealFamily;
    let bytes = std::fs::read(path).with_context(|| format!("cannot read {}", path.display()))?;
    let real = crate::document::real_family(&bytes);
    // A CFB container whose directory names no Office document leaves the name as the only
    // evidence, answered as the reading path answers it (`crate::document::classify`).
    let real = match real {
        RealFamily::Other if bytes.starts_with(crate::document::CFB_MAGIC) => {
            crate::legacy::named_family(path).map_or(real, crate::legacy::Family::real)
        }
        other => other,
    };
    // A legacy `.doc`/`.xls`/`.ppt` can be genuinely encrypted, which its container alone
    // does not say: only the family's own reader can tell a password from corruption, so an
    // encrypted legacy family gets the password verdict here.
    if let Some(RealFormat::Legacy(family)) = RealFormat::of(real)
        && crate::legacy::is_encrypted(&bytes, family)
    {
        return Ok(RealFamily::Encrypted);
    }
    Ok(real)
}

/// The verdict a genuinely encrypted input gets whatever its name says; `wanted` lets the
/// refusal name what a password-free copy is for in the caller's own voice.
fn password_refusal(path: &Path, wanted: Wanted) -> anyhow::Error {
    anyhow::anyhow!(
        "usage: {} is password-protected — hint: remove the protection, save an unprotected copy \
         and {}",
        file_name_of(path),
        wanted.unprotected()
    )
}

/// The middle clause of a refusal: the file's real format when its bytes name one;
/// otherwise a package name means unreadable, and any other name means no document.
fn real_clause(real: Option<RealFormat>, path: &Path) -> String {
    if let Some(format) = real {
        return format!("which is really {}", format.phrase());
    }
    crate::ooxml::family_of(path).map_or_else(
        || "which is not a Word, Excel, PowerPoint or PDF document".to_owned(),
        |family| format!("which is {}", crate::ooxml::corrupt_reason(family)),
    )
}

/// What a refusal names a file as: the one mapping from
/// [`crate::document::RealFamily`]'s variants to the three kinds every refusal sentence is
/// written against.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RealFormat {
    Pdf,
    Package(crate::ooxml::Family),
    Legacy(crate::legacy::Family),
}

impl RealFormat {
    /// The format `real` is, or `None` for a file that names none.
    fn of(real: crate::document::RealFamily) -> Option<Self> {
        use crate::document::RealFamily;
        match real {
            RealFamily::Pdf => Some(Self::Pdf),
            RealFamily::Docx => Some(Self::Package(crate::ooxml::Family::Docx)),
            RealFamily::Xlsx => Some(Self::Package(crate::ooxml::Family::Xlsx)),
            RealFamily::Pptx => Some(Self::Package(crate::ooxml::Family::Pptx)),
            RealFamily::LegacyDoc => Some(Self::Legacy(crate::legacy::Family::Doc)),
            RealFamily::LegacyXls => Some(Self::Legacy(crate::legacy::Family::Xls)),
            RealFamily::LegacyPpt => Some(Self::Legacy(crate::legacy::Family::Ppt)),
            RealFamily::Encrypted | RealFamily::Other => None,
        }
    }

    /// What it is, as a refusal names it.
    fn phrase(self) -> &'static str {
        match self {
            Self::Pdf => "a PDF",
            Self::Package(crate::ooxml::Family::Docx) => "a .docx package",
            Self::Package(crate::ooxml::Family::Xlsx) => "an .xlsx package",
            Self::Package(crate::ooxml::Family::Pptx) => "a .pptx package",
            Self::Legacy(crate::legacy::Family::Doc) => "an old .doc file",
            Self::Legacy(crate::legacy::Family::Xls) => "an old .xls file",
            Self::Legacy(crate::legacy::Family::Ppt) => "an old .ppt file",
        }
    }
}

/// What the caller's action can do with a file of its own family: which door to point
/// the caller at, and what the old formats are owed.
#[derive(Clone, Copy)]
enum Wanted {
    /// One of the three editable packages: a caller that works on files, like `Self::Pdf`.
    Package,
    Sample,
    /// A PDF, for the actions that work on one; a real PDF is never refused for it.
    Pdf,
}

impl Wanted {
    const fn verb(self) -> &'static str {
        match self {
            Self::Package => "edited",
            Self::Sample => "filled",
            Self::Pdf => "written",
        }
    }

    /// What the old formats' sentence tells the caller to convert the file to.
    const fn convert(self) -> &'static str {
        match self {
            Self::Pdf => "save it as a PDF first",
            Self::Package | Self::Sample => "save it as one of the OOXML families first",
        }
    }

    /// What a wrong-family PDF is owed: a caller that fills cannot fill pages, so it is
    /// pointed at the one action that fills a PDF's own fields.
    const fn pdf(self) -> &'static str {
        match self {
            Self::Sample => "a PDF's form fields are filled with pdf_form_fill",
            Self::Package | Self::Pdf => {
                "a PDF's own actions are pdf_merge, pdf_split, pdf_rotate, pdf_crop, pdf_resize, \
                 pdf_text, pdf_image and pdf_form_fill"
            }
        }
    }

    /// What the password refusal tells the caller to save a password-free copy as, in this
    /// action's own voice.
    const fn unprotected(self) -> &'static str {
        match self {
            Self::Package => "edit that",
            Self::Sample => "fill that",
            Self::Pdf => "convert it to a PDF",
        }
    }
}

/// The advice a wrong-family refusal ends with: another OOXML package points at the action
/// that edits it, an old-format file keeps the sentence the old formats are owed, and a file
/// that names no format is passed as what the action takes.
fn wrong_family_advice(real: Option<RealFormat>, takes: &str, wanted: Wanted) -> String {
    match real {
        Some(RealFormat::Package(family)) => match wanted {
            Wanted::Package => format!("use {}_edit to edit it", family.name()),
            // A package a fill can fill is filled, so the package it is refused is one whose
            // name disagrees with its bytes.
            Wanted::Sample => "rename it to match its content".to_owned(),
            Wanted::Pdf => "convert it to a PDF first".to_owned(),
        },
        Some(RealFormat::Legacy(_)) => old_format_advice(wanted),
        Some(RealFormat::Pdf) => wanted.pdf().to_owned(),
        None => format!("pass {takes}"),
    }
}

/// The sentence the old binary formats are owed — read, but never written — in the
/// caller's own verb.
fn old_format_advice(wanted: Wanted) -> String {
    format!(
        "an old .doc/.xls/.ppt file is read but never {}; {}",
        wanted.verb(),
        wanted.convert()
    )
}

/// The refusal an input of the wrong family is owed: `what` the action takes, `takes` the
/// short form a hint carries, `real` what the bytes hold and `wanted` what the action would
/// have done. The verdict follows the bytes; the name is consulted only for bytes that are
/// no document.
fn wrong_family(
    what: &str,
    takes: &str,
    path: &Path,
    real: crate::document::RealFamily,
    wanted: Wanted,
) -> anyhow::Error {
    use crate::document::RealFamily;
    // The password verdict is owed whatever the action asked: every sentence below names a
    // format, and an encrypted file's own is not one the caller can act on.
    if real == RealFamily::Encrypted {
        return password_refusal(path, wanted);
    }
    let format = RealFormat::of(real);
    anyhow::anyhow!(
        "usage: {what}, got {}, {} — hint: {}",
        file_name_of(path),
        real_clause(format, path),
        wrong_family_advice(format, takes, wanted)
    )
}

/// Require an edit input to be the package family its action edits, from its bytes: another
/// family, a PDF, no document and an old binary `.doc`/`.xls`/`.ppt` are each named for what
/// they are, and an encrypted package gets the password verdict.
async fn require_edit_family(path: &Path, family: crate::ooxml::Family) -> Result<()> {
    let real = real_family_of(path).await?;
    if RealFormat::of(real) == Some(RealFormat::Package(family)) {
        return Ok(());
    }
    let accepted = match family {
        crate::ooxml::Family::Docx => "a .docx/.docm file",
        crate::ooxml::Family::Xlsx => "a .xlsx/.xlsm file",
        crate::ooxml::Family::Pptx => "a .pptx/.pptm file",
    };
    Err(wrong_family(
        &format!("{}_edit edits only {accepted}", family.name()),
        accepted,
        path,
        real,
        Wanted::Package,
    ))
}

/// The family a fill treats `sample` as: the family its NAME claims — that picks the filler,
/// the copy's extension and the file the copy is compared against — which the bytes must be.
/// A package one rename away is refused with the name it needs.
async fn require_sample_family(sample: &Path) -> Result<crate::ooxml::Family> {
    let real = real_family_of(sample).await?;
    let format = RealFormat::of(real);
    if let Some(RealFormat::Package(family)) = format
        && crate::ooxml::family_of(sample) == Some(family)
    {
        return Ok(family);
    }
    let accepted = "a .docx/.docm, .pptx/.pptm or .xlsx/.xlsm sample";
    let what = if matches!(format, Some(RealFormat::Package(_))) {
        "the sample's name must be the family its bytes are".to_owned()
    } else {
        format!("a sample must be {accepted}")
    };
    Err(wrong_family(&what, accepted, sample, real, Wanted::Sample))
}

/// Require a `pdf_*` input to really be a PDF, from its own bytes: a valid PDF under a
/// non-PDF name keeps working, and anything else is refused naming what it holds.
async fn require_pdf(path: &Path) -> Result<()> {
    let real = real_family_of(path).await?;
    if real == crate::document::RealFamily::Pdf {
        return Ok(());
    }
    Err(wrong_family(
        "the input must be a PDF",
        "a PDF",
        path,
        real,
        Wanted::Pdf,
    ))
}

/// Validate and normalize one family's `edits`, refusing every shape the kit would fail on
/// before a runtime is spawned; returns the array the request carries.
fn validate_edits(family: crate::ooxml::Family, args: &Value) -> Result<Value> {
    let names = edit_op_fields(family)
        .iter()
        .map(|(op, _)| *op)
        .collect::<Vec<_>>();
    let edits = match args.get("edits") {
        Some(Value::Array(edits)) if !edits.is_empty() => edits,
        Some(Value::Array(_)) => {
            anyhow::bail!("usage: \"edits\" is empty — hint: name at least one edit")
        }
        Some(v) => return Err(super::wrong_type("edits", "an array", v)),
        None => anyhow::bail!(
            "usage: missing required argument \"edits\" — hint: pass a JSON array of edit objects, \
             e.g. [{{\"op\": \"replace_text\", \"find\": \"…\", \"replace\": \"…\"}}]"
        ),
    };
    if edits.len() > RULES.edits_max {
        anyhow::bail!(
            "usage: {} edits is more than one call takes (limit {}) — hint: split them across \
             calls",
            edits.len(),
            RULES.edits_max
        );
    }
    let mut out = Vec::with_capacity(edits.len());
    for (index, edit) in edits.iter().enumerate() {
        let at = format!("edits[{index}]");
        let Some(object) = edit.as_object() else {
            anyhow::bail!("usage: {at} must be an object — hint: give every edit an \"op\"");
        };
        let Some(op) = object.get("op").and_then(Value::as_str) else {
            anyhow::bail!("usage: {at} has no \"op\" — hint: use {}", names.join(", "));
        };
        if !names.contains(&op) {
            anyhow::bail!(
                "usage: unknown {} edit \"{op}\" — hint: use {}",
                family.name(),
                names.join(", ")
            );
        }
        out.push(validate_edit(family, edit, object, op, &at)?);
    }
    Ok(Value::Array(out))
}

/// Validate one edit: an xlsx `set_cell`'s formula is normalized to its text, every other
/// family's edit passes through, and a `null` field is dropped from all three.
fn validate_edit(
    family: crate::ooxml::Family,
    edit: &Value,
    object: &serde_json::Map<String, Value>,
    op: &str,
    at: &str,
) -> Result<Value> {
    require_taken_keys(
        object,
        at,
        &format!("{} \"{op}\"", family.name()),
        op_fields(family, op),
        &["op"],
    )?;
    let validated = match family {
        crate::ooxml::Family::Docx => {
            validate_docx_edit(object, op, at)?;
            edit.clone()
        }
        crate::ooxml::Family::Xlsx => validate_xlsx_edit(edit, object, op, at)?,
        crate::ooxml::Family::Pptx => {
            validate_pptx_edit(object, op, at)?;
            edit.clone()
        }
    };
    Ok(without_nulls(validated))
}

/// `edit` with its null-valued keys dropped: the boundary reads a `null` as absent, but the
/// kit tests only `!== undefined`, so a `format_text`'s `bold: null` would strip the run's own
/// bold. The drop reaches into object-valued fields' own keys; an array is left as it is.
/// Validation runs before the drop, so a `null` where a value is required is still refused.
fn without_nulls(edit: Value) -> Value {
    match edit {
        Value::Object(object) => Value::Object(
            object
                .into_iter()
                .filter(|(_, value)| !value.is_null())
                .map(|(key, value)| (key, without_nulls(value)))
                .collect(),
        ),
        other => other,
    }
}

/// One string field of an edit, bounded by the shared `edit_text_max`.
fn edit_string<'a>(
    object: &'a serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<Option<&'a str>> {
    match optional_string(object.get(key), at, key)? {
        Some(text) => {
            let length = text.chars().count();
            if length > RULES.edit_text_max {
                anyhow::bail!(
                    "usage: {at}.{key} must be at most {} characters, got {length} — hint: shorten \
                     the text",
                    RULES.edit_text_max
                );
            }
            Ok(Some(text))
        }
        None => Ok(None),
    }
}

/// Require an edit's string field to be present; an empty value is still a value, which is what
/// several ops accept.
fn edit_string_present<'a>(
    object: &'a serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<&'a str> {
    match edit_string(object, key, at)? {
        Some(text) => Ok(text),
        None => {
            anyhow::bail!("usage: {at} has no \"{key}\" — hint: give the edit its \"{key}\" text")
        }
    }
}

fn edit_string_non_empty<'a>(
    object: &'a serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<&'a str> {
    match edit_string(object, key, at)? {
        Some(text) if !text.is_empty() => Ok(text),
        _ => anyhow::bail!("usage: {at}.{key} must not be empty"),
    }
}

/// Require an optional string field, when present, to be a non-empty value.
fn require_optional_text(
    object: &serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<()> {
    match edit_string(object, key, at)? {
        Some("") => anyhow::bail!("usage: {at}.{key} must not be empty"),
        _ => Ok(()),
    }
}

/// One optional whole-number field of an edit; a negative, fractional or non-numeric value
/// is refused here.
fn edit_integer(
    object: &serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<Option<u64>> {
    match object.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(value) => value.as_u64().map(Some).ok_or_else(|| {
            super::wrong_type(&format!("{at}.{key}"), "a non-negative integer", value)
        }),
    }
}

/// One optional number field of an edit; a non-numeric or non-finite value is refused here.
fn edit_number(
    object: &serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<Option<f64>> {
    match object.get(key) {
        None | Some(Value::Null) => Ok(None),
        Some(value) => value
            .as_f64()
            .filter(|number| number.is_finite())
            .map(Some)
            .ok_or_else(|| super::wrong_type(&format!("{at}.{key}"), "a number", value)),
    }
}

/// The docx edit vocabulary: text ops address the joined text of a paragraph's runs in the body.
fn validate_docx_edit(object: &serde_json::Map<String, Value>, op: &str, at: &str) -> Result<()> {
    match op {
        "replace_text" => {
            edit_string_non_empty(object, "find", at)?;
            edit_string_present(object, "replace", at)?;
        }
        "insert_text" => {
            edit_string_non_empty(object, "find", at)?;
            edit_string_non_empty(object, "insert", at)?;
            require_position(object, at)?;
        }
        "remove_text" | "remove_paragraph" => {
            edit_string_non_empty(object, "find", at)?;
        }
        "format_text" => {
            edit_string_non_empty(object, "find", at)?;
            require_format(object, at)?;
        }
        "format_paragraph" => {
            edit_string_non_empty(object, "find", at)?;
            require_paragraph_format(object, at)?;
        }
        "add_paragraph" => {
            edit_string_present(object, "text", at)?;
            require_optional_text(object, "after", at)?;
        }
        "add_image" => {
            edit_string_non_empty(object, "after", at)?;
            edit_string_non_empty(object, "image", at)?;
            require_span_number(
                object,
                "width",
                &RULES.dimension_points,
                "a picture's width in points",
                at,
            )?;
            require_span_number(
                object,
                "height",
                &RULES.dimension_points,
                "a picture's height in points",
                at,
            )?;
        }
        "add_table" => {
            edit_string_non_empty(object, "after", at)?;
            require_table(object, at, Some(RULES.table_columns_max))?;
        }
        _ => unreachable!("the op was checked against the family's vocabulary"),
    }
    Ok(())
}

/// Require an `insert_text`'s optional `position` to be `after` or `before`.
fn require_position(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    match optional_string(object.get("position"), at, "position")? {
        None | Some("after" | "before") => Ok(()),
        Some(position) => anyhow::bail!(
            "usage: {at}.position must be \"after\" or \"before\", got \"{position}\""
        ),
    }
}

/// Require each named toggle, when present and not null, to be a boolean; returns whether any
/// was stated.
fn require_toggles(
    object: &serde_json::Map<String, Value>,
    keys: &[&str],
    at: &str,
) -> Result<bool> {
    let mut any = false;
    for key in keys {
        match object.get(*key) {
            None | Some(Value::Null) => {}
            Some(Value::Bool(_)) => any = true,
            Some(v) => return Err(super::wrong_type(&format!("{at}.{key}"), "a boolean", v)),
        }
    }
    Ok(any)
}

/// Require an optional numeric field to sit inside `span`; `what` names the number in a refusal.
fn require_span_number(
    object: &serde_json::Map<String, Value>,
    key: &str,
    span: &Span,
    what: &str,
    at: &str,
) -> Result<()> {
    match edit_number(object, key, at)? {
        Some(number) if span.contains(number) => Ok(()),
        Some(number) => anyhow::bail!(
            "usage: {at}.{key} must be {}, got {number} — hint: {what}",
            span.bounds()
        ),
        None => Ok(()),
    }
}

/// Require an optional numeric field to sit inside `span`, reporting whether it was stated —
/// the "at least one property" test's count, read the way [`edit_number`] reads one.
fn require_stated_number(
    object: &serde_json::Map<String, Value>,
    key: &str,
    span: &Span,
    what: &str,
    at: &str,
) -> Result<bool> {
    require_span_number(object, key, span, what, at)?;
    Ok(stated(object, key))
}

/// Require a `format_text` to name at least one property, each the shape the kit writes: a
/// toggle, a point size inside the shared bound, or a colour.
fn require_format(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let mut any = require_toggles(object, &["bold", "italic", "underline", "strike"], at)?;
    any |= require_stated_number(
        object,
        "size",
        &RULES.text_size_points,
        "give a size in points",
        at,
    )?;
    any |= require_color(object, at)?;
    if !any {
        anyhow::bail!(
            "usage: {at} (format_text) needs at least one of bold, italic, underline, strike, \
             size or color — hint: a boolean toggles bold, italic, underline or strike, size is \
             in points and color is {} hex digits",
            RULES.color_digits
        );
    }
    Ok(())
}

/// Require a `format_paragraph` to name at least one property: an alignment word, a style, an
/// indent, a spacing, a line height, or a list (a kind with an optional level, or `false`).
fn require_paragraph_format(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let indent = "give an indent in points";
    let spacing = "give spacing in points";
    let mut any = require_alignment(
        object,
        "align",
        &pair_words(&RULES.paragraph_alignments),
        at,
    )?;
    // Nothing here can check that a named style exists; the kit resolves it and refuses an
    // unknown one.
    any |= require_name(object, "style", RULES.paragraph_style_max, at)?;
    for (key, span, what) in [
        ("indent_left", &RULES.paragraph_indent_points, indent),
        ("indent_right", &RULES.paragraph_indent_points, indent),
        ("indent_first_line", &RULES.paragraph_indent_points, indent),
        ("spacing_before", &RULES.paragraph_spacing_points, spacing),
        ("spacing_after", &RULES.paragraph_spacing_points, spacing),
        (
            "line_spacing",
            &RULES.paragraph_line_points,
            "give a line height in points",
        ),
    ] {
        any |= require_stated_number(object, key, span, what, at)?;
    }
    any |= require_list(object, at)?;
    require_list_level(object, at)?;
    if !any {
        anyhow::bail!(
            "usage: {at} (format_paragraph) needs at least one of align, style, indent_left, \
             indent_right, indent_first_line, spacing_before, spacing_after, line_spacing or \
             list — hint: name the property the paragraph is to take"
        );
    }
    Ok(())
}

/// Require an optional name-shaped field (a style, a font, a number format) to be a non-empty
/// string of at most `max` characters; reports whether it was stated.
fn require_name(
    object: &serde_json::Map<String, Value>,
    key: &str,
    max: usize,
    at: &str,
) -> Result<bool> {
    match edit_string(object, key, at)? {
        None => Ok(false),
        Some("") => anyhow::bail!("usage: {at}.{key} must not be empty"),
        Some(name) if name.chars().count() <= max => Ok(true),
        Some(name) => anyhow::bail!(
            "usage: {at}.{key} must be at most {max} characters, got {}",
            name.chars().count()
        ),
    }
}

/// Require an optional `format_paragraph` `list`: a word the shared rules state, or `false`
/// taking it away; reports whether the field was stated, the `false` included.
fn require_list(object: &serde_json::Map<String, Value>, at: &str) -> Result<bool> {
    let kinds = pair_words(&RULES.paragraph_lists);
    match object.get("list") {
        None | Some(Value::Null) => Ok(false),
        Some(Value::Bool(false)) => Ok(true),
        Some(Value::String(kind)) if kinds.contains(&kind.as_str()) => Ok(true),
        Some(Value::String(kind)) => anyhow::bail!(
            "usage: {at}.list must be {}, or false to take the paragraph's list away, got \
             \"{kind}\"",
            listed(&kinds)
        ),
        Some(value) => Err(super::wrong_type(
            &format!("{at}.list"),
            "a list kind or false",
            value,
        )),
    }
}

/// Require an optional `format_paragraph` `level` to be inside the shared cap and to have a
/// list to belong to — a level beside no `list` names a depth there is none at.
fn require_list_level(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let Some(level) = edit_integer(object, "level", at)? else {
        return Ok(());
    };
    if !matches!(object.get("list"), Some(Value::String(_))) {
        anyhow::bail!(
            "usage: {at}.level needs a list to belong to — hint: name \"list\" as {} beside it",
            listed(&pair_words(&RULES.paragraph_lists))
        );
    }
    if level > u64::from(RULES.paragraph_level_max) {
        anyhow::bail!(
            "usage: {at}.level must be a whole number from 0 to {}, got {level}",
            RULES.paragraph_level_max
        );
    }
    Ok(())
}

/// A `format_cells`'s one target: a cell rectangle, a column's width or a row's height —
/// exclusive, so an edit naming two is refused rather than settled by precedence.
#[derive(Clone, Copy)]
enum FormatCellsTarget {
    Range,
    Column,
    Row,
}

impl FormatCellsTarget {
    fn key(self) -> &'static str {
        match self {
            Self::Range => "range",
            Self::Column => "column",
            Self::Row => "row",
        }
    }

    /// The formatting properties this target takes, and the keys an unknown one is refused against.
    fn attributes(self) -> &'static [&'static str] {
        match self {
            Self::Range => &[
                "font",
                "size",
                "bold",
                "italic",
                "underline",
                "strike",
                "color",
                "fill",
                "border",
                "align",
                "vertical",
                "wrap",
                "number_format",
            ],
            Self::Column => &["width_chars"],
            Self::Row => &["height_points"],
        }
    }

    /// Every key this target's edit takes: the sheet, the target itself and the properties
    /// it formats.
    fn keys(self) -> Vec<&'static str> {
        let mut keys = vec!["sheet", self.key()];
        keys.extend_from_slice(self.attributes());
        keys
    }
}

/// Whether an edit stated a field: a `null` is absent, as the whole boundary reads one.
fn stated(object: &serde_json::Map<String, Value>, key: &str) -> bool {
    !matches!(object.get(key), None | Some(Value::Null))
}

fn require_format_cells_target(
    object: &serde_json::Map<String, Value>,
    at: &str,
) -> Result<FormatCellsTarget> {
    let named = ["range", "column", "row"]
        .into_iter()
        .filter(|key| stated(object, key))
        .collect::<Vec<_>>();
    match named.as_slice() {
        [] => anyhow::bail!(
            "usage: {at} names no target — hint: name \"range\" (a cell or a range of cells), \
             \"column\" (a column's letters, for its width) or \"row\" (a 1-based row, for its \
             height)"
        ),
        ["range"] => Ok(FormatCellsTarget::Range),
        ["column"] => Ok(FormatCellsTarget::Column),
        ["row"] => Ok(FormatCellsTarget::Row),
        both => {
            let listed = both
                .iter()
                .map(|key| format!("\"{key}\""))
                .collect::<Vec<_>>()
                .join(" and ");
            anyhow::bail!(
                "usage: {at} names more than one target ({listed}) — hint: an edit formats one of \
                 \"range\", \"column\" or \"row\""
            )
        }
    }
}

/// The corners an A1 range names, inside the sheet's grid; `what` names the field in a refusal.
fn range_corners(range: &str, what: &str) -> Result<((u32, u32), (u32, u32))> {
    let mut corners = range.split(':');
    let first = corners.next().unwrap_or_default();
    let second = corners.next();
    if corners.next().is_some() {
        anyhow::bail!(
            "usage: {what} must be a cell or a rectangular range like B2:D2, got \"{range}\""
        );
    }
    let first = check_cell_address(first, what)?;
    let second = match second {
        Some(second) => check_cell_address(second, what)?,
        None => first,
    };
    Ok((first, second))
}

/// Require a `format_cells` `range` to be a cell or a rectangle inside the sheet's grid, at
/// most `format_cells_max` cells: the kit writes it out cell by cell.
fn require_format_cells_range(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let field = format!("{at}.range");
    let range = edit_string_non_empty(object, "range", at)?;
    let ((first_row, first_column), (last_row, last_column)) = range_corners(range, &field)?;
    let rows = u64::from(last_row.abs_diff(first_row)) + 1;
    let columns = u64::from(last_column.abs_diff(first_column)) + 1;
    let cells = rows * columns;
    if cells > RULES.format_cells_max as u64 {
        anyhow::bail!(
            "usage: {field} \"{range}\" holds {cells} cells, more than one edit formats ({}) — \
             hint: name the rows and columns you mean",
            RULES.format_cells_max
        );
    }
    Ok(())
}

/// Require `range` to name one merge: two corners in either order inside the grid, covering
/// at least two cells. Overlap is the kit's to refuse.
fn require_merge_text(range: &str, what: &str) -> Result<()> {
    let ((first_row, first_column), (last_row, last_column)) = range_corners(range, what)?;
    let cells = (u64::from(last_row.abs_diff(first_row)) + 1)
        * (u64::from(last_column.abs_diff(first_column)) + 1);
    if cells < 2 {
        anyhow::bail!(
            "usage: {what} \"{range}\" covers one cell, and a merge needs at least two — hint: name \
             a range like A1:B2"
        );
    }
    Ok(())
}

fn require_merge_range(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let range = edit_string_non_empty(object, "range", at)?;
    require_merge_text(range, &format!("{at}.range"))
}

/// Require an optional colour to be the shape the kit parses (see [`require_hex_color`]);
/// reports whether it was stated.
fn require_color(object: &serde_json::Map<String, Value>, at: &str) -> Result<bool> {
    match optional_string(object.get("color"), at, "color")? {
        None => Ok(false),
        Some(color) => {
            require_hex_color(&format!("{at}.color"), color)?;
            Ok(true)
        }
    }
}

/// Require an optional `format_cells` `fill`: a colour, or `false` taking the fill away.
fn require_fill(object: &serde_json::Map<String, Value>, at: &str) -> Result<bool> {
    match object.get("fill") {
        None | Some(Value::Null) => Ok(false),
        Some(Value::Bool(false)) => Ok(true),
        Some(Value::Bool(true)) => anyhow::bail!(
            "usage: {at}.fill must be a colour or false — hint: false takes the cell's fill away, \
             and a fill cannot be named without its colour"
        ),
        Some(Value::String(color)) => {
            // The colour is refused with the shared message, naming "none" beside it: the
            // spelling a caller reaches for when they mean "take the fill away".
            require_hex_color(&format!("{at}.fill"), color).map_err(|color_error| {
                anyhow::anyhow!("{color_error} — or pass false to take the cell's fill away")
            })?;
            Ok(true)
        }
        Some(value) => Err(super::wrong_type(
            &format!("{at}.fill"),
            "a colour or false",
            value,
        )),
    }
}

/// Require an optional `border`: an object naming at least one side, each a boolean; an
/// object naming no side and an unknown side are both refused. Reports whether it was stated.
fn require_border(object: &serde_json::Map<String, Value>, at: &str) -> Result<bool> {
    let border = match object.get("border") {
        None | Some(Value::Null) => return Ok(false),
        Some(Value::Object(border)) => border,
        Some(value) => {
            return Err(super::wrong_type(
                &format!("{at}.border"),
                "an object of sides",
                value,
            ));
        }
    };
    let stated = border
        .iter()
        .filter(|(_, value)| !value.is_null())
        .collect::<Vec<_>>();
    if stated.is_empty() {
        anyhow::bail!(
            "usage: {at}.border names no side — hint: it takes {}",
            listed(&RULES.cell_border_sides)
        );
    }
    for (side, value) in stated {
        if !RULES.cell_border_sides.contains(side) {
            anyhow::bail!(
                "usage: {at}.border.{side} is not a side — hint: it takes {}",
                listed(&RULES.cell_border_sides)
            );
        }
        if !matches!(value, Value::Bool(_)) {
            return Err(super::wrong_type(
                &format!("{at}.border.{side}"),
                "a boolean",
                value,
            ));
        }
    }
    Ok(true)
}

/// Require an optional alignment field to be one the writer has — a word whose values are the
/// tokens themselves.
fn require_alignment<W: AsRef<str> + std::fmt::Display>(
    object: &serde_json::Map<String, Value>,
    key: &str,
    values: &[W],
    at: &str,
) -> Result<bool> {
    match optional_string(object.get(key), at, key)? {
        None => Ok(false),
        Some(value) if values.iter().any(|allowed| allowed.as_ref() == value) => Ok(true),
        Some(value) => anyhow::bail!(
            "usage: {at}.{key} must be {}, got \"{value}\"",
            listed(values)
        ),
    }
}

/// Refuse a key the shape `subject` does not take, naming the ones it does: the kit reads only
/// those, so an extra key would be dropped in silence. `fields` is the vocabulary and `always`
/// the keys every shape takes; a null value is not stated.
fn require_taken_keys(
    object: &serde_json::Map<String, Value>,
    at: &str,
    subject: &str,
    fields: &[&str],
    always: &[&str],
) -> Result<()> {
    for key in object.keys() {
        if !always.contains(&key.as_str()) && !fields.contains(&key.as_str()) && stated(object, key)
        {
            let taken = always.iter().chain(fields).copied().collect::<Vec<_>>();
            anyhow::bail!(
                "usage: {at}.{key} is not a field of {subject} — hint: it takes {}",
                listed(&taken)
            );
        }
    }
    Ok(())
}

/// Refuse a content block's key its own kind does not take, against [`CONTENT_BLOCKS`].
fn require_block_keys(object: &serde_json::Map<String, Value>, at: &str, kind: &str) -> Result<()> {
    let fields = CONTENT_BLOCKS
        .iter()
        .find_map(|(name, fields, _)| (*name == kind).then_some(*fields))
        .expect("every block kind the boundary reads is one the declaration names");
    require_taken_keys(object, at, &format!("the {kind} block"), fields, &["type"])
}

/// Content only a Word document can carry — a link, a page break, a table of contents or a
/// footnote: refused for a presentation and this tool's PDF rather than handed to a writer
/// that would drop it.
fn require_docx_block(format: &str, at: &str, kind: &str) -> Result<()> {
    if format == "docx" {
        return Ok(());
    }
    anyhow::bail!(
        "usage: {at} ({kind}) is content only a .docx holds — hint: leave it out of a {format} \
         create"
    )
}

/// A link's address must be one an office application can follow: `http`, `https`, `mailto`
/// and `tel`, anything else refused with the reason. The parsed address is the one carried,
/// since parsing trims the space around it and skips an embedded tab or newline.
fn link_address(raw: &str, index: usize) -> Result<String> {
    let Ok(url) = url::Url::parse(raw) else {
        anyhow::bail!(
            "usage: content[{index}].url must be an absolute URL, e.g. https://example.com — \
             got: {raw:?}"
        );
    };
    if !matches!(url.scheme(), "http" | "https" | "mailto" | "tel") {
        anyhow::bail!(
            "usage: content[{index}].url must be an http, https, mailto or tel address — got: \
             {raw:?}"
        );
    }
    Ok(url.to_string())
}

/// The xlsx edit vocabulary: a sheet is named by every op but `add_sheet`, a cell is an A1
/// address, a row and a column are the 1-based units the reader shows, and a merge is a range
/// of at least two cells.
#[expect(clippy::too_many_lines)] // the one place the xlsx op vocabulary is checked
fn validate_xlsx_edit(
    edit: &Value,
    object: &serde_json::Map<String, Value>,
    op: &str,
    at: &str,
) -> Result<Value> {
    // Ahead of the arm, so an op added later cannot forget it.
    if op != "add_sheet" {
        require_sheet_field(object, at)?;
    }
    match op {
        "set_cell" => {
            require_cell(object, at)?;
            require_name(object, "number_format", RULES.number_format_max, at)?;
            let mut normalized = edit.clone();
            normalized["value"] = require_cell_value(object, at)?;
            return Ok(normalized);
        }
        "clear_cell" => {
            require_cell(object, at)?;
        }
        "format_cells" => {
            let target = require_format_cells_target(object, at)?;
            // A property another target owns (`bold` on a column, which sets only a width) is
            // refused by name.
            require_taken_keys(
                object,
                at,
                &format!("a {} target", target.key()),
                &target.keys(),
                &["op"],
            )?;
            let named = match target {
                FormatCellsTarget::Range => {
                    require_format_cells_range(object, at)?;
                    let mut named = require_toggles(
                        object,
                        &["bold", "italic", "underline", "strike", "wrap"],
                        at,
                    )?;
                    // Excel's own name length; `<name val>` carries the name verbatim.
                    named |= require_name(object, "font", RULES.font_name_max, at)?;
                    named |= require_stated_number(
                        object,
                        "size",
                        &RULES.cell_font_points,
                        "give a size in points",
                        at,
                    )?;
                    named |= require_color(object, at)?;
                    named |= require_fill(object, at)?;
                    named |= require_border(object, at)?;
                    named |= require_alignment(object, "align", &RULES.cell_alignments, at)?;
                    named |= require_alignment(object, "vertical", &RULES.cell_verticals, at)?;
                    if stated(object, "number_format") {
                        require_name(object, "number_format", RULES.number_format_max, at)?;
                        named = true;
                    }
                    named
                }
                FormatCellsTarget::Column => {
                    require_column(object, at)?;
                    require_stated_number(
                        object,
                        "width_chars",
                        &RULES.column_width_chars,
                        "give a width in characters, as Excel shows one",
                        at,
                    )?
                }
                FormatCellsTarget::Row => {
                    require_row(object, at)?;
                    require_stated_number(
                        object,
                        "height_points",
                        &RULES.row_height_points,
                        "give a height in points",
                        at,
                    )?
                }
            };
            if !named {
                anyhow::bail!(
                    "usage: {at} names no formatting — hint: name at least one of {}, beyond the \
                     target it applies to",
                    target.attributes().join(", ")
                );
            }
        }
        "insert_row" | "delete_row" => {
            require_row(object, at)?;
        }
        "insert_column" | "delete_column" => {
            require_column(object, at)?;
        }
        "merge_cells" => {
            require_merge_range(object, at)?;
        }
        "unmerge_cells" => {
            // The corners alone: a one-cell range is refused by the kit, which names the merges
            // the sheet really has.
            let field = format!("{at}.range");
            range_corners(edit_string_non_empty(object, "range", at)?, &field)?;
        }
        "add_sheet" | "rename_sheet" => {
            require_sheet_name_field(object, at)?;
        }
        // Nothing beyond `sheet`: the last-sheet and last-visible refusals are the kit's, which
        // sees the list.
        "delete_sheet" => {}
        "move_sheet" => {
            require_one_based_number(object, "to", at)?;
        }
        "add_image" => {
            require_cell(object, at)?;
            edit_string_non_empty(object, "image", at)?;
            require_span_number(
                object,
                "width",
                &RULES.dimension_points,
                "a picture's width in points",
                at,
            )?;
            require_span_number(
                object,
                "height",
                &RULES.dimension_points,
                "a picture's height in points",
                at,
            )?;
        }
        _ => unreachable!("the op was checked against the family's vocabulary"),
    }
    Ok(edit.clone())
}

/// Require an xlsx edit's `sheet` — every op but `add_sheet` names one — and its length.
fn require_sheet_field(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let sheet = edit_string_non_empty(object, "sheet", at)?;
    require_sheet_name_length(sheet, &format!("{at}.sheet"))
}

/// Require an xlsx edit's `name` to be a sheet name of the shared shape; a duplicate is the
/// kit's refusal.
fn require_sheet_name_field(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let name = edit_string_non_empty(object, "name", at)?;
    require_sheet_name_text(name, &format!("{at}.name"))
}

/// The 1-based column number A1-style letters name (`"A"` -> 1, `"XFD"` -> 16384), or `None`;
/// the letters' shape is checked here and nowhere else.
fn column_number(letters: &str) -> Option<u32> {
    if !((1..=3).contains(&letters.len()) && letters.bytes().all(|byte| byte.is_ascii_uppercase()))
    {
        return None;
    }
    crate::reader_output::column_index(letters).map(|index| index + 1)
}

/// The row and column an A1 address names, or `None`; at most seven digits, so the row cannot
/// overflow a `u32`.
fn cell_address(cell: &str) -> Option<(u32, u32)> {
    let split = cell.find(|c: char| c.is_ascii_digit())?;
    let (letters, digits) = cell.split_at(split);
    let column = column_number(letters)?;
    let digits_ok = digits.len() <= 7
        && digits
            .as_bytes()
            .first()
            .is_some_and(|byte| (b'1'..=b'9').contains(byte))
        && digits.bytes().all(|byte| byte.is_ascii_digit());
    if !digits_ok {
        return None;
    }
    Some((digits.parse().ok()?, column))
}

/// The row and column an A1 address names inside the sheet's grid, refused with `what` naming
/// the field a caller gave it in.
fn check_cell_address(cell: &str, what: &str) -> Result<(u32, u32)> {
    let Some((row, column)) = cell_address(cell) else {
        anyhow::bail!("usage: {what} must be an A1 address like B7, got \"{cell}\"");
    };
    if row > RULES.sheet_row_max {
        anyhow::bail!(
            "usage: {what} \"{cell}\": the row must be between 1 and {}",
            RULES.sheet_row_max
        );
    }
    if column > RULES.sheet_column_max {
        anyhow::bail!(
            "usage: {what} \"{cell}\": the column must be between A and {}",
            crate::reader_output::column_letters(RULES.sheet_column_max - 1)
        );
    }
    Ok((row, column))
}

/// Require an edit's `cell` to be an A1 address inside the sheet's grid.
fn require_cell(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let cell = edit_string_non_empty(object, "cell", at)?;
    check_cell_address(cell, &format!("{at}.cell")).map(|_| ())
}

/// The `value` a `set_cell` writes: a scalar the writer stringifies, or a `{"formula": "…"}`
/// object normalized to its text, as `create`'s cells are. A `null` is absent.
fn require_cell_value(object: &serde_json::Map<String, Value>, at: &str) -> Result<Value> {
    let Some(value) = object.get("value").filter(|value| !value.is_null()) else {
        anyhow::bail!(
            "usage: {at} has no \"value\" — hint: pass a string, a number, a boolean or \
             {{\"formula\": \"SUM(A1:A2)\"}}, or use the \"format_cells\" op to change only the \
             cell's formatting"
        );
    };
    if is_scalar(value) {
        return Ok(value.clone());
    }
    match value {
        Value::Object(formula) => normalized_formula(&format!("{at}.value"), formula),
        other => Err(super::wrong_type(
            &format!("{at}.value"),
            SCALAR_TYPE,
            other,
        )),
    }
}

/// Require an edit's `row` to be a sheet row the workbook's grid holds.
fn require_row(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    match edit_integer(object, "row", at)? {
        Some(row) if (1..=u64::from(RULES.sheet_row_max)).contains(&row) => Ok(()),
        _ => anyhow::bail!(
            "usage: {at}.row must be a whole number between 1 and {} — hint: a 1-based sheet row",
            RULES.sheet_row_max
        ),
    }
}

/// Require an edit's `column` to be column letters the workbook's grid holds.
fn require_column(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let column = edit_string_non_empty(object, "column", at)?;
    match column_number(column) {
        Some(number) if number <= RULES.sheet_column_max => Ok(()),
        _ => anyhow::bail!(
            "usage: {at}.column must be column letters between A and {}, got \"{column}\"",
            crate::reader_output::column_letters(RULES.sheet_column_max - 1)
        ),
    }
}

/// The pptx edit vocabulary: a slide is its 1-based number, and a text op names a fragment
/// that must be on it.
fn validate_pptx_edit(object: &serde_json::Map<String, Value>, op: &str, at: &str) -> Result<()> {
    match op {
        "replace_text" | "replace_notes" => {
            require_slide(object, at)?;
            require_pptx_lookup(edit_string_non_empty(object, "find", at)?, "find", at)?;
            edit_string_present(object, "replace", at)?;
        }
        "remove_text" | "remove_paragraph" | "remove_notes" => {
            require_slide(object, at)?;
            require_pptx_lookup(edit_string_non_empty(object, "find", at)?, "find", at)?;
        }
        "format_text" => {
            require_slide(object, at)?;
            require_pptx_lookup(edit_string_non_empty(object, "find", at)?, "find", at)?;
            require_pptx_format(object, at)?;
        }
        "add_paragraph" => {
            require_slide(object, at)?;
            edit_string_present(object, "text", at)?;
            // An absent anchor places the paragraph last; a blank one is refused like a blank
            // `find`.
            if let Some(after) = edit_string(object, "after", at)? {
                require_pptx_lookup(after, "after", at)?;
            }
            require_optional_level(object, at)?;
        }
        "add_image" => {
            require_slide(object, at)?;
            edit_string_non_empty(object, "image", at)?;
            require_slide_geometry(object, at)?;
        }
        "add_table" => {
            require_slide(object, at)?;
            // A presentation's table has no column bound (see [`require_table`]).
            require_table(object, at, None)?;
            require_slide_geometry(object, at)?;
        }
        "add_slide" => {
            if edit_integer(object, "after", at)? == Some(0) {
                anyhow::bail!("usage: {at}.after must be a whole number of at least 1");
            }
            require_optional_text(object, "title", at)?;
            require_bullets(object, at)?;
        }
        "delete_slide" | "duplicate_slide" => {
            require_slide(object, at)?;
        }
        "move_slide" => {
            require_slide(object, at)?;
            require_one_based_number(object, "to", at)?;
        }
        "add_notes" => {
            require_slide(object, at)?;
            edit_string_present(object, "text", at)?;
        }
        _ => unreachable!("the op was checked against the family's vocabulary"),
    }
    Ok(())
}

/// Require a pptx edit's lookup — the `find` a text op searches for, or the `after` anchor —
/// to name text; one empty once trimmed is refused before the deck is read.
fn require_pptx_lookup(text: &str, key: &str, at: &str) -> Result<()> {
    if text.trim().is_empty() {
        anyhow::bail!(
            "usage: {at}.{key} must name text — whitespace alone names nothing to search for"
        );
    }
    Ok(())
}

/// Require an edit's `slide` to be a 1-based slide number; a deck's length is the kit's to know.
fn require_slide(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    require_one_based_number(object, "slide", at)
}

/// Require a 1-based number under `key`: an edit's `slide`, or a `move_slide`/`move_sheet` `to`.
fn require_one_based_number(
    object: &serde_json::Map<String, Value>,
    key: &str,
    at: &str,
) -> Result<()> {
    match edit_integer(object, key, at)? {
        Some(number) if number >= 1 => Ok(()),
        _ => anyhow::bail!("usage: {at}.{key} must be a whole number of at least 1"),
    }
}

/// Require an `add_paragraph`'s optional outline `level` to be one the slide writer has (0 is
/// the slide's own level).
fn require_optional_level(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    match edit_integer(object, "level", at)? {
        None => Ok(()),
        Some(level) if level <= u64::from(RULES.paragraph_level_max) => Ok(()),
        Some(level) => {
            anyhow::bail!(
                "usage: {at}.level must be a whole number from 0 to {}, got {level}",
                RULES.paragraph_level_max
            )
        }
    }
}

/// Require an `add_slide`'s optional `bullets` to be a list of bounded strings.
fn require_bullets(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let bullets = match object.get("bullets") {
        None | Some(Value::Null) => return Ok(()),
        Some(Value::Array(bullets)) => bullets,
        Some(v) => return Err(super::wrong_type(&format!("{at}.bullets"), "an array", v)),
    };
    if bullets.len() > RULES.bullets_max {
        anyhow::bail!(
            "usage: {at}.bullets must hold at most {} bullets, got {} — hint: split the slide",
            RULES.bullets_max,
            bullets.len()
        );
    }
    for (index, bullet) in bullets.iter().enumerate() {
        let Some(text) = bullet.as_str() else {
            return Err(super::wrong_type(
                &format!("{at}.bullets[{index}]"),
                "a string",
                bullet,
            ));
        };
        let length = text.chars().count();
        if length > RULES.edit_text_max {
            anyhow::bail!(
                "usage: {at}.bullets[{index}] must be at most {} characters, got {length}",
                RULES.edit_text_max
            );
        }
    }
    Ok(())
}

/// The words of a shared `(word, value)` list, in the order the rules state them: what a
/// refusal and the model-facing hint both read.
fn pair_words(list: &[(String, String)]) -> Vec<&str> {
    list.iter().map(|(word, _)| word.as_str()).collect()
}

/// The slide sizes a `create` may name, as the words the model chooses from.
fn pptx_size_words() -> Vec<&'static str> {
    RULES
        .pptx_sizes
        .iter()
        .map(|size| size.name.as_str())
        .collect()
}

/// The same sizes as the model reads them: every word with the deck it means.
fn pptx_size_list() -> String {
    RULES
        .pptx_sizes
        .iter()
        .map(|size| format!("{} ({})", size.name, size.deck.inches()))
        .collect::<Vec<_>>()
        .join(", ")
}

/// The shared Word marks a reading prints in brackets, and the labels it adds without them,
/// quoted for the prompt (see [`crate::docgen::docx_marks`]); a mark's group is the shape it
/// is printed as.
fn spelled_docx_marks(bracketed: bool) -> String {
    crate::docgen::docx_marks()
        .iter()
        .filter(|mark| mark.example.starts_with('[') == bracketed)
        .map(|mark| format!("`{}`", mark.example))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Require a pptx `format_text` to name at least one property, each the shape the kit writes:
/// a toggle, a point size inside the presentation's bound, a hex colour, or an alignment.
fn require_pptx_format(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let mut any = require_toggles(object, &["bold", "italic", "underline", "strike"], at)?;
    any |= require_stated_number(
        object,
        "size",
        &RULES.slide_text_size_points,
        "give a size in points",
        at,
    )?;
    any |= require_color(object, at)?;
    any |= require_alignment(object, "align", &pair_words(&RULES.slide_alignments), at)?;
    if !any {
        anyhow::bail!(
            "usage: {at} (format_text) needs at least one of bold, italic, underline, strike, \
             size, color or align — hint: a boolean sets bold, italic, underline or strike (false \
             switches it off), size is in points, color is hex digits and align is {}",
            listed(&pair_words(&RULES.slide_alignments))
        );
    }
    Ok(())
}

/// Require a shape's optional placement and size: `x_fraction`/`y_fraction` may sit on the
/// slide's edge, `width_fraction`/`height_fraction` may not be zero.
fn require_slide_geometry(object: &serde_json::Map<String, Value>, at: &str) -> Result<()> {
    let place = "give the fraction of the slide the shape is placed at";
    let size = "give the fraction of the slide the shape is scaled to";
    for (key, span, what) in [
        ("x_fraction", &RULES.slide_position_fraction, place),
        ("y_fraction", &RULES.slide_position_fraction, place),
        ("width_fraction", &RULES.slide_size_fraction, size),
        ("height_fraction", &RULES.slide_size_fraction, size),
    ] {
        require_span_number(object, key, span, what, at)?;
    }
    Ok(())
}

/// Resolve and validate the `content` blocks, resolving every embedded image path under the
/// caller's [`PathAccess`].
async fn resolve_content(
    ws: &Workspace,
    args: &Value,
    format: &str,
    access: PathAccess,
) -> Result<Value> {
    let blocks = match args.get("content") {
        Some(Value::Array(blocks)) if !blocks.is_empty() => blocks,
        Some(Value::Array(_)) => {
            anyhow::bail!("usage: \"content\" is empty — hint: pass at least one block")
        }
        Some(v) => return Err(super::wrong_type("content", "an array", v)),
        None => anyhow::bail!(
            "usage: missing required argument \"content\" — hint: pass a JSON array of blocks, \
             e.g. [{{\"type\": \"paragraph\", \"text\": \"…\"}}]"
        ),
    };
    let mut out = Vec::with_capacity(blocks.len());
    // The kinds a block may name, from the one table that states them.
    let kinds = CONTENT_BLOCKS
        .iter()
        .map(|(kind, _, _)| *kind)
        .collect::<Vec<_>>();
    let mut contents = false;
    for (index, block) in blocks.iter().enumerate() {
        let Some(object) = block.as_object() else {
            anyhow::bail!(
                "usage: content[{index}] must be an object — hint: give every block a \"type\""
            );
        };
        let Some(kind) = object.get("type").and_then(Value::as_str) else {
            anyhow::bail!(
                "usage: content[{index}] has no \"type\" — hint: use {}",
                listed(&kinds)
            );
        };
        let at = format!("content[{index}]");
        // Every arm produces the block to push, validating its shape and handing back what the
        // request carries, the image's path resolved against the workspace.
        let resolved = match kind {
            "heading" => {
                require_block_keys(object, &at, "heading")?;
                require_string(object, "text", index)?;
                require_heading_level(object, index)?;
                block.clone()
            }
            "paragraph" => {
                require_block_keys(object, &at, "paragraph")?;
                require_string(object, "text", index)?;
                // A footnote is a Word document's own — a presentation and a PDF have nowhere to
                // print one — and an explicit null is an absent footnote.
                if object.get("footnote").is_some_and(|value| !value.is_null()) {
                    require_docx_block(format, &at, "footnote")?;
                    require_text(object, "footnote", index)?;
                }
                block.clone()
            }
            // Speaker notes exist only on a presentation: dropping the block for a document or a
            // PDF would lose text the caller asked for.
            "notes" => {
                if format != "pptx" {
                    anyhow::bail!(
                        "usage: content[{index}] (notes) is a presentation's speaker notes — \
                         only pptx has notes — hint: write a paragraph block instead"
                    );
                }
                require_block_keys(object, &at, "notes")?;
                require_string(object, "text", index)?;
                block.clone()
            }
            "list" => {
                require_block_keys(object, &at, "list")?;
                let Some(items) = object.get("items") else {
                    anyhow::bail!("usage: content[{index}] has no \"items\"");
                };
                require_scalar_array(items, &format!("content[{index}].items"))?;
                require_optional_bool(object, "ordered", index)?;
                block.clone()
            }
            "table" => {
                require_block_keys(object, &at, "table")?;
                // The block reaches the writers as the one shape both take: an empty header set and
                // a cell-less row are dropped here. Only a Word table has a column bound.
                let table = normalize_table(object);
                let max = (format == "docx").then_some(RULES.table_columns_max);
                require_table(&table, &at, max)?;
                Value::Object(table)
            }
            "image" => resolve_image_block(ws, block, object, index, format, access).await?,
            "link" | "page_break" | "contents" => {
                docx_only_block(block, object, kind, index, format, &mut contents)?
            }
            other => anyhow::bail!(
                "usage: content[{index}] has unknown type \"{other}\" — hint: use {}",
                listed(&kinds)
            ),
        };
        out.push(resolved);
    }
    Ok(Value::Array(out))
}

/// A block only a Word document holds — a link, a page break or a table of contents — in the
/// shape its kind declares, carrying the address its own parse produced.
fn docx_only_block(
    block: &Value,
    object: &serde_json::Map<String, Value>,
    kind: &str,
    index: usize,
    format: &str,
    contents: &mut bool,
) -> Result<Value> {
    let at = format!("content[{index}]");
    require_block_keys(object, &at, kind)?;
    require_docx_block(format, &at, kind)?;
    let mut resolved = block.clone();
    match kind {
        "link" => {
            require_text(object, "text", index)?;
            resolved["url"] = json!(link_address(require_string(object, "url", index)?, index)?);
        }
        "contents" if *contents => anyhow::bail!(
            "usage: content[{index}] is a second table of contents — a document has one"
        ),
        "contents" => *contents = true,
        _ => {}
    }
    Ok(resolved)
}

/// One `image` content block resolved: its path under the caller's [`PathAccess`], checked
/// against the formats the target can hold.
async fn resolve_image_block(
    ws: &Workspace,
    block: &Value,
    object: &serde_json::Map<String, Value>,
    index: usize,
    format: &str,
    access: PathAccess,
) -> Result<Value> {
    require_block_keys(object, &format!("content[{index}]"), "image")?;
    require_optional_size(object, "width", index)?;
    require_optional_size(object, "height", index)?;
    let Some(raw) = object.get("image").and_then(Value::as_str) else {
        anyhow::bail!(
            "usage: content[{index}] (image) has no \"image\" — hint: give the image's path"
        );
    };
    let (image, _) = resolve_input(ws, raw, access).await?;
    // A PDF's own two encodings take no WebP; the block is refused before an output is reserved.
    if format == "pdf" {
        ensure_picture(&image, &pdf_pictures())?;
    } else {
        ensure_picture(&image, &embedded_pictures())?;
    }
    let mut resolved = block.clone();
    resolved["image"] = json!(image.to_string_lossy());
    Ok(resolved)
}

/// Resolve every `add_image` picture in a validated edit list under [`PathAccess`], the way
/// `create`'s image block is, so an edit cannot embed a file outside the caller's reach.
async fn resolve_edit_images(ws: &Workspace, edits: &mut Value, access: PathAccess) -> Result<()> {
    let list = edits
        .as_array_mut()
        .expect("validate_edits hands an edit list back as an array");
    for edit in list {
        let object = edit
            .as_object_mut()
            .expect("validate_edits hands every edit back as an object");
        if object.get("op").and_then(Value::as_str) != Some("add_image") {
            continue;
        }
        let raw = object
            .get("image")
            .and_then(Value::as_str)
            .expect("the edit validator requires an add_image image")
            .to_owned();
        let (image, _) = resolve_input(ws, &raw, access).await?;
        ensure_picture(&image, &embedded_pictures())?;
        object.insert("image".to_owned(), json!(image.to_string_lossy()));
    }
    Ok(())
}

/// Whether one of `edits` looks text up on the slide itself (see [`PPTX_SLIDE_TEXT_OPS`]):
/// only such an edit needs the slides' diagram text read.
fn edits_search_slide_text(edits: &Value) -> bool {
    edits.as_array().is_some_and(|edits| {
        edits.iter().any(|edit| {
            let names_a_lookup = edit.get("find").is_some() || edit.get("after").is_some();
            names_a_lookup
                && edit
                    .get("op")
                    .and_then(Value::as_str)
                    .is_some_and(|op| PPTX_SLIDE_TEXT_OPS.contains(&op))
        })
    })
}

/// Resolve and validate the `sheets` argument, every cell a shape the kit's writer knows.
fn resolve_sheets(args: &Value) -> Result<Value> {
    let sheets = match args.get("sheets") {
        Some(Value::Array(sheets)) if !sheets.is_empty() => sheets,
        Some(Value::Array(_)) => {
            anyhow::bail!("usage: \"sheets\" is empty — hint: pass at least one sheet")
        }
        Some(v) => return Err(super::wrong_type("sheets", "an array", v)),
        None => anyhow::bail!(
            "usage: missing required argument \"sheets\" — hint: pass a JSON array of sheets, \
             e.g. [{{\"rows\": [[\"Cell\", 1]]}}]"
        ),
    };
    let mut normalized = Vec::with_capacity(sheets.len());
    let mut seen_names = HashSet::new();
    for (index, sheet) in sheets.iter().enumerate() {
        let Some(object) = sheet.as_object() else {
            anyhow::bail!(
                "usage: sheets[{index}] must be an object — hint: {{\"name\": …, \"rows\": [[…]]}}"
            );
        };
        let at = format!("sheets[{index}]");
        require_taken_keys(object, &at, "a sheet", &sheet_field_names(), &[])?;
        let name = optional_string(object.get("name"), &at, "name")?;
        // A sheet with no name is written as `Sheet<n>` by position: resolving it here means the
        // request always carries an explicit name, held to the shared rules too.
        let name = name.filter(|name| !name.is_empty()).map_or_else(
            || format!("Sheet{}", index + 1),
            std::string::ToString::to_string,
        );
        require_sheet_name(&name, index, &mut seen_names)?;
        let rows = match object.get("rows") {
            Some(Value::Array(rows)) => normalize_sheet_cells(rows, index)?,
            Some(v) => {
                return Err(super::wrong_type(
                    &format!("sheets[{index}].rows"),
                    "an array",
                    v,
                ));
            }
            None => anyhow::bail!(
                "usage: sheets[{index}] has no \"rows\" — hint: {{\"rows\": [[\"Cell\", 1]]}}"
            ),
        };
        let mut normalized_sheet = object.clone();
        normalized_sheet.insert("name".to_owned(), json!(name));
        normalized_sheet.insert("rows".to_owned(), rows);
        // The clone carries the sheet's own `merges` in place; a null reads as absent, as the kit
        // tests only `!== undefined`.
        match object.get("merges") {
            None => {}
            Some(Value::Null) => {
                normalized_sheet.remove("merges");
            }
            Some(Value::Array(merges)) => require_sheet_merges(merges, index)?,
            Some(v) => {
                return Err(super::wrong_type(
                    &format!("sheets[{index}].merges"),
                    "an array",
                    v,
                ));
            }
        }
        normalized.push(Value::Object(normalized_sheet));
    }
    Ok(Value::Array(normalized))
}

/// Require a `create` sheet's `merges`: each an A1 range inside the grid covering at least two
/// cells. Overlap is the kit's to refuse.
fn require_sheet_merges(merges: &[Value], index: usize) -> Result<()> {
    for (position, merge) in merges.iter().enumerate() {
        let at = format!("sheets[{index}].merges[{position}]");
        match merge {
            Value::String(range) => require_merge_text(range, &at)?,
            other => return Err(super::wrong_type(&at, "a string", other)),
        }
    }
    Ok(())
}

/// Refuse a sheet name longer than the shared cap, naming `at` in the message. The length rule is
/// the same one `create`'s `sheets[{index}].name` enforces, so the two sites must stay in step.
fn require_sheet_name_length(name: &str, at: &str) -> Result<()> {
    if name.chars().count() > RULES.sheet_name_max {
        anyhow::bail!(
            "usage: {at} must be at most {} characters, got \"{name}\" — hint: shorten the sheet \
             name",
            RULES.sheet_name_max
        );
    }
    Ok(())
}

/// Require a sheet name to satisfy the shared rules — the cap, none of the forbidden characters
/// and no earlier sheet sharing it ignoring case; only the upper bound is checked here.
fn require_sheet_name(name: &str, index: usize, seen: &mut HashSet<String>) -> Result<()> {
    let at = format!("sheets[{index}].name");
    require_sheet_name_text(name, &at)?;
    if !seen.insert(name.to_lowercase()) {
        anyhow::bail!(
            "usage: {at} is not unique, ignoring case, got \"{name}\" — hint: give every sheet a \
             distinct name"
        );
    }
    Ok(())
}

/// Require a sheet name to have the shared shape: the cap and no forbidden character.
/// Uniqueness is `create`'s and the kit's.
fn require_sheet_name_text(name: &str, at: &str) -> Result<()> {
    require_sheet_name_length(name, at)?;
    if let Some(forbidden) = RULES
        .sheet_name_forbidden
        .chars()
        .find(|character| name.contains(*character))
    {
        // The offending character as a JSON string; a bare `\` before a closing quote reads as an
        // escaped quote instead.
        anyhow::bail!(
            "usage: {at} must not contain {:?} — hint: a sheet name cannot hold any of {:?}",
            forbidden.to_string(),
            RULES.sheet_name_forbidden
        );
    }
    Ok(())
}

/// A sheet cell holding a formula: an object with nothing but a `formula` whose text, trimmed
/// with one leading `=` removed, is not empty and no longer starts with `=` — returned as
/// `{"formula": …}` so the cell holds a formula. The kit repeats the rule.
fn normalized_formula(at: &str, object: &serde_json::Map<String, Value>) -> Result<Value> {
    let normalized = object
        .get("formula")
        .and_then(Value::as_str)
        .map(str::trim)
        .map(|text| text.strip_prefix('=').unwrap_or(text).trim())
        .filter(|text| !text.is_empty() && !text.starts_with('='));
    match normalized {
        Some(text) if object.len() == 1 => Ok(json!({ "formula": text })),
        _ => anyhow::bail!(
            "usage: {at} must be text, a number, a boolean or {{\"formula\": \"SUM(A1:A2)\"}} — \
             hint: the formula's text alone, as in \"SUM(A1:A2)\""
        ),
    }
}

/// Normalize every row of a sheet: an array of cells the writer knows, a string starting with
/// `=` staying text; a formula cell goes through [`normalized_formula`].
fn normalize_sheet_cells(rows: &[Value], sheet: usize) -> Result<Value> {
    let mut normalized_rows = Vec::with_capacity(rows.len());
    for (row_index, row) in rows.iter().enumerate() {
        let Some(cells) = row.as_array() else {
            return Err(super::wrong_type(
                &format!("sheets[{sheet}].rows[{row_index}]"),
                "an array",
                row,
            ));
        };
        let mut normalized_cells = Vec::with_capacity(cells.len());
        for (cell_index, cell) in cells.iter().enumerate() {
            let at = format!("sheets[{sheet}].rows[{row_index}][{cell_index}]");
            match cell {
                value if is_scalar(value) => normalized_cells.push(value.clone()),
                Value::Object(object) => {
                    let formula = normalized_formula(&at, object)?;
                    normalized_cells.push(formula);
                }
                other => return Err(super::wrong_type(&at, SCALAR_TYPE, other)),
            }
        }
        normalized_rows.push(Value::Array(normalized_cells));
    }
    Ok(Value::Array(normalized_rows))
}

/// A table's shape as both producers take it: `headers` and `rows` of scalars, something to lay
/// out, and — where the target has one — the column bound (`None` for a pptx or a PDF).
fn require_table(
    object: &serde_json::Map<String, Value>,
    at: &str,
    max_columns: Option<usize>,
) -> Result<()> {
    // `headers` is optional — null counts as absent here exactly as it does for `rows`.
    let headers = match object.get("headers").filter(|value| !value.is_null()) {
        None => 0,
        Some(headers) => {
            require_scalar_array(headers, &format!("{at}.headers"))?;
            headers.as_array().map_or(0, Vec::len)
        }
    };
    // The headings row is a row too: its cells count toward the columns the table states.
    let mut widest = headers;
    let mut laid_out = 0;
    if let Some(rows) = object.get("rows").filter(|value| !value.is_null()) {
        let Some(rows) = rows.as_array() else {
            return Err(super::wrong_type(&format!("{at}.rows"), "an array", rows));
        };
        for (row_index, row) in rows.iter().enumerate() {
            let Some(cells) = row.as_array() else {
                return Err(super::wrong_type(
                    &format!("{at}.rows[{row_index}]"),
                    "an array",
                    row,
                ));
            };
            if let Some((cell_index, cell)) = scalar_array_violation(cells) {
                return Err(super::wrong_type(
                    &format!("{at}.rows[{row_index}][{cell_index}]"),
                    SCALAR_TYPE,
                    cell,
                ));
            }
            widest = widest.max(cells.len());
            // A row with no cells lays out nothing, and a `<w:tr/>` is one Word refuses to open
            // (see [`normalize_table`]).
            laid_out += usize::from(!cells.is_empty());
        }
    }
    // A table with nothing to lay out is refused: the docx arm would emit a `<w:tbl>` with no
    // row, which Word refuses to open.
    if laid_out + headers == 0 {
        anyhow::bail!(
            "usage: {at} states a table with no rows and no headers — hint: give it at least one \
             row or one header"
        );
    }
    if let Some(max) = max_columns.filter(|max| widest > *max) {
        anyhow::bail!(
            "usage: {at} states {widest} columns — a table holds at most {max} — hint: split the \
             table"
        );
    }
    Ok(())
}

/// Require `value` to be an array of scalars (see [`SCALAR_TYPE`]), naming the offending
/// position by `at` — the full path.
fn require_scalar_array(value: &Value, at: &str) -> Result<()> {
    let Some(values) = value.as_array() else {
        return Err(super::wrong_type(at, "an array", value));
    };
    match scalar_array_violation(values) {
        Some((position, scalar)) => Err(super::wrong_type(
            &format!("{at}[{position}]"),
            SCALAR_TYPE,
            scalar,
        )),
        None => Ok(()),
    }
}

/// What a bullet and a table cell can hold: the types the kit's writers stringify.
const SCALAR_TYPE: &str = "text, a number or a boolean";

/// The type name a scalar has in the shared rules' vocabulary, or `None` for a structure (and
/// for null).
fn scalar_kind(value: &Value) -> Option<&'static str> {
    match value {
        Value::String(_) => Some("string"),
        Value::Number(_) => Some("number"),
        Value::Bool(_) => Some("boolean"),
        _ => None,
    }
}

/// Whether `value` is one of the scalar kinds the shared rules allow.
fn is_scalar(value: &Value) -> bool {
    scalar_kind(value).is_some_and(|kind| RULES.scalar_kinds.iter().any(|allowed| allowed == kind))
}

/// The first element of `values` that is not a scalar, with its position.
fn scalar_array_violation(values: &[Value]) -> Option<(usize, &Value)> {
    values
        .iter()
        .enumerate()
        .find(|(_, value)| !is_scalar(value))
}

/// Normalize a table block: an empty set is an absent one, so an empty `headers` array is
/// removed and a cell-less row is dropped; [`require_table`] shape-checks what is left.
fn normalize_table(object: &serde_json::Map<String, Value>) -> serde_json::Map<String, Value> {
    let mut table = object.clone();
    if table
        .get("headers")
        .and_then(Value::as_array)
        .is_some_and(Vec::is_empty)
    {
        table.remove("headers");
    }
    if let Some(Value::Array(rows)) = table.get_mut("rows") {
        rows.retain(|row| !row.as_array().is_some_and(Vec::is_empty));
    }
    table
}

/// `1, 2 or 3` — how a refusal hint and the description name the values a rule allows.
fn listed<T: std::fmt::Display>(values: &[T]) -> String {
    crate::util::listed(values, "or")
}

/// Whole megabytes of `bytes`, the unit the tool's messages state a size in.
fn megabytes(bytes: u64) -> u64 {
    bytes / (1024 * 1024)
}

/// Require a heading's `level` to be one of the levels the writers have.
fn require_heading_level(object: &serde_json::Map<String, Value>, index: usize) -> Result<()> {
    match object.get("level") {
        None | Some(Value::Null) => Ok(()),
        Some(value) => {
            let valid = value
                .as_f64()
                .is_some_and(|level| level.fract() == 0.0 && RULES.heading_levels.contains(&level));
            if valid {
                Ok(())
            } else {
                anyhow::bail!(
                    "usage: content[{index}].level must be {} — hint: a lower number is the more \
                     important heading",
                    listed(&RULES.heading_levels)
                )
            }
        }
    }
}

/// Require an optional content-block size field to be a number inside the shared
/// `dimension_points` range: zero or a negative number is not a size.
fn require_optional_size(
    object: &serde_json::Map<String, Value>,
    key: &str,
    index: usize,
) -> Result<()> {
    match object.get(key) {
        None | Some(Value::Null) => Ok(()),
        Some(value) => {
            let number = value.as_f64().ok_or_else(|| {
                super::wrong_type(&format!("content[{index}].{key}"), "a number", value)
            })?;
            if !RULES.dimension_points.contains(number) {
                anyhow::bail!(
                    "usage: content[{index}].{key} must be {} points, got {number} — hint: give \
                     the size the image should be placed at",
                    RULES.dimension_points.bounds()
                );
            }
            Ok(())
        }
    }
}

fn require_optional_bool(
    object: &serde_json::Map<String, Value>,
    key: &str,
    index: usize,
) -> Result<()> {
    match object.get(key) {
        None | Some(Value::Null | Value::Bool(_)) => Ok(()),
        Some(value) => Err(super::wrong_type(
            &format!("content[{index}].{key}"),
            "a boolean",
            value,
        )),
    }
}

/// A present optional string: an absent or null value is `None`, a value of another type is
/// refused rather than read as absent. `at` prefixes the path a refusal names.
fn optional_string<'a>(value: Option<&'a Value>, at: &str, key: &str) -> Result<Option<&'a str>> {
    match value {
        None | Some(Value::Null) => Ok(None),
        Some(Value::String(text)) => Ok(Some(text)),
        Some(other) => Err(super::wrong_type(&format!("{at}.{key}"), "a string", other)),
    }
}

/// The PDF description `metadata` names, in the kit's shape: a field it does not name is absent
/// rather than null, so the file's own entry stays — except the modification date an edit advances.
fn opt_metadata(args: &Value) -> Result<Option<Value>> {
    let Some(value) = args.get("metadata") else {
        return Ok(None);
    };
    if value.is_null() {
        return Ok(None);
    }
    let Some(object) = value.as_object() else {
        return Err(super::wrong_type("metadata", "an object", value));
    };
    let fields = crate::docgen::pdf_metadata_fields();
    let keys = fields
        .iter()
        .map(|field| field.key.as_str())
        .collect::<Vec<_>>();
    if object.is_empty() {
        anyhow::bail!(
            "usage: \"metadata\" is empty — hint: name at least one of {}",
            listed(&keys)
        );
    }
    let mut metadata = serde_json::Map::with_capacity(object.len());
    for (key, value) in object {
        let Some(field) = fields.iter().find(|field| field.key == *key) else {
            anyhow::bail!(
                "usage: unknown metadata field \"{key}\" — hint: use {}",
                listed(&keys)
            );
        };
        let Some(text) = value.as_str() else {
            return Err(super::wrong_type(
                &format!("metadata.{key}"),
                "a string",
                value,
            ));
        };
        metadata.insert(
            key.clone(),
            Value::String(if field.date {
                pdf_date(text)?
            } else {
                text.to_string()
            }),
        );
    }
    Ok(Some(Value::Object(metadata)))
}

/// Attach a PDF action's `metadata` to its request, when the caller named it.
fn set_metadata(request: &mut Value, metadata: Option<Value>) {
    if let Some(metadata) = metadata {
        request["metadata"] = metadata;
    }
}

/// The PDF spelling of a metadata date: `D:YYYYMMDDHHMMSS` with `Z` or `±HH'MM'`; a calendar
/// date alone is midnight UTC. An empty string clears the entry.
fn pdf_date(text: &str) -> Result<String> {
    if text.is_empty() {
        return Ok(String::new());
    }
    let refused = || {
        anyhow::anyhow!(
            "usage: \"{text}\" is not a date — hint: use {}",
            crate::docgen::pdf_date_format()
        )
    };
    let date = text.get(..10).ok_or_else(refused)?;
    let date = chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").map_err(|_| refused())?;
    let mut rest = &text[10..];
    let offset_minutes = if let Some(stripped) = rest.strip_suffix('Z') {
        rest = stripped;
        0
    } else if let Some(index) = rest.rfind(['+', '-']) {
        let (time, offset) = rest.split_at(index);
        rest = time;
        pdf_offset(offset).ok_or_else(refused)?
    } else {
        0
    };
    let time = if rest.is_empty() {
        chrono::NaiveTime::from_hms_opt(0, 0, 0).expect("midnight is a valid time")
    } else {
        let time = rest.strip_prefix('T').ok_or_else(refused)?;
        ["%H:%M", "%H:%M:%S"]
            .iter()
            .find_map(|format| chrono::NaiveTime::parse_from_str(time, format).ok())
            .ok_or_else(refused)?
    };
    let mut rendered = format!(
        "D:{:04}{:02}{:02}{:02}{:02}{:02}",
        date.year(),
        date.month(),
        date.day(),
        time.hour(),
        time.minute(),
        time.second()
    );
    if offset_minutes == 0 {
        rendered.push('Z');
    } else {
        let sign = if offset_minutes < 0 { '-' } else { '+' };
        let minutes = offset_minutes.abs();
        let _ = write!(rendered, "{sign}{:02}'{:02}'", minutes / 60, minutes % 60);
    }
    Ok(rendered)
}

/// A `±HH:MM` offset as minutes from UTC.
fn pdf_offset(text: &str) -> Option<i32> {
    let (sign, rest) = match text.as_bytes().first()? {
        b'+' => (1, &text[1..]),
        b'-' => (-1, &text[1..]),
        _ => return None,
    };
    let (hours, minutes) = rest.split_once(':')?;
    if hours.len() != 2 || minutes.len() != 2 {
        return None;
    }
    let hours: i32 = hours.parse().ok()?;
    let minutes: i32 = minutes.parse().ok()?;
    if hours > 23 || minutes > 59 {
        return None;
    }
    Some(sign * (hours * 60 + minutes))
}

/// Require a fill's `values` to be present and non-empty: a fill with no values is a copy, not
/// a fill. Both fills resolve their input first.
fn require_values(args: &Value, kind: &str) -> Result<serde_json::Map<String, Value>> {
    let values = super::get_object(args, "values")?;
    if values.is_empty() {
        anyhow::bail!(
            "usage: missing or empty argument \"values\" — hint: name at least one {kind}, e.g. \
             {{\"name\": \"Иван\"}}"
        );
    }
    Ok(values)
}

/// Require every value of a name-keyed map to be a scalar the kit can write; a structure would
/// reach the document as `[object Object]`.
fn require_scalar_values(values: &serde_json::Map<String, Value>) -> Result<()> {
    for (name, value) in values {
        if !is_scalar(value) {
            return Err(super::wrong_type(
                &format!("values.{name}"),
                SCALAR_TYPE,
                value,
            ));
        }
    }
    Ok(())
}

/// Check a colour against the shared `color_digits`, with an optional leading `#`; `at` names
/// the path a refusal spells.
fn require_hex_color(at: &str, color: &str) -> Result<()> {
    let digits = color.strip_prefix('#').unwrap_or(color);
    if digits.len() == RULES.color_digits && digits.chars().all(|digit| digit.is_ascii_hexdigit()) {
        return Ok(());
    }
    anyhow::bail!(
        "usage: {at} must be {} hex digits, with an optional leading \"#\", got \"{color}\" — \
         hint: like \"#{}\"",
        RULES.color_digits,
        "f".repeat(RULES.color_digits)
    )
}

/// Require `object[key]` to be a string, naming the block position in the error, and give its text.
fn require_string<'a>(
    object: &'a serde_json::Map<String, Value>,
    key: &str,
    index: usize,
) -> Result<&'a str> {
    match object.get(key) {
        Some(Value::String(text)) => Ok(text),
        Some(v) => Err(super::wrong_type(
            &format!("content[{index}].{key}"),
            "a string",
            v,
        )),
        None => anyhow::bail!("usage: content[{index}] has no \"{key}\""),
    }
}

/// Require text to hold something: an empty or whitespace-only link text, footnote, header or
/// footer is content no reader shows, so it is refused rather than written. `at` names the
/// field and `hint` the way out.
fn require_visible(at: &str, text: &str, hint: &str) -> Result<()> {
    if text.trim().is_empty() {
        anyhow::bail!("usage: {at} is empty — hint: {hint}");
    }
    Ok(())
}

/// Require `object[key]` to be a string holding something (see [`require_visible`]).
fn require_text(object: &serde_json::Map<String, Value>, key: &str, index: usize) -> Result<()> {
    require_visible(
        &format!("content[{index}].{key}"),
        require_string(object, key, index)?,
        "give the text it shows",
    )
}

/// The picture formats one placement takes: the extensions a path is checked against, and the
/// phrase every argument and refusal states them by.
struct PictureFormats {
    extensions: Vec<&'static str>,
    names: &'static str,
}

/// The formats a document or a presentation embeds, holding the WebP the picture tool writes.
fn embedded_pictures() -> PictureFormats {
    PictureFormats {
        extensions: RULES.image_extensions.iter().map(String::as_str).collect(),
        names: "PNG, JPEG or WebP",
    }
}

/// A PDF's own two encodings: the WebP the document writers take is refused here, before an
/// output is reserved.
fn pdf_pictures() -> PictureFormats {
    PictureFormats {
        extensions: vec!["png", "jpg", "jpeg"],
        names: "PNG or JPEG",
    }
}

/// Require a picture's path to carry an extension of `formats`; the bytes decide the kind, and
/// the kit reads them there.
fn ensure_picture(path: &Path, formats: &PictureFormats) -> Result<()> {
    if crate::util::has_extension(path, &formats.extensions) {
        Ok(())
    } else {
        anyhow::bail!(
            "usage: a picture must be {}, got {} — hint: convert the image and retry",
            formats.names,
            path.display()
        )
    }
}

enum Pages {
    /// Every page (`"all"`, an empty `pages`, or an absent one).
    All,
    /// 1-based page numbers, in the order the elements name them.
    Explicit(Vec<u32>),
}

impl Pages {
    /// The value the kit understands: `"all"`, or an array of 1-based numbers.
    #[must_use]
    fn kit_value(&self) -> Value {
        match self {
            Self::All => json!("all"),
            Self::Explicit(pages) => json!(pages),
        }
    }
}

/// The page selections a call names: absent, null or empty means every page, and an element is
/// `"all"` or a comma-separated list of `N` and `N-M` that [`parse_range`] reads. An `"all"`
/// element takes every page, so it cannot sit beside another.
fn page_selections(args: &Value) -> Result<Vec<String>> {
    // The element's own name is what a caller can fix, so the refusal is the array's.
    let selections = super::get_str_array(args, "pages")?;
    if selections.len() > 1
        && selections
            .iter()
            .any(|selection| selection.trim().eq_ignore_ascii_case("all"))
    {
        anyhow::bail!(
            "usage: an \"all\" selection takes every page, so it cannot sit beside another \
             selection — hint: name every page explicitly, or pass \"all\" alone"
        );
    }
    Ok(selections)
}

/// Parse `pages` into the pages the action acts on: the union of every element, in their
/// order; absent, null or empty means every page, and `"all"` stands alone.
fn opt_pages(args: &Value) -> Result<Pages> {
    let mut seen = HashSet::new();
    let mut pages = Vec::new();
    let mut all = false;
    for selection in page_selections(args)? {
        let selection = selection.trim();
        if selection.eq_ignore_ascii_case("all") {
            all = true;
            continue;
        }
        pages.extend(parse_range(selection, &mut seen)?);
    }
    if all || pages.is_empty() {
        Ok(Pages::All)
    } else {
        Ok(Pages::Explicit(pages))
    }
}

/// Parse one `pdf_split` selection per output file, in order: the list is required and
/// non-empty, so the element count is the attachment count. An `"all"` element stands alone,
/// and the kit resolves it against the document's own page count.
fn split_groups(args: &Value) -> Result<Vec<Value>> {
    let selections = page_selections(args)?;
    if selections.is_empty() {
        anyhow::bail!(
            "usage: missing required argument \"pages\" — hint: one page selection per output file, \
             e.g. [\"1-3\", \"5\"]"
        );
    }
    if selections.len() > MAX_SPLIT_PARTS {
        anyhow::bail!(
            "usage: {} output files is more than one call can produce (limit {MAX_SPLIT_PARTS}) — \
             hint: ask for fewer page selections, or wider ones",
            selections.len()
        );
    }
    // The `seen` set is the request's: a page named in two elements would be written into two
    // files, and the page cap is on the whole request.
    let mut seen = HashSet::new();
    let mut groups = Vec::with_capacity(selections.len());
    for selection in &selections {
        let selection = selection.trim();
        if selection.eq_ignore_ascii_case("all") {
            groups.push(json!("all"));
            continue;
        }
        groups.push(json!(parse_range(selection, &mut seen)?));
    }
    Ok(groups)
}

/// Parse a comma-separated range (`"1-3,5"`) into ascending 1-based pages, rejecting 0, a
/// reversed range and any page `seen` already claims — its length bounds the whole request.
fn parse_range(spec: &str, seen: &mut HashSet<u32>) -> Result<Vec<u32>> {
    let mut pages = Vec::new();
    for token in spec.split(',') {
        let token = token.trim();
        if token.is_empty() {
            anyhow::bail!(
                "usage: empty page range in \"{spec}\" — hint: write a selection like \
                 \"1-3,5\""
            );
        }
        let (start, end) = if let Some((start, end)) = token.split_once('-') {
            (parse_page(start)?, parse_page(end)?)
        } else {
            let page = parse_page(token)?;
            (page, page)
        };
        if end < start {
            anyhow::bail!(
                "usage: reversed page range \"{token}\" — hint: write it low-to-high, \
                 e.g. \"{end}-{start}\""
            );
        }
        for page in start..=end {
            if !seen.insert(page) {
                anyhow::bail!(
                    "usage: page {page} appears more than once — hint: list each page once"
                );
            }
            pages.push(page);
            if seen.len() > RULES.max_pages_per_request {
                anyhow::bail!(
                    "usage: too many pages requested (limit {})",
                    RULES.max_pages_per_request
                );
            }
        }
    }
    Ok(pages)
}

/// Parse one page number, rejecting 0.
fn parse_page(text: &str) -> Result<u32> {
    let page: u32 = text.trim().parse().map_err(|_| {
        anyhow::anyhow!(
            "usage: \"{text}\" is not a page number — hint: pages are 1-based, like \"3\" or \"1-3\""
        )
    })?;
    if page == 0 {
        anyhow::bail!("usage: page 0 does not exist — hint: the first page is 1");
    }
    Ok(page)
}

/// Copy a present numeric argument into the request, bounded on its magnitude (negative
/// positions are legal): pdf-lib writes the number straight through, so an unbounded one
/// becomes a file no reader can open.
fn set_number(request: &mut Value, args: &Value, key: &str) -> Result<()> {
    match args.get(key) {
        None | Some(Value::Null) => Ok(()),
        Some(v) => {
            let number = v
                .as_f64()
                .filter(|number| number.is_finite())
                .ok_or_else(|| super::wrong_type(key, "a number", v))?;
            if number.abs() > RULES.pdf_point_abs_max {
                anyhow::bail!(
                    "usage: \"{key}\" must be within ±{} points, got {number} — hint: \
                     give a position or size on the page",
                    RULES.pdf_point_abs_max
                );
            }
            request[key] = v.clone();
            Ok(())
        }
    }
}

/// [`set_number`] for a measure the writers lay out, where zero or a negative number is not a
/// size; the caller passes the span that governs it.
fn set_positive_number(request: &mut Value, args: &Value, key: &str, span: &Span) -> Result<()> {
    set_bounded_number(request, args, key, span, "give a size in points")
}

/// [`set_number`] for a value the shared rules bound, with the hint a refusal gives.
fn set_bounded_number(
    request: &mut Value,
    args: &Value,
    key: &str,
    span: &Span,
    hint: &str,
) -> Result<()> {
    set_number(request, args, key)?;
    if let Some(number) = request.get(key).and_then(Value::as_f64)
        && !span.contains(number)
    {
        anyhow::bail!(
            "usage: \"{key}\" must be {}, got {number} — hint: {hint}",
            span.bounds()
        );
    }
    Ok(())
}

/// The `area` a `pdf_crop` names: exactly `x`, `y`, `width` and `height`, fractions of the
/// visible area and together inside it. The format clips silently, so a larger area is
/// refused rather than answered with a smaller crop.
fn require_page_area(args: &Value) -> Result<Value> {
    let Some(area) = args.get("area").filter(|value| !value.is_null()) else {
        anyhow::bail!(
            "usage: missing required argument \"area\" — hint: name x, y, width and height as \
             fractions of the page's visible area"
        );
    };
    let Some(object) = area.as_object() else {
        return Err(super::wrong_type(
            "area",
            "an object of x, y, width and height",
            area,
        ));
    };
    let names = ["x", "y", "width", "height"];
    if let Some(unknown) = object.keys().find(|key| !names.contains(&key.as_str())) {
        anyhow::bail!(
            "usage: unknown area key \"{unknown}\" — hint: an area names exactly {}",
            listed(&names)
        );
    }
    let mut sides = [0f64; 4];
    for (side, slot) in names.iter().zip(&mut sides) {
        let Some(value) = object.get(*side) else {
            anyhow::bail!(
                "usage: \"area\" has no \"{side}\" — hint: name all four of {}",
                listed(&names)
            );
        };
        *slot = value
            .as_f64()
            .filter(|number| number.is_finite())
            .ok_or_else(|| super::wrong_type(&format!("area.{side}"), "a number", value))?;
        if !RULES.pdf_page_fraction.contains(*slot) {
            anyhow::bail!(
                "usage: \"area.{side}\" must be {}, got {} — hint: give a fraction of the page",
                RULES.pdf_page_fraction.bounds(),
                *slot
            );
        }
    }
    let [x, y, width, height] = sides;
    if width <= 0.0 || height <= 0.0 {
        anyhow::bail!(
            "usage: \"area\" must have a size, got {width}×{height} — hint: give a width and a \
             height above zero"
        );
    }
    // A tolerance, so a computed area (1/3 wide and 2/3 across) is not refused for the last bit
    // a double cannot hold — the kit applies the same slack.
    let slack = RULES.pdf_fraction_slack;
    if x + width > 1.0 + slack || y + height > 1.0 + slack {
        anyhow::bail!(
            "usage: \"area\" reaches past the page (x {x} + width {width}, y {y} + height \
             {height}) — hint: the format would silently clip it; name an area inside the page"
        );
    }
    Ok(area.clone())
}

/// Refuse an output directory that is a symlink: the reservations never follow a symlink for
/// the file itself, but a symlinked directory would take the whole call outside the workspace.
/// A command-line call cannot reach this — its destination is already canonicalized.
async fn refuse_symlinked_output(dir: &Path) -> Result<()> {
    if let Ok(meta) = tokio::fs::symlink_metadata(dir).await
        && meta.file_type().is_symlink()
    {
        anyhow::bail!(
            "forbidden: {} is a symlink — hint: document output needs a real directory there",
            dir.display()
        );
    }
    Ok(())
}

/// Reserve one output file per base with a create-new write of an empty file: the create *is* the
/// collision check (see [`crate::util::create_unique_file`]); a failure removes every reservation.
async fn reserve(dir: &Path, bases: &[String], ext: &str) -> Result<Vec<PathBuf>> {
    refuse_symlinked_output(dir).await?;
    tokio::fs::create_dir_all(dir)
        .await
        .with_context(|| format!("failed to create the output directory at {}", dir.display()))?;
    let mut reserved = Vec::with_capacity(bases.len());
    for base in bases {
        match reserve_one(dir, base, ext).await {
            Ok(path) => reserved.push(path),
            Err(e) => {
                remove_files(&reserved).await;
                return Err(e);
            }
        }
    }
    Ok(reserved)
}

/// Reserve one unique `base.<ext>` inside `dir` with a create-new write, dropping the handle.
async fn reserve_one(dir: &Path, base: &str, ext: &str) -> Result<PathBuf> {
    let name = format!("{base}.{ext}");
    let (_file, path) = crate::util::create_unique_file(dir, &name)
        .await
        .with_context(|| format!("failed to reserve an output file in {}", dir.display()))?;
    Ok(path)
}

/// Remove reserved files, best effort, so a call that produced nothing leaves nothing.
async fn remove_files(paths: &[PathBuf]) {
    for path in paths {
        let _ = tokio::fs::remove_file(path).await;
    }
}

/// [`FILE_MARKER`] around one produced file's absolute path — the line every producing
/// operation's answer carries.
pub(crate) fn file_marker(path: &Path) -> String {
    format!("{FILE_MARKER}{}]", path.to_string_lossy())
}

pub(crate) fn describe(prefix: &str, names: &[String], sizes: &[u64]) -> String {
    if names.len() == 1 {
        return format!(
            "{prefix} {} ({})",
            names[0],
            super::listing::human_readable_size(sizes[0])
        );
    }
    let list = names
        .iter()
        .zip(sizes)
        .map(|(name, size)| format!("{name} ({})", super::listing::human_readable_size(*size)))
        .collect::<Vec<_>>()
        .join(", ");
    format!("{prefix} {} files: {list}", names.len())
}

/// Strip a string to one safe file-name component: the directory part dropped, the reserved
/// punctuation neutralized and removed, and the result trimmed and length-capped.
#[must_use]
fn clean_component(raw: &str) -> String {
    // Any directory part is dropped: the tool chooses the directory, so a name must not steer it.
    let last = raw.rsplit(['/', '\\']).next().unwrap_or(raw);
    let cleaned: String = crate::util::neutralized_name(last)
        .chars()
        .filter(|c| !matches!(c, '<' | '>' | ':' | '"' | '|' | '?' | '*'))
        .collect();
    let capped: String = cleaned
        .trim_matches(['.', ' '])
        .chars()
        .take(MAX_BASE_CHARS)
        .collect();
    capped.trim_matches(['.', ' ']).to_string()
}

/// `name` without a trailing extension the tool appends itself.
#[must_use]
fn strip_output_extension(name: &str) -> &str {
    let Some((stem, ext)) = name.rsplit_once('.') else {
        return name;
    };
    if stem.is_empty() {
        return name;
    }
    // The tool appends the OOXML families' own extension and PDF; any other trailing
    // extension is the model's name and is kept.
    let appended =
        crate::ooxml::family_of(Path::new(name)).is_some() || ext.eq_ignore_ascii_case("pdf");
    if appended { stem } else { name }
}

/// Sanitize a `file_name` to one safe path component, falling back to the cleaned default when
/// the model's name leaves nothing usable; a trailing extension the tool appends is stripped.
#[must_use]
pub(crate) fn sanitize_base(raw: Option<&str>, fallback: &str) -> String {
    let candidate = raw.map_or_else(|| clean_component(fallback), clean_component);
    let preferred = strip_output_extension(&candidate);
    if preferred.is_empty() {
        clean_component(fallback)
    } else {
        preferred.to_string()
    }
}

#[must_use]
fn default_base(format: &str) -> &'static str {
    match format {
        "xlsx" => "spreadsheet",
        "pptx" => "presentation",
        _ => "document",
    }
}

/// The default base name for an action that edits an input: the input's stem plus what the
/// action did to it.
#[must_use]
fn input_base(input: &Path, suffix: &str) -> String {
    format!("{}_{suffix}", crate::util::name_stem(&file_name_of(input)))
}

/// The file-name spelling of a path, or the path's whole spelling when it has none.
#[must_use]
fn file_name_of(path: &Path) -> String {
    crate::util::file_name_or_path(&path.to_string_lossy()).to_string()
}

/// The extension a copy of `input` is written with: the input's own when its name is the family
/// its bytes are (a `.docm` copy stays one, macros and all), the family's name otherwise.
#[must_use]
fn copy_extension(input: &Path, family: crate::ooxml::Family) -> String {
    if crate::ooxml::family_of(input) == Some(family)
        && let Some(ext) = input.extension()
    {
        return ext.to_string_lossy().to_ascii_lowercase();
    }
    family.name().to_string()
}

#[must_use]
fn path_strings(paths: &[PathBuf]) -> Vec<String> {
    paths
        .iter()
        .map(|path| path.to_string_lossy().into_owned())
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::test::noisy_png;
    use crate::workspace::test_ws_named;
    use std::io::{Cursor, Write as _};

    /// The workspace-confined document tool — what every Assistant but the admin's gets.
    fn confined_document() -> DocumentTool {
        DocumentTool::new(PathAccess::Workspace)
    }

    fn workspace() -> (tempfile::TempDir, crate::Workspace) {
        // The kit is materialized under the storage root, so a test reaching it needs one
        // resolved; the shared test root is set once per process, and this is a no-op if set.
        let _ = crate::config::CONFIG.try_set_storage_root(crate::util::test::test_root().clone());
        let dir = tempfile::TempDir::new().expect("tempdir");
        // The workspace path must be canonical, as a stored one is: a raw `/tmp` spelling
        // diverges from macOS's `/private/tmp` and every read would be refused.
        let path = std::fs::canonicalize(dir.path()).expect("canonical workspace");
        let ws = test_ws_named(&path.to_string_lossy(), "document-test");
        (dir, ws)
    }

    fn add_bytes(zip: &mut zip::ZipWriter<Cursor<Vec<u8>>>, name: &str, body: &[u8]) {
        zip.start_file(name, zip::write::SimpleFileOptions::default())
            .expect("start part");
        zip.write_all(body).expect("write part");
    }

    fn write_fixture(ws: &Workspace, name: &str, bytes: &[u8]) -> PathBuf {
        let path = ws.as_path().join(name);
        std::fs::write(&path, bytes).expect("write fixture");
        path
    }

    /// A package whose only part is `part`: the family verdict reads the container's own entry
    /// names.
    fn package_with(part: &str) -> Vec<u8> {
        let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
        add_bytes(&mut zip, part, b"<x/>");
        zip.finish().expect("finish package").into_inner()
    }

    /// A genuinely encrypted package: a CFB container declaring both streams genuine encryption
    /// writes.
    fn encrypted_package() -> Vec<u8> {
        crate::legacy::test_fixtures::cfb(&[
            ("EncryptionInfo", b"info".as_slice()),
            ("EncryptedPackage", b"data".as_slice()),
        ])
    }

    /// A legacy `.doc`: a CFB container declaring the old Word stream.
    fn legacy_doc() -> Vec<u8> {
        crate::legacy::test_fixtures::cfb(&[("WordDocument", b"legacy word".as_slice())])
    }

    /// A password-protected legacy `.doc`: [`legacy_doc`]'s container with the reader's own
    /// encrypted fixture, whose FIB sets `fEncrypted` — a flag only the reader can see.
    fn encrypted_legacy_doc() -> Vec<u8> {
        crate::legacy::test_fixtures::doc_fixture("secret", &[], true)
    }

    /// A one-page PDF with a single fillable field named `name`; the kit authors no form, so the
    /// fixture is written here.
    fn fillable_pdf() -> Vec<u8> {
        crate::document::test_fixtures::assemble_pdf(&[
            b"<< /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] /DA (/Helv 0 Tf 0 g) >> >>"
                .to_vec(),
            b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec(),
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] \
              /Resources << /Font << /Helv 4 0 R >> >> /Annots [5 0 R] >>"
                .to_vec(),
            b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec(),
            b"<< /Type /Annot /Subtype /Widget /FT /Tx /T (name) /Rect [72 700 300 730] \
              /P 3 0 R /V () /DA (/Helv 12 Tf 0 g) >>"
                .to_vec(),
        ])
    }

    /// A block only a Word document can hold is refused for every other format, before an
    /// output is reserved.
    #[tokio::test]
    async fn a_docx_only_block_is_refused_for_another_format() {
        let (_dir, ws) = workspace();
        for (format, block) in [
            ("pptx", json!({ "type": "page_break" })),
            ("pdf", json!({ "type": "contents" })),
            (
                "pptx",
                json!({ "type": "link", "text": "x", "url": "https://example.com" }),
            ),
            (
                "pdf",
                json!({ "type": "paragraph", "text": "x", "footnote": "note" }),
            ),
        ] {
            let err = resolve_content(
                &ws,
                &json!({ "content": [block.clone()] }),
                format,
                PathAccess::Workspace,
            )
            .await
            .expect_err("a block only a .docx holds must be refused");
            assert!(
                err.to_string().contains(".docx"),
                "the refusal must name the format it belongs to: {err}"
            );
        }
    }

    /// A link's address follows an allowlist of schemes, and the document carries the address the
    /// parse produced rather than the raw string.
    #[tokio::test]
    async fn a_link_address_must_be_followable() {
        let (_dir, ws) = workspace();
        let err = resolve_content(
            &ws,
            &json!({ "content": [{ "type": "link", "text": "x", "url": "example.com" }] }),
            "docx",
            PathAccess::Workspace,
        )
        .await
        .expect_err("an address without a scheme cannot be followed");
        assert!(
            err.to_string().contains("absolute URL"),
            "the refusal must say what a link's address is: {err}"
        );
        let err = resolve_content(
            &ws,
            &json!({ "content": [{ "type": "link", "text": "x", "url": "javascript:alert(1)" }] }),
            "docx",
            PathAccess::Workspace,
        )
        .await
        .expect_err("a scheme outside the allowlist must be refused");
        assert!(
            err.to_string()
                .contains("must be an http, https, mailto or tel address"),
            "the refusal must name the schemes a link may use: {err}"
        );
        // Parsing trims the space around an address and skips an embedded tab or newline, so the
        // block carries the parsed one.
        let resolved = resolve_content(
            &ws,
            &json!({ "content": [{ "type": "link", "text": "x", "url": " https://exa\nmple.com " }] }),
            "docx",
            PathAccess::Workspace,
        )
        .await
        .expect("a padded http address is the same address");
        assert_eq!(
            resolved[0]["url"],
            json!("https://example.com/"),
            "the document would state an address other than the one that parses: {resolved}"
        );
    }

    /// A crop's area is checked at the boundary, so the format never answers with a smaller crop
    /// than was asked: an area past the page, with no size or with a missing side is refused.
    #[tokio::test]
    async fn pdf_crop_refuses_an_area_it_cannot_crop() {
        let (_dir, ws) = workspace();
        // The check runs before the file is opened as a PDF, so a stub is enough.
        let source = ws.as_path().join("stub.pdf");
        std::fs::write(&source, b"%PDF-1.4\n").expect("write stub pdf");
        for (area, expected) in [
            (
                json!({ "x": 0.5, "y": 0.0, "width": 0.6, "height": 1.0 }),
                "reaches past the page",
            ),
            (
                json!({ "x": 0.0, "y": 0.0, "width": 0.0, "height": 1.0 }),
                "must have a size",
            ),
            (
                json!({ "x": 0.0, "y": 0.0, "width": 1.0, "height": 1.0, "top": 0.0 }),
                "unknown area key \"top\"",
            ),
            (
                json!({ "x": 0.0, "y": 0.0, "width": 1.0 }),
                "\"area\" has no \"height\"",
            ),
            (Value::Null, "missing required argument \"area\""),
        ] {
            let mut args = json!({
                "action": "pdf_crop", "path": source.to_string_lossy(),
            });
            if !area.is_null() {
                args["area"] = area;
            }
            let err = confined_document()
                .execute(&ws, args)
                .await
                .expect_err("an area the tool cannot crop must be refused");
            let message = err.to_string();
            assert!(message.starts_with("usage:"), "got: {message}");
            assert!(
                message.contains(expected),
                "expected {expected:?}, got: {message}"
            );
        }
    }

    /// A resize names both sides: one side alone is not "keep the page's own".
    #[tokio::test]
    async fn pdf_resize_refuses_a_single_side() {
        let (_dir, ws) = workspace();
        let source = ws.as_path().join("stub.pdf");
        std::fs::write(&source, b"%PDF-1.4\n").expect("write stub pdf");
        for side in ["width", "height"] {
            let mut args = json!({
                "action": "pdf_resize", "path": source.to_string_lossy(),
            });
            args[side] = json!(300);
            let err = confined_document()
                .execute(&ws, args)
                .await
                .expect_err("a resize with one side must be refused");
            let message = err.to_string();
            assert!(message.starts_with("usage:"), "got: {message}");
            assert!(
                message.contains("a resize names both sides"),
                "got: {message}"
            );
        }
    }

    /// A document's input follows the caller's access: the admin's from anywhere, a guest's
    /// inside its own workspace.
    #[tokio::test]
    async fn inputs_follow_the_callers_access() {
        let (dir, ws) = workspace();
        let outside = tempfile::TempDir::new().unwrap();
        let sample = outside.path().join("sample.docx");
        std::fs::write(&sample, b"a sample the kit would take").unwrap();
        let path = sample.to_string_lossy().to_string();

        let err = resolve_input(&ws, &path, PathAccess::Workspace)
            .await
            .expect_err("a guest's input must stay inside its workspace");
        assert!(
            err.to_string().contains("outside the workspace"),
            "the refusal must name the boundary: {err}"
        );
        resolve_input(&ws, &path, PathAccess::Unrestricted)
            .await
            .expect("the admin's input may be read from anywhere");

        drop((dir, outside));
    }

    /// An encrypted legacy `.doc` is the password verdict, not the old formats' sentence: only
    /// the family's own reader can see the password, so the classifier asks it.
    #[tokio::test]
    async fn a_legacy_encrypted_document_is_the_password_verdict() {
        let (_dir, ws) = workspace();
        let secret = write_fixture(&ws, "secret.doc", &encrypted_legacy_doc());

        let err = confined_document()
            .execute(
                &ws,
                json!({
                    "action": "docx_edit", "path": secret.to_string_lossy(),
                    "edits": [{ "op": "replace_text", "find": "x", "replace": "y" }],
                }),
            )
            .await
            .expect_err("an encrypted old document cannot be edited");
        let message = err.to_string();
        assert!(
            message.contains("password-protected"),
            "the edit refusal must give the read path's verdict: {message}"
        );
        assert!(
            !message.contains("save it as one of the OOXML families"),
            "a password is not a reason to convert the file: {message}"
        );

        let err = confined_document()
            .execute(
                &ws,
                json!({
                    "action": "fill_template", "file_name": "copy",
                    "path": secret.to_string_lossy(), "values": { "name": "Имя" },
                }),
            )
            .await
            .expect_err("an encrypted old document cannot be filled");
        let message = err.to_string();
        assert!(
            message.contains("password-protected"),
            "the fill refusal must give the read path's verdict: {message}"
        );
        assert!(
            message.contains("secret.doc"),
            "the refusal must name the file: {message}"
        );
    }

    /// A PDF action given an encrypted input is owed the password verdict in its own voice, with
    /// a PDF as the unprotected copy to save.
    #[tokio::test]
    async fn a_pdf_action_tells_an_encrypted_input_to_convert_it_to_a_pdf() {
        let (_dir, ws) = workspace();
        for (name, bytes) in [
            ("package.docx", encrypted_package()),
            ("secret.doc", encrypted_legacy_doc()),
        ] {
            let path = write_fixture(&ws, name, &bytes);
            let err = confined_document()
                .execute(
                    &ws,
                    json!({
                        "action": "pdf_rotate", "path": path.to_string_lossy(), "degrees": 90,
                    }),
                )
                .await
                .expect_err("an encrypted input cannot be read as a PDF");
            let message = err.to_string();
            assert!(
                message.contains("password-protected"),
                "{name}: the refusal must give the read path's verdict: {message}"
            );
            assert!(
                message.contains("and convert it to a PDF"),
                "{name}: a PDF action's password refusal must ask for a PDF: {message}"
            );
        }
    }

    /// Every action the schema advertises is dispatched: a listed name absent from the `match`
    /// would answer "unknown action" to a call the model was told to make.
    #[tokio::test]
    async fn every_advertised_action_is_dispatched() {
        let (_dir, ws) = workspace();
        for action in ACTIONS {
            let error = confined_document()
                .execute(&ws, json!({ "action": action }))
                .await
                .expect_err("an action with no arguments cannot succeed");
            let message = format!("{error:#}");
            assert!(!message.contains("unknown action"), "{action}: {message}");
        }
    }

    /// The whole schema is checked at the boundary: every shape the writers cannot render is
    /// refused with its position, so nothing reaches the kit as `[object Object]` or a `NaN`.
    #[tokio::test]
    #[expect(clippy::too_many_lines)] // reason: one boundary case per argument shape
    async fn the_content_and_sheet_shapes_are_checked_at_the_boundary() {
        let (_dir, ws) = workspace();

        let content = [
            // A table needs something to lay out, and the presentation writer rejects an empty
            // one outright.
            (
                json!({ "content": [{ "type": "table", "rows": [] }] }),
                "no rows and no headers",
            ),
            (
                json!({ "content": [{ "type": "table", "headers": [], "rows": [] }] }),
                "no rows and no headers",
            ),
            // A row, a cell, a header or a bullet the writers cannot render: a structure reaches
            // the document as `[object Object]`.
            (
                json!({ "content": [{ "type": "table", "rows": ["not a row"] }] }),
                "content[0].rows[0]",
            ),
            (
                json!({ "content": [{ "type": "table", "rows": [[{ "a": 1 }]] }] }),
                "content[0].rows[0][0]",
            ),
            (
                json!({ "content": [{ "type": "table", "headers": [{ "a": 1 }], "rows": [["a"]] }] }),
                "content[0].headers[0]",
            ),
            (
                json!({ "content": [{ "type": "list", "items": [{ "a": 1 }] }] }),
                "content[0].items[0]",
            ),
            // A heading level the writers do not have — refused, not clamped to one they do.
            (
                json!({ "content": [{ "type": "heading", "text": "h", "level": 7 }] }),
                "level must be 1, 2 or 3",
            ),
            (
                json!({ "content": [{ "type": "heading", "text": "h", "level": "2" }] }),
                "level must be 1, 2 or 3",
            ),
            // A list's `ordered` decides a rendering only a boolean can pick.
            (
                json!({ "content": [{ "type": "list", "items": ["a"], "ordered": "yes" }] }),
                "content[0].ordered",
            ),
            // A size the layout has no meaning for.
            (
                json!({ "content": [{ "type": "image", "image": "x.png", "width": { "a": 1 } }] }),
                "content[0].width",
            ),
            (
                json!({ "content": [{ "type": "image", "image": "x.png", "height": -1 }] }),
                "content[0].height",
            ),
            (
                json!({ "content": [{ "type": "image", "image": "x.png", "width": 1e30 }] }),
                "content[0].width",
            ),
        ];
        for (args, expected) in content {
            let err = resolve_content(&ws, &args, "docx", PathAccess::Workspace)
                .await
                .expect_err("a shape the writers cannot render");
            assert!(
                err.to_string().contains(expected),
                "expected the refusal to name {expected}: {err}"
            );
        }

        // The same for a workbook's sheets and cells.
        let long_name = "a".repeat(RULES.sheet_name_max + 1);
        let sheets = [
            (
                json!({ "sheets": [{ "name": 5, "rows": [["a"]] }] }),
                "sheets[0].name",
            ),
            // A name the writer cannot hold: past the cap, holding a forbidden character, or
            // shared with an earlier sheet ignoring case.
            (
                json!({ "sheets": [{ "name": long_name, "rows": [["a"]] }] }),
                "sheets[0].name",
            ),
            (
                json!({ "sheets": [{ "name": "bad:name", "rows": [["a"]] }] }),
                "sheets[0].name",
            ),
            (
                json!({ "sheets": [
                    { "name": "Trips", "rows": [["a"]] },
                    { "name": "trips", "rows": [["b"]] },
                ] }),
                "sheets[1].name",
            ),
            (
                json!({ "sheets": [{ "rows": [[null]] }] }),
                "sheets[0].rows[0][0]",
            ),
            (
                json!({ "sheets": [{ "rows": [[{ "b": 1 }]] }] }),
                "sheets[0].rows[0][0]",
            ),
            (
                json!({ "sheets": [{ "rows": [[{ "formula": "  " }]] }] }),
                "sheets[0].rows[0][0]",
            ),
            // A formula that says nothing: the leading `=` is not a formula.
            (
                json!({ "sheets": [{ "rows": [[{ "formula": "=" }]] }] }),
                "sheets[0].rows[0][0]",
            ),
            // A second `=` survives normalization and would land in the cell's `<f>` as text:
            // refused.
            (
                json!({ "sheets": [{ "rows": [[{ "formula": "==SUM(A1:A2)" }]] }] }),
                "sheets[0].rows[0][0]",
            ),
            (json!({ "sheets": [[["a"]]] }), "sheets[0]"),
        ];
        for (args, expected) in sheets {
            let err = resolve_sheets(&args).expect_err("a shape the writer cannot write");
            assert!(
                err.to_string().contains(expected),
                "expected the refusal to name {expected}: {err}"
            );
        }

        // `headers` stays optional, null counts as absent, and a well-formed table and sheet pass.
        let good = json!({ "content": [{ "type": "table", "rows": [["a", "b"]] }] });
        assert!(
            resolve_content(&ws, &good, "docx", PathAccess::Workspace)
                .await
                .is_ok()
        );
        let good =
            json!({ "content": [{ "type": "table", "headers": null, "rows": [["a", "b"]] }] });
        assert!(
            resolve_content(&ws, &good, "docx", PathAccess::Workspace)
                .await
                .is_ok()
        );
        let headers_only = json!({ "content": [{ "type": "table", "headers": ["a"] }] });
        assert!(
            resolve_content(&ws, &headers_only, "docx", PathAccess::Workspace)
                .await
                .is_ok()
        );
        let good = json!({ "sheets": [{ "name": "Лист", "rows": [["a", 1, true, { "formula": "=SUM(A1:A2)" }]] }] });
        let normalized = resolve_sheets(&good).expect("a well-formed sheet");
        assert_eq!(
            normalized[0]["rows"][0][3],
            json!({ "formula": "SUM(A1:A2)" }),
            "the formula must reach the request without its leading `=`"
        );
    }

    /// Every argument of an action that produces a file is checked before an output is reserved,
    /// so a refused call leaves nothing behind — and a file that is not the image it is named as
    /// is refused.
    #[tokio::test]
    #[expect(clippy::too_many_lines)] // one case per argument, all refused before anything is reserved
    async fn the_arguments_are_checked_before_an_output_is_reserved() {
        let (_dir, ws) = workspace();
        let image = ws.as_path().join("picture.png");
        std::fs::write(&image, noisy_png(4, 4)).expect("write png");
        let notes = ws.as_path().join("notes.txt");
        std::fs::write(&notes, b"not an image").expect("write notes");
        let document = ws.as_path().join("document.pdf");
        std::fs::write(&document, fillable_pdf()).expect("write pdf");
        let merged = ws.as_path().join("merged.pdf");
        std::fs::write(&merged, fillable_pdf()).expect("write pdf");
        let path = document.to_string_lossy();
        // An input the kit loads whole is bounded: an oversized one must be refused on its own
        // merits rather than as a killed run. Sparse, so the test costs no disk.
        let huge = ws.as_path().join("huge.pdf");
        std::fs::File::create(&huge)
            .and_then(|file| file.set_len(crate::util::FILE_MAX_BYTES + 1))
            .expect("a sparse oversized input");
        // A merge holds every input at once, so the whole set is bounded too: five files, each
        // within the per-file limit and together over what one call may load. Sparse.
        let mut batch = Vec::new();
        for index in 0..5 {
            let member = ws.as_path().join(format!("batch{index}.pdf"));
            std::fs::File::create(&member)
                .and_then(|file| file.set_len(crate::util::FILE_MAX_BYTES))
                .expect("a sparse input at the per-file limit");
            batch.push(member.to_string_lossy().into_owned());
        }

        let calls = [
            (
                json!({ "action": "create", "format": "docx", "file_name": 5,
                        "content": [{ "type": "paragraph", "text": "x" }] }),
                "file_name",
            ),
            // The argument the chosen format does not use is named, never dropped in silence.
            (
                json!({ "action": "create", "format": "xlsx",
                        "sheets": [{ "rows": [["a"]] }],
                        "content": [{ "type": "paragraph", "text": "x" }] }),
                "\"content\" is not used for format \"xlsx\"",
            ),
            (
                json!({ "action": "create", "format": "docx",
                        "content": [{ "type": "paragraph", "text": "x" }],
                        "sheets": [{ "rows": [["a"]] }] }),
                "\"sheets\" is not used for format \"docx\"",
            ),
            (
                json!({ "action": "pdf_text", "path": path, "text": "x", "color": "red" }),
                "color",
            ),
            (
                json!({ "action": "pdf_text", "path": path, "text": "x", "size": 0 }),
                "size",
            ),
            // A number no page can carry: pdf-lib writes it through, and the caller would receive
            // a file nothing can open as a success.
            (
                json!({ "action": "pdf_text", "path": path, "text": "x", "size": 1e300 }),
                "within ±20000",
            ),
            (
                json!({ "action": "pdf_image", "path": path, "image": image.to_string_lossy(),
                        "x": -1e300 }),
                "within ±20000",
            ),
            // A wrong-typed `flatten` is read before the output is reserved.
            (
                json!({ "action": "pdf_form_fill", "path": path, "values": { "name": "x" },
                        "flatten": "yes" }),
                "flatten",
            ),
            (
                json!({ "action": "pdf_image", "path": path,
                        "image": image.to_string_lossy(), "width": -5 }),
                "width",
            ),
            (
                json!({ "action": "pdf_image", "path": path, "image": notes.to_string_lossy() }),
                "PNG or JPEG",
            ),
            (
                json!({ "action": "pdf_rotate", "path": path, "degrees": 45 }),
                "multiple of 90",
            ),
            // A whole turn (or zero) is refused: the pages would come back unchanged.
            (
                json!({ "action": "pdf_rotate", "path": path, "degrees": 360 }),
                "would leave the pages as they are",
            ),
            // A form filled with nothing says nothing.
            (
                json!({ "action": "pdf_form_fill", "path": path, "values": {} }),
                "empty",
            ),
            (
                json!({ "action": "pdf_rotate", "path": huge.to_string_lossy(), "degrees": 90 }),
                "MB limit",
            ),
            (
                json!({ "action": "pdf_rotate", "path": path, "degrees": 90, "pages": ["0"] }),
                "page 0 does not exist",
            ),
            (
                json!({ "action": "pdf_merge", "paths": [merged.to_string_lossy()] }),
                "at least 2",
            ),
            (
                json!({ "action": "pdf_merge",
                        "paths": (0..=MAX_MERGE_INPUTS).map(|index| format!("part{index}.pdf")).collect::<Vec<_>>() }),
                "limit 50",
            ),
            (
                json!({ "action": "pdf_merge", "paths": batch }),
                "more than one merge takes",
            ),
            (
                json!({ "action": "pdf_split", "path": path,
                        "pages": (1..=MAX_SPLIT_PARTS + 1).map(|n| n.to_string()).collect::<Vec<_>>() }),
                "limit 50",
            ),
            // The page cap is on the pages the request names, not on the document's length: a
            // one-page file still refuses a selection naming more pages than one call takes.
            (
                json!({ "action": "pdf_split", "path": path,
                        "pages": [format!("1-{}", RULES.max_pages_per_request + 1)] }),
                "limit 10000",
            ),
            (
                json!({ "action": "pdf_split", "path": path, "pages": ["3-1"] }),
                "reversed",
            ),
        ];
        for (args, expected) in calls {
            let err = confined_document()
                .execute(&ws, args)
                .await
                .expect_err("a call the tool cannot carry out");
            assert!(
                err.to_string().contains(expected),
                "expected the refusal to name {expected}: {err}"
            );
        }
        let left = std::fs::read_dir(ws.as_path().join(GENERATED_DIR))
            .map_or(0, std::iter::Iterator::count);
        assert_eq!(left, 0, "a refused call left an output behind");
    }

    /// A metadata date is canonicalised to the PDF's own spelling: a calendar date is midnight
    /// UTC, `T` separates the time, and a zero offset is written `Z`.
    #[test]
    fn pdf_dates_are_written_in_the_pdfs_own_spelling() {
        assert_eq!(
            pdf_date("2024-05-17").expect("a calendar date"),
            "D:20240517000000Z"
        );
        assert_eq!(
            pdf_date("2024-05-17T10:30").expect("a date and minutes"),
            "D:20240517103000Z"
        );
        assert_eq!(
            pdf_date("2024-05-17T10:30:15Z").expect("a date, seconds and Z"),
            "D:20240517103015Z"
        );
        assert_eq!(
            pdf_date("2024-05-17T10:30:00+03:00").expect("a positive offset"),
            "D:20240517103000+03'00'"
        );
        assert_eq!(pdf_date("").expect("an empty string clears"), "");
        for bad in [
            "2024-13-01",
            "2024-05-17T10:30:00 o'clock",
            "2024-05-17 10:30:15Z",
            "2024-05-17T10:30:00-0530",
        ] {
            let err = pdf_date(bad).expect_err("a bad date must be refused");
            let message = err.to_string();
            assert!(message.starts_with("usage:"), "got: {message}");
            assert!(
                message.contains(bad),
                "the refusal must echo {bad:?}: {message}"
            );
            assert!(
                message.contains("YYYY-MM-DD"),
                "the refusal must spell the accepted form: {message}"
            );
        }
    }

    /// A workspace-only tool refuses a path outside the workspace.
    #[tokio::test]
    async fn refuses_a_sample_outside_the_workspace() {
        let (_dir, ws) = workspace();
        let outside = tempfile::NamedTempFile::new().expect("temp file");
        let err = confined_document()
            .execute(
                &ws,
                json!({
                    "action": "fill_template",
                    "path": outside.path().to_string_lossy(),
                    "values": {},
                }),
            )
            .await
            .expect_err("a sample outside the workspace must be refused");
        assert!(
            err.to_string().contains("outside the workspace"),
            "got: {err}"
        );
    }

    /// A `generated` that is a symlink would take every output write wherever it points, so the
    /// reservation refuses it before it creates anything.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_symlinked_generated_directory_is_refused() {
        let (dir, ws) = workspace();
        let elsewhere = dir.path().join("elsewhere");
        std::fs::create_dir_all(&elsewhere).expect("target directory");
        let generated = ws.as_path().join("generated");
        std::os::unix::fs::symlink(&elsewhere, &generated).expect("symlink generated");

        let err = reserve(&generated, &["report".to_string()], "docx")
            .await
            .expect_err("a symlinked generated directory must be refused");
        assert!(err.to_string().starts_with("forbidden:"), "got: {err}");
        assert!(
            std::fs::read_dir(&elsewhere)
                .expect("target directory")
                .next()
                .is_none(),
            "nothing may be written through the symlink"
        );
    }

    /// The generated directory's entry count: how a test proves a refused call left no output
    /// behind.
    fn generated_count(ws: &Workspace) -> usize {
        std::fs::read_dir(ws.as_path().join(GENERATED_DIR)).map_or(0, std::iter::Iterator::count)
    }

    /// The three edit actions address a file's own FAMILY, from its bytes and never its name:
    /// another family, a PDF, no document and an old `.doc`/`.xls`/`.ppt` are each refused for
    /// what they really are.
    #[tokio::test]
    async fn editing_refuses_an_input_of_another_family() {
        let (_dir, ws) = workspace();
        let legacy = "an old .doc/.xls/.ppt file is read but never edited";
        let cases = [
            // The input's own bytes, not its name, are what each action takes.
            ("report.doc", legacy_doc(), "docx_edit", legacy),
            ("sheet.xls", legacy_doc(), "xlsx_edit", legacy),
            ("deck.ppt", legacy_doc(), "pptx_edit", legacy),
            (
                "paper.pdf",
                fillable_pdf(),
                "docx_edit",
                "edits only a .docx/.docm file",
            ),
            (
                "paper.pdf",
                fillable_pdf(),
                "xlsx_edit",
                "edits only a .xlsx/.xlsm file",
            ),
            (
                "paper.pdf",
                fillable_pdf(),
                "pptx_edit",
                "edits only a .pptx/.pptm file",
            ),
            // A real package under another family's name is refused as the family it really
            // holds, and pointed at the action that edits it.
            (
                "report.docx",
                package_with("xl/workbook.xml"),
                "docx_edit",
                "which is really an .xlsx package",
            ),
            (
                "sheet.xlsx",
                package_with("ppt/presentation.xml"),
                "xlsx_edit",
                "which is really a .pptx package",
            ),
            // A container that is no document is not called one.
            (
                "notes.msg",
                crate::legacy::test_fixtures::cfb(&[("__properties_version1.0", b"outlook")]),
                "docx_edit",
                "which is not a Word, Excel, PowerPoint or PDF document",
            ),
        ];
        for (name, bytes, action, expected) in cases {
            std::fs::write(ws.as_path().join(name), &bytes).expect("write input");
            let err = confined_document()
                .execute(
                    &ws,
                    json!({
                        "action": action, "path": name,
                        "edits": [{ "op": "replace_text", "find": "x", "replace": "y" }],
                    }),
                )
                .await
                .expect_err("a wrong-family input must be refused");
            assert!(
                err.to_string().contains(expected),
                "{action} on {name}: expected {expected:?}, got {err}"
            );
        }
        assert_eq!(generated_count(&ws), 0, "a refused call left an output");

        // An encrypted package is the password verdict whatever its name says — and an
        // old-format document under that same name is not.
        for (name, bytes, expected) in [
            ("encrypted.docx", encrypted_package(), "password-protected"),
            ("container.doc", legacy_doc(), legacy),
        ] {
            std::fs::write(ws.as_path().join(name), &bytes).expect("write input");
            let err = confined_document()
                .execute(
                    &ws,
                    json!({
                        "action": "docx_edit", "path": name,
                        "edits": [{ "op": "replace_text", "find": "x", "replace": "y" }],
                    }),
                )
                .await
                .expect_err("a container is refused for what it really holds");
            assert!(
                err.to_string().contains(expected),
                "{name}: expected {expected:?}, got {err}"
            );
        }
        assert_eq!(generated_count(&ws), 0, "a refused call left an output");
    }

    /// A file's name is not its format: a valid PDF under a `.txt` name is taken by a `pdf_*`
    /// action, and a file that is not a PDF is refused naming what it holds.
    #[tokio::test]
    async fn a_pdf_is_taken_under_any_name() {
        let (_dir, ws) = workspace();
        let renamed = write_fixture(&ws, "notes.txt", &fillable_pdf());
        require_pdf(&renamed)
            .await
            .expect("a PDF under any name is a PDF");

        let workbook = write_fixture(&ws, "sheet.txt", &package_with("xl/workbook.xml"));
        let err = require_pdf(&workbook)
            .await
            .expect_err("a workbook is not a PDF, whatever it is called");
        assert!(
            err.to_string().contains("which is really an .xlsx package"),
            "got: {err}"
        );

        // The renamed PDF meets the managed runtime, never a refusal about its format.
        if let Err(e) = confined_document()
            .execute(
                &ws,
                json!({ "action": "pdf_text", "path": "notes.txt", "text": "x" }),
            )
            .await
        {
            assert!(!e.to_string().contains("must be a PDF"), "got: {e}");
        }
    }

    /// `pages` is one argument with one grammar for every PDF action that takes it: an array of
    /// selections, whose elements are the files a split cuts and whose union the acting actions
    /// use. A page named twice anywhere is refused before the kit is spawned.
    #[tokio::test]
    async fn the_pages_argument_is_an_array_of_selections() {
        let (_dir, ws) = workspace();
        assert_eq!(
            split_groups(&json!({ "pages": ["1-3", "5"] })).expect("two selections"),
            vec![json!([1, 2, 3]), json!([5])],
            "one output file per element, in order"
        );
        // `"all"` is the same element an acting action takes, and the kit resolves it against
        // the document's own page count.
        assert_eq!(
            split_groups(&json!({ "pages": ["all"] })).expect("one file, every page"),
            vec![json!("all")],
            "an element naming every page is passed through unexpanded"
        );
        assert_eq!(
            opt_pages(&json!({ "pages": ["1-3", "5"] }))
                .expect("a selection list")
                .kit_value(),
            json!([1, 2, 3, 5]),
            "the union of the elements is what the action acts on"
        );
        for pages in [
            json!({}),
            json!({ "pages": null }),
            json!({ "pages": [] }),
            json!({ "pages": ["all"] }),
        ] {
            assert_eq!(
                opt_pages(&pages).expect("every page").kit_value(),
                json!("all"),
                "{pages} names no page to narrow the call to"
            );
        }
        // An empty element names no page: a blank one is refused rather than silently widening
        // the call.
        for pages in [json!({ "pages": [""] }), json!({ "pages": ["1-3", ""] })] {
            let err = opt_pages(&pages)
                .map(|pages| pages.kit_value())
                .expect_err("a blank page element must be refused");
            assert!(
                err.to_string().contains("empty page range"),
                "{pages}: got {err}"
            );
        }
        let duplicate = split_groups(&json!({ "pages": ["1", "2", "1"] }))
            .expect_err("a page named twice is refused");
        assert!(
            duplicate.to_string().contains("appears more than once"),
            "got: {duplicate}"
        );
        // An `"all"` element stands alone: beside another it would name the same page twice.
        for pages in [
            json!({ "pages": ["all", "1"] }),
            json!({ "pages": ["1-3", "all"] }),
            json!({ "pages": ["all", "all"] }),
        ] {
            let err = split_groups(&pages).expect_err("an \"all\" element stands alone");
            assert!(
                err.to_string()
                    .contains("cannot sit beside another selection"),
                "split {pages}: got {err}"
            );
            let err = opt_pages(&pages)
                .map(|pages| pages.kit_value())
                .expect_err("an \"all\" element stands alone");
            assert!(
                err.to_string()
                    .contains("cannot sit beside another selection"),
                "{pages}: got {err}"
            );
        }

        let pdf = write_fixture(&ws, "base.pdf", &fillable_pdf());
        let err = confined_document()
            .execute(
                &ws,
                json!({ "action": "pdf_rotate", "path": pdf.to_string_lossy(),
                        "degrees": 90, "pages": ["1-2", "2"] }),
            )
            .await
            .expect_err("a page named twice is refused");
        assert!(
            err.to_string().contains("appears more than once"),
            "got: {err}"
        );
        assert_eq!(generated_count(&ws), 0, "a refused call left an output");
    }

    /// Both call shapes are accepted: the flat one, the nested one the schema describes, and the
    /// chrome-shaped one; anything else is refused with the shape the caller was expected to use.
    #[tokio::test]
    async fn a_nested_action_call_is_dispatched_like_a_flat_one() {
        let (_dir, ws) = workspace();
        assert_eq!(
            normalize_call(&json!({
                "action": { "pdf_rotate": { "path": "a.pdf", "degrees": 90 } },
                "file_name": "turned",
            }))
            .expect("the nested shape"),
            json!({
                "action": "pdf_rotate", "path": "a.pdf", "degrees": 90, "file_name": "turned"
            })
        );
        assert_eq!(
            normalize_call(&json!({ "action": "pdf_rotate", "pdf_rotate": { "degrees": 90 } }))
                .expect("the chrome shape"),
            json!({ "action": "pdf_rotate", "degrees": 90 })
        );
        // An argument stated beside the action object is the caller's: kept rather than dropped,
        // so a nested call cannot widen into a call the caller did not make.
        assert_eq!(
            normalize_call(&json!({
                "action": { "pdf_text": { "path": "a.pdf", "text": "x" } },
                "pages": ["1"],
            }))
            .expect("the nested shape with a selection beside it"),
            json!({ "action": "pdf_text", "path": "a.pdf", "text": "x", "pages": ["1"] })
        );
        for bad in [
            json!({ "action": 5 }),
            json!({ "action": ["pdf_rotate"] }),
            json!({ "action": { "a": 1, "b": 2 } }),
            json!({ "action": {} }),
        ] {
            let err = normalize_call(&bad).expect_err("a shape the tool cannot read");
            assert!(err.to_string().contains("\"action\""), "{bad}: {err}");
        }

        // Dispatch follows the normalisation: the nested call meets the same refusal the flat one
        // does.
        let pdf = write_fixture(&ws, "base.pdf", &fillable_pdf());
        let err = confined_document()
            .execute(
                &ws,
                json!({
                    "action": { "pdf_rotate": { "path": pdf.to_string_lossy(), "degrees": 45 } }
                }),
            )
            .await
            .expect_err("45 degrees is not a multiple of 90");
        assert!(err.to_string().contains("multiple of 90"), "got: {err}");
    }

    /// Every edit shape the kit would fail on is refused at the boundary, naming the offending
    /// edit and field, before an output is reserved.
    #[tokio::test]
    #[expect(clippy::too_many_lines)] // reason: one refused edit shape per op and field
    async fn edit_shapes_are_checked_before_an_output_is_reserved() {
        let (_dir, ws) = workspace();
        // The input's own bytes decide the family, so a fixture standing for one is a package
        // holding that family's own main part.
        for (name, part) in [
            ("doc.docx", "word/document.xml"),
            ("book.xlsx", "xl/workbook.xml"),
            ("deck.pptx", "ppt/presentation.xml"),
        ] {
            std::fs::write(ws.as_path().join(name), package_with(part)).expect("write input");
        }
        let too_many: Vec<Value> = (0..=RULES.edits_max)
            .map(|_| json!({ "op": "replace_text", "find": "x", "replace": "y" }))
            .collect();
        let long_style = "a".repeat(RULES.paragraph_style_max + 1);
        let style_cap = format!("must be at most {} characters", RULES.paragraph_style_max);
        let wide_row: Vec<Value> = (0..=RULES.table_columns_max)
            .map(|column| json!(column))
            .collect();
        let calls = [
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "nope", "find": "x" }] }),
                "unknown docx edit",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "nope", "sheet": "Values", "cell": "A1" }] }),
                "unknown xlsx edit",
            ),
            (
                json!({ "action": "pptx_edit", "path": "deck.pptx",
                        "edits": [{ "op": "nope", "slide": 1 }] }),
                "unknown pptx edit",
            ),
            // A lookup of nothing but whitespace names no text a slide holds, so it is refused
            // before the deck is read rather than searched for.
            (
                json!({ "action": "pptx_edit", "path": "deck.pptx",
                        "edits": [{ "op": "replace_text", "slide": 1, "find": "  ",
                                    "replace": "x" }] }),
                "must name text",
            ),
            (
                json!({ "action": "pptx_edit", "path": "deck.pptx",
                        "edits": [{ "op": "add_paragraph", "slide": 1, "text": "X",
                                    "after": "\t" }] }),
                "must name text",
            ),
            // A `find` an op needs, a `format_text` with nothing to set, and an `insert_text` in
            // the wrong position.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "replace_text", "replace": "y" }] }),
                "must not be empty",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_text", "find": "x" }] }),
                "at least one of bold",
            ),
            // A `format_text` whose only property is a null has nothing to set: the null is
            // absent at the boundary.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_text", "find": "x", "bold": null }] }),
                "at least one of bold",
            ),
            // A `format_text` size outside the shared bound, or one JSON cannot carry as a finite
            // number: the kit writes half-points, so either would be a `<w:sz>` a reader cannot
            // hold. A non-finite float is JSON null, which is an absent property.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_text", "find": "x", "size": 1e300 }] }),
                "size must be",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_text", "find": "x", "size": f64::INFINITY }] }),
                "at least one of bold",
            ),
            // A `format_text` naming an attribute the op does not take beside one it does: the kit
            // reads only the fields it knows, so the extra one would be dropped in silence.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_text", "find": "x", "bold": true,
                                    "level": 1 }] }),
                "level is not a field of docx",
            ),
            // A known attribute whose value the writer has not: a colour that is not hex digits,
            // and an alignment the closed set does not hold.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_text", "find": "x", "color": "red" }] }),
                "got \"red\"",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x",
                                    "align": "middle" }] }),
                "got \"middle\"",
            ),
            // A `format_paragraph` naming no property would rewrite the paragraph and change
            // nothing.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x" }] }),
                "at least one of align",
            ),
            // A `level` with no list to belong to: alone, and beside `list: false`.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x", "level": 2 }] }),
                "needs a list to belong to",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x", "list": false,
                                    "level": 2 }] }),
                "needs a list to belong to",
            ),
            // A list kind outside the closed set, and a style name past the cap.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x",
                                    "list": "dash" }] }),
                "got \"dash\"",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x",
                                    "style": long_style }] }),
                style_cap.as_str(),
            ),
            // An indent and a line height outside the shared bounds, the line height's zero
            // included.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x",
                                    "indent_left": 3000 }] }),
                "indent_left must be",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x",
                                    "line_spacing": 0 }] }),
                "line_spacing must be",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "format_paragraph", "find": "x",
                                    "line_spacing": 3000 }] }),
                "line_spacing must be",
            ),
            // A well-formed `format_paragraph` passes: the refusal it meets is the family one a
            // path that is not a `.docx` is owed.
            (
                json!({ "action": "docx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_paragraph", "find": "x", "align": "center",
                                    "list": "bullet", "level": 2 }] }),
                "edits only a .docx/.docm file",
            ),
            // A `set_cell` needs a `value`: a value-less one is refused with a pointer to the
            // `format_cells` op.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "set_cell", "sheet": "Values", "cell": "A1",
                                    "number_format": "0.00" }] }),
                "has no \"value\"",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "insert_text", "find": "x", "insert": "y",
                                    "position": "middle" }] }),
                "position",
            ),
            // The two block-adding ops: an anchor and a picture are required, a picture's width
            // is a point measure above zero, and a table needs rows no wider than Word draws.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "add_image", "image": "picture.png" }] }),
                "after must not be empty",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "add_image", "after": "x", "image": "picture.png",
                                    "width": 0 }] }),
                "width must be",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "add_table", "after": "x" }] }),
                "a table with no rows and no headers",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "add_table", "after": "x", "rows": [[]] }] }),
                "a table with no rows and no headers",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "add_table", "after": "x", "rows": [wide_row] }] }),
                "a table holds at most",
            ),
            // A cell, a row and a column outside the workbook's grid.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "set_cell", "sheet": "Values", "cell": "A9999999",
                                    "value": 1 }] }),
                "the row must be between",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "set_cell", "sheet": "Values", "cell": "ZZZ1",
                                    "value": 1 }] }),
                "the column must be between",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "set_cell", "sheet": "Values", "cell": "A0",
                                    "value": 1 }] }),
                "must be an A1 address",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "insert_row", "sheet": "Values", "row": 0 }] }),
                "row must be a whole number",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "insert_column", "sheet": "Values", "column": "A1" }] }),
                "column must be column letters",
            ),
            // A `format_cells` target's own address is checked like every other op's.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "column": "A1",
                                    "width_chars": 10 }] }),
                "column must be column letters",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "column": "b",
                                    "width_chars": 10 }] }),
                "column must be column letters",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "row": 99_999_999,
                                    "height_points": 20 }] }),
                "row must be a whole number",
            ),
            // A `format_cells` naming no target, more than one target, or only the target and
            // none of its properties.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "bold": true }] }),
                "names no target",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "column": "B", "bold": true }] }),
                "names more than one target",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1" }] }),
                "names no formatting",
            ),
            // A property of the wrong type, or one the target does not take: the kit reads only
            // the keys it knows.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "bold": "yes" }] }),
                "must be a boolean",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "shade": "FF0000" }] }),
                "is not a field of xlsx",
            ),
            // The same for a docx key the op does not take: `position` belongs to an `insert_text`.
            (
                json!({ "action": "docx_edit", "path": "doc.docx",
                        "edits": [{ "op": "replace_text", "find": "x", "replace": "y",
                                    "position": "after" }] }),
                "is not a field of docx",
            ),
            // An alignment word and a border side the closed sets do not hold, and a border that
            // names no side at all.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "align": "middle" }] }),
                "align must be",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "border": { "leftish": true } }] }),
                "is not a side",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "border": {} }] }),
                "names no side",
            ),
            // A size, a width and a height outside the shared bounds, and a range holding more
            // cells than one `format_cells` may name.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "size": 500 }] }),
                "size must be",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "column": "B",
                                    "width_chars": 300 }] }),
                "width_chars must be",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "row": 3,
                                    "height_points": 500 }] }),
                "height_points must be",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1:A999999",
                                    "bold": true }] }),
                "more than one edit formats",
            ),
            // A colour and a fill that are not six hex digits.
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "color": "red" }] }),
                "color must be",
            ),
            (
                json!({ "action": "xlsx_edit", "path": "book.xlsx",
                        "edits": [{ "op": "format_cells", "sheet": "Values", "range": "A1",
                                    "fill": "red" }] }),
                "fill must be",
            ),
            // A slide number below one.
            (
                json!({ "action": "pptx_edit", "path": "deck.pptx",
                        "edits": [{ "op": "delete_slide", "slide": 0 }] }),
                "slide must be a whole number",
            ),
            (
                json!({ "action": "docx_edit", "path": "doc.docx", "edits": too_many }),
                "more than one call takes",
            ),
        ];
        for (args, expected) in calls {
            let err = confined_document()
                .execute(&ws, args)
                .await
                .expect_err("a call the tool cannot carry out");
            assert!(
                err.to_string().contains(expected),
                "expected the refusal to name {expected}: {err}"
            );
        }
        assert_eq!(generated_count(&ws), 0, "a refused call left an output");
    }

    /// A `null` for an optional edit field is absent, and the request spells it that way: the
    /// kit reads a null as a value, which would strip a run's own bold or be read as text.
    #[test]
    fn edit_nulls_are_dropped_before_the_request_is_forwarded() {
        use crate::ooxml::Family;
        let docx = validate_edits(
            Family::Docx,
            &json!({ "edits": [
                { "op": "format_text", "find": "x", "bold": null, "size": 24 },
                { "op": "insert_text", "find": "x", "insert": "y", "position": null },
                { "op": "add_paragraph", "text": "z", "after": null },
            ]}),
        )
        .expect("valid docx edits");
        assert_eq!(
            docx,
            json!([
                { "op": "format_text", "find": "x", "size": 24 },
                { "op": "insert_text", "find": "x", "insert": "y" },
                { "op": "add_paragraph", "text": "z" },
            ])
        );

        // The normalized `value` survives beside the dropped `number_format`, and the nested
        // null inside the `border` object is dropped at that level too.
        let xlsx = validate_edits(
            Family::Xlsx,
            &json!({ "edits": [
                { "op": "set_cell", "sheet": "S", "cell": "A1", "value": 1,
                  "number_format": null },
                { "op": "format_cells", "sheet": "S", "range": "A1",
                  "border": { "top": null, "left": true } },
            ]}),
        )
        .expect("valid xlsx edits");
        assert_eq!(
            xlsx,
            json!([
                { "op": "set_cell", "sheet": "S", "cell": "A1", "value": 1 },
                { "op": "format_cells", "sheet": "S", "range": "A1",
                  "border": { "left": true } },
            ])
        );

        let pptx = validate_edits(
            Family::Pptx,
            &json!({ "edits": [
                { "op": "add_paragraph", "slide": 1, "text": "z", "after": null,
                  "level": null },
                { "op": "add_slide", "after": null, "title": null, "bullets": null },
            ]}),
        )
        .expect("valid pptx edits");
        assert_eq!(
            pptx,
            json!([
                { "op": "add_paragraph", "slide": 1, "text": "z" },
                { "op": "add_slide" },
            ])
        );
    }

    /// The values the schema now declares are the values the boundary takes: a `list` and a
    /// `fill` of `false`, and a `set_cell` `value` that is a number or the formula object.
    #[test]
    fn the_schema_declares_the_shapes_the_boundary_accepts() {
        use crate::ooxml::Family;

        let docx = validate_edits(
            Family::Docx,
            &json!({ "edits": [{ "op": "format_paragraph", "find": "x", "list": false }] }),
        )
        .expect("list: false takes the paragraph's list away");
        assert_eq!(
            docx,
            json!([{ "op": "format_paragraph", "find": "x", "list": false }])
        );

        let xlsx = validate_edits(
            Family::Xlsx,
            &json!({ "edits": [
                { "op": "format_cells", "sheet": "S", "range": "A1", "fill": false },
                { "op": "set_cell", "sheet": "S", "cell": "A1", "value": 42 },
                { "op": "set_cell", "sheet": "S", "cell": "A2",
                  "value": { "formula": "SUM(A1:A1)" } },
            ]}),
        )
        .expect("a false fill, a number and a formula object are all declared shapes");
        assert_eq!(
            xlsx,
            json!([
                { "op": "format_cells", "sheet": "S", "range": "A1", "fill": false },
                { "op": "set_cell", "sheet": "S", "cell": "A1", "value": 42 },
                { "op": "set_cell", "sheet": "S", "cell": "A2",
                  "value": { "formula": "SUM(A1:A1)" } },
            ])
        );

        // The same values the boundary just took are the ones the schema states: the list's enum
        // holds `false` beside the words, the fill is a colour or `false`, and a cell's `value`
        // is a scalar or the formula object.
        let fields = |action: &str| {
            action_schema(action)["properties"][action]["properties"]["edits"]["items"]
                ["properties"]
                .clone()
        };
        let docx_fields = fields("docx_edit");
        assert_eq!(docx_fields["list"]["type"], json!(["string", "boolean"]));
        assert!(
            docx_fields["list"]["enum"]
                .as_array()
                .is_some_and(|values| values.contains(&json!(false))),
            "the list enum must offer false beside the kinds: {}",
            docx_fields["list"]
        );
        let xlsx_fields = fields("xlsx_edit");
        assert_eq!(xlsx_fields["fill"]["anyOf"][0]["type"], json!("string"));
        assert_eq!(xlsx_fields["fill"]["anyOf"][1]["enum"], json!([false]));
        assert_eq!(
            xlsx_fields["value"]["anyOf"][0]["type"],
            json!(RULES.scalar_kinds)
        );
        assert_eq!(
            xlsx_fields["value"]["anyOf"][1]["required"],
            json!(["formula"])
        );
    }

    /// A copy of an edited input is named with the input's own extension when the name is the
    /// family the bytes are, and with the family's own when the name says nothing.
    #[test]
    fn copy_extension_follows_the_content_when_the_name_does_not() {
        use crate::ooxml::Family;
        assert_eq!(
            copy_extension(Path::new("report.docm"), Family::Docx),
            "docm"
        );
        assert_eq!(
            copy_extension(Path::new("report.docx"), Family::Docx),
            "docx"
        );
        assert_eq!(copy_extension(Path::new("report"), Family::Docx), "docx");
        assert_eq!(
            copy_extension(Path::new("report.bin"), Family::Docx),
            "docx"
        );
        assert_eq!(copy_extension(Path::new("sheet.xls"), Family::Xlsx), "xlsx");
        assert_eq!(copy_extension(Path::new("deck.ppt"), Family::Pptx), "pptx");
    }

    /// A pptx edit naming a key its op does not take is refused at the boundary: the kit reads
    /// only the fields the op knows, so a mistyped parameter would be dropped in silence.
    #[test]
    fn pptx_edit_refuses_a_key_its_op_does_not_take() {
        let cases = [
            (
                json!([{ "op": "delete_slide", "slide": 1, "title": "x" }]),
                "edits[0].title is not a field of pptx \"delete_slide\"",
            ),
            (
                json!([{ "op": "format_text", "slide": 1, "find": "a", "shadow": true }]),
                "edits[0].shadow is not a field of pptx \"format_text\"",
            ),
        ];
        for (edits, expected) in cases {
            let err = validate_edits(crate::ooxml::Family::Pptx, &json!({ "edits": edits }))
                .expect_err("a key the op does not take must be refused");
            let message = err.to_string();
            assert!(
                message.contains("usage:") && message.contains(expected),
                "expected {expected:?}, got: {message}"
            );
        }
    }

    /// The naming helpers drop a directory part, neutralize marker punctuation, ignore a trailing
    /// extension the tool appends itself, and fall back when nothing usable is left.
    #[test]
    fn naming_strips_extension_directory_and_markers() {
        assert_eq!(sanitize_base(Some("report.docx"), "fallback"), "report");
        assert_eq!(sanitize_base(Some("dir/sub/report"), "fallback"), "report");
        assert_eq!(sanitize_base(Some("re[po]rt"), "fallback"), "re_po_rt");
        assert_eq!(sanitize_base(Some("   "), "fallback"), "fallback");
        assert_eq!(sanitize_base(Some("..."), "fallback"), "fallback");
    }

    /// The page cap is on the total a request names, not on one selection's own size: two
    /// selections that add up past the limit must be refused before the kit sees them.
    #[test]
    fn split_groups_refuses_a_request_over_the_page_cap() {
        let err = split_groups(&json!({ "pages": ["1-6000", "6001-12000"] }))
            .expect_err("a request over the cap must be refused");
        assert!(
            err.to_string().contains("too many pages"),
            "unexpected error: {err}"
        );
    }

    /// The rules both this tool and the kit enforce are one committed file: a malformed one must
    /// fail loudly when read, and an emptied one must not silently widen every bound.
    #[test]
    fn the_shared_rules_parse_and_are_sane() {
        let rules = &*RULES;
        assert!(
            !rules.heading_levels.is_empty(),
            "no heading levels — every heading would be refused"
        );
        // The docx `HeadingLevel` list and the PDF size table have three entries each, indexed
        // by `level - 1`; a fourth would pass the guard and then render an undefined style or a
        // wrong pptx size.
        assert!(
            rules
                .heading_levels
                .iter()
                .all(|level| level.fract() == 0.0 && (1.0..=3.0).contains(level)),
            "a heading level the writers cannot style"
        );
        assert!(!rules.scalar_kinds.is_empty(), "no scalar kinds");
        assert!(!rules.image_extensions.is_empty(), "no image extensions");
        // Each of these is a closed vocabulary an edit is refused against, so an empty one would
        // refuse every value the model is told to pass.
        assert!(!rules.cell_alignments.is_empty(), "no cell alignments");
        assert!(!rules.cell_verticals.is_empty(), "no cell verticals");
        assert!(!rules.cell_border_sides.is_empty(), "no cell border sides");
        assert!(
            !rules.paragraph_alignments.is_empty(),
            "no paragraph alignments"
        );
        assert!(!rules.paragraph_lists.is_empty(), "no paragraph lists");
        assert!(
            rules.dimension_points.min < rules.dimension_points.max,
            "an empty dimension range"
        );
        assert!(
            rules.slide_position_fraction.min < rules.slide_position_fraction.max,
            "an empty slide-position range"
        );
        assert!(
            rules.slide_size_fraction.min < rules.slide_size_fraction.max,
            "an empty slide-size range"
        );
        assert!(
            rules.text_size_points.min < rules.text_size_points.max,
            "an empty text-size range"
        );
        assert!(
            rules.paragraph_indent_points.min < rules.paragraph_indent_points.max,
            "an empty paragraph-indent range"
        );
        assert!(
            rules.paragraph_spacing_points.min < rules.paragraph_spacing_points.max,
            "an empty paragraph-spacing range"
        );
        assert!(
            rules.paragraph_line_points.min < rules.paragraph_line_points.max,
            "an empty paragraph-line range"
        );
        assert!(
            rules.slide_text_size_points.min < rules.slide_text_size_points.max,
            "an empty slide-text-size range"
        );
        assert!(
            rules.cell_font_points.min < rules.cell_font_points.max,
            "an empty cell-font-size range"
        );
        assert!(
            rules.column_width_chars.min < rules.column_width_chars.max,
            "an empty column-width range"
        );
        assert!(
            rules.row_height_points.min < rules.row_height_points.max,
            "an empty row-height range"
        );
        assert!(
            rules.color_digits > 0 && rules.color_digits.is_multiple_of(3),
            "a colour whose digits do not split into three channels"
        );
        assert!(
            rules.degrees_step > 0 && rules.degrees_step < 360 && 360 % rules.degrees_step == 0,
            "a step that leaves no rotation below a full turn"
        );
        assert!(
            rules.sheet_name_max > 0,
            "a sheet-name limit that refuses every name"
        );
        assert!(
            !rules.sheet_name_forbidden.is_empty(),
            "an empty forbidden set admits every character"
        );
        // Each cap is a bound the tool refuses past, so a zero would refuse every value a caller
        // could pass.
        for (name, cap) in [
            ("edit_text_max", rules.edit_text_max),
            ("edits_max", rules.edits_max),
            ("bullets_max", rules.bullets_max),
            ("paragraph_level_max", rules.paragraph_level_max as usize),
            ("sheet_row_max", rules.sheet_row_max as usize),
            ("sheet_column_max", rules.sheet_column_max as usize),
            ("number_format_max", rules.number_format_max),
            ("font_name_max", rules.font_name_max),
            ("format_cells_max", rules.format_cells_max),
            ("paragraph_style_max", rules.paragraph_style_max),
            ("table_columns_max", rules.table_columns_max),
        ] {
            assert!(cap > 0, "{name} refuses every value");
        }
    }

    /// Whether `text` states `value` as a whole number rather than as a slice of a longer one:
    /// a bare `contains` would let the paragraph-level cap `8` be satisfied by the `1048576` of
    /// the row cap.
    fn states_whole_number(text: &str, value: &str) -> bool {
        // An empty value is found everywhere, so it would pass this test vacuously.
        if value.is_empty() {
            return false;
        }
        let mut from = 0;
        while let Some(at) = text[from..].find(value) {
            let start = from + at;
            let end = start + value.len();
            let digit_before = text[..start]
                .chars()
                .next_back()
                .is_some_and(|c| c.is_ascii_digit());
            let digit_after = text[end..]
                .chars()
                .next()
                .is_some_and(|c| c.is_ascii_digit());
            if !digit_before && !digit_after {
                return true;
            }
            from = start + 1;
        }
        false
    }

    /// Every string the schema itself carries, unescaped, so a rule stated in the parameter
    /// interface is searched the way the rendered description is.
    fn schema_text(value: &Value) -> String {
        match value {
            Value::String(text) => text.clone(),
            Value::Array(values) => values.iter().map(schema_text).collect::<Vec<_>>().join(" "),
            Value::Object(object) => object
                .values()
                .map(schema_text)
                .collect::<Vec<_>>()
                .join(" "),
            other => other.to_string(),
        }
    }

    /// Every rule the tool enforces is stated where the model reads it: the asset's placeholders
    /// are rendered from `rules.json`, and the bounds that live on a single argument are stated
    /// in the parameter schema.
    #[test]
    fn the_description_states_every_rule_it_names() {
        let description = confined_document().description();
        assert!(
            !description.contains("{{"),
            "the description left a placeholder unreplaced:\n{description}"
        );
        let schema = schema_text(&confined_document().parameters_schema());
        for value in [
            listed(&RULES.heading_levels),
            RULES.dimension_points.bounds(),
            RULES.slide_position_fraction.bounds(),
            RULES.slide_size_fraction.bounds(),
            RULES.text_size_points.bounds(),
            RULES.paragraph_indent_points.bounds(),
            RULES.paragraph_spacing_points.bounds(),
            RULES.paragraph_line_points.bounds(),
            RULES.slide_text_size_points.bounds(),
            RULES.cell_font_points.bounds(),
            RULES.column_width_chars.bounds(),
            RULES.row_height_points.bounds(),
            RULES.color_digits.to_string(),
            RULES.degrees_step.to_string(),
            RULES.sheet_name_max.to_string(),
            format!("{:?}", RULES.sheet_name_forbidden),
            RULES.edit_text_max.to_string(),
            RULES.edits_max.to_string(),
            RULES.bullets_max.to_string(),
            RULES.paragraph_level_max.to_string(),
            RULES.paragraph_style_max.to_string(),
            RULES.sheet_row_max.to_string(),
            RULES.sheet_column_max.to_string(),
            RULES.number_format_max.to_string(),
            RULES.font_name_max.to_string(),
            RULES.format_cells_max.to_string(),
            RULES.table_columns_max.to_string(),
            RULES.max_pages_per_request.to_string(),
            megabytes(crate::util::FILE_MAX_BYTES).to_string(),
        ] {
            assert!(
                states_whole_number(&description, &value) || states_whole_number(&schema, &value),
                "neither the description nor the schema states the rule it names — {value:?} is \
                 missing as a whole number from:\n{description}\n{schema}"
            );
        }
        // The default deck's size is text the model reads rather than a number inside a
        // sentence, so the whole-number guard above would not cover it.
        let default_deck = RULES.pptx_default_size.inches();
        assert!(
            schema.contains(&default_deck),
            "the schema does not state the default deck's size {default_deck:?}:\n{schema}"
        );
        // A slide mark is not a number, so the guard asserts nothing for it: the description
        // names every mark the reader prints, from the shared lists. A label's `{n}` is the
        // reader's own placeholder, so the description states it as `<n>`; each enumeration word
        // is checked on its own.
        for word in pair_words(&RULES.paragraph_alignments)
            .into_iter()
            .chain(pair_words(&RULES.paragraph_lists))
            .chain(pair_words(&RULES.slide_alignments))
            .chain(RULES.cell_alignments.iter().map(String::as_str))
            .chain(RULES.cell_verticals.iter().map(String::as_str))
            .chain(RULES.cell_border_sides.iter().map(String::as_str))
            .chain(RULES.pptx_sizes.iter().map(|size| size.name.as_str()))
        {
            assert!(
                description.contains(word) || schema.contains(word),
                "neither the description nor the schema names the accepted word {word:?}"
            );
        }
        let marks = crate::docgen::ppt_marks();
        let labels = crate::docgen::ppt_slide_labels();
        let slide_label = crate::reader_output::slide_label(&labels.slide, "<n>");
        let notes_label = crate::reader_output::slide_label(&labels.notes, "<n>");
        let comments_label = crate::reader_output::slide_label(&labels.comments, "<n>");
        for mark in [
            &marks.title,
            &marks.hidden_slide,
            &marks.diagram_text,
            &marks.diagram_text_lost,
            &marks.no_text,
            &slide_label,
            &notes_label,
            &comments_label,
        ] {
            assert!(
                description.contains(mark.as_str()),
                "the description does not name the slide mark {mark:?}"
            );
        }
        for mark in crate::docgen::docx_marks() {
            assert!(
                description.contains(mark.example.as_str()),
                "the description does not name the Word mark {:?}",
                mark.example
            );
        }
    }

    /// What this tool's model-read contract measured: the rendered description for the path-access
    /// variant this test builds, and the description and the serialized schema together.
    const BASELINE_DESCRIPTION: usize = 9_532;
    const BASELINE_TOTAL: usize = 37_402;

    /// The whole per-action contract is one compact value: every action has an entry declaring
    /// exactly the arguments it takes and requires, within the measured baseline.
    #[test]
    fn the_schema_is_compact_and_declares_every_action() {
        let tool = confined_document();
        let schema = tool.parameters_schema();
        let entries = schema["properties"]["action"]["oneOf"]
            .as_array()
            .expect("the action list is a oneOf");
        assert_eq!(entries.len(), ACTIONS.len(), "one entry per action");
        for (entry, action) in entries.iter().zip(ACTIONS) {
            assert_eq!(
                entry["properties"][action]["type"], "object",
                "{action} must be one entry with its own arguments"
            );
            assert_eq!(
                entry["required"],
                json!([action]),
                "{action}'s entry must require its own name"
            );
            assert_eq!(
                entry["additionalProperties"], false,
                "an entry takes only the actions it names"
            );
        }
        let description = tool.description().len();
        assert!(
            description <= BASELINE_DESCRIPTION,
            "the rendered description is {description} bytes, more than the measured \
             {BASELINE_DESCRIPTION}"
        );
        let size = serde_json::to_string(&schema)
            .expect("the schema serializes")
            .len();
        assert!(
            description + size <= BASELINE_TOTAL,
            "the description ({description}) and serialized schema ({size}) together are {} bytes, \
             more than the measured {BASELINE_TOTAL}",
            description + size
        );
    }

    /// The tool is offered exactly while the managed runtime is present: a tool whose runtime is
    /// missing must not be in the role's list, and a host that has it must not lose it.
    #[test]
    fn the_tool_is_offered_exactly_with_the_managed_runtime() {
        let (_dir, ws) = workspace();
        let (tools, _) = crate::agent::role_tools_and_specs(
            crate::Role::Assistant,
            &ws,
            false,
            std::sync::Arc::default(),
            None,
        );
        assert_eq!(
            tools.iter().any(|tool| tool.name() == "document"),
            crate::tools::bun::bun_binary_path().is_some(),
            "the tool must be offered exactly while the managed bun runtime is present"
        );
    }
}