omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
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
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
//! Structural and destructive spreadsheet edits via `spreadsheets.batchUpdate`.
//!
//! The `drive sheets add-sheet`/`rename-sheet`/`insert-rows`/`insert-columns`
//! (additive, issue #1613, [ADR-0075](../../../docs/adrs/adr-0075.md)),
//! `insert-range` (additive, issue #1838),
//! `duplicate-sheet`/`reorder-sheet`/`hide-sheet`/`show-sheet` (also
//! additive, issue #1643, [ADR-0078](../../../docs/adrs/adr-0078.md)),
//! `move-rows`/`move-columns` (also additive — nothing is discarded, issue
//! #1834, [ADR-0083](../../../docs/adrs/adr-0083.md)),
//! `delete-sheet`/`delete-rows`/`delete-columns`/`delete-range` (destructive,
//! issue #1623,
//! [ADR-0077](../../../docs/adrs/adr-0077-sheets-deletion-via-batchupdate.md)),
//! and `update-workbook-properties` (also additive, issue #1836,
//! [ADR-0086](../../../docs/adrs/adr-0086-workbook-properties.md)) engines,
//! gated by the ADR-0071 folder write-permission rules.
//!
//! `update-workbook-properties` is the one verb here with no sheet target:
//! every other verb acts on a tab within the workbook, this one acts on the
//! workbook itself (locale, time zone, auto-recalc, iterative calculation —
//! deliberately not `spreadsheetTheme`, a large nested type left for a
//! future issue). [`StructureVerb::sheet_title`] returns `Option<&str>`
//! rather than `&str` for exactly this reason, and [`resolve_sheet`] returns
//! `Ok(None)` for it without consulting the sheet list at all. Turning
//! iterative calculation on is a value effect reached indirectly — it
//! changes what a circular-reference formula elsewhere *evaluates to*
//! without changing that formula itself, the same shape of concern
//! ADR-0081 raised for named-range deletion — so it stays gated as
//! `sheets-structure` rather than treated as a data mutation; see
//! [`crate::drive::sheets::types::IterativeCalculationSettings`]'s doc
//! comment.
//!
//! [ADR-0073](../../../docs/adrs/adr-0073.md) §12 deferred this surface
//! because `batchUpdate` is where "one call destroys far more than its
//! arguments suggest". Two properties answer that, and each is structural
//! rather than a matter of care:
//!
//! - **Typed verbs, no raw request passthrough.** Every verb builds its own
//!   [`BatchUpdateRequestItem`], so the gate and `--dry-run` can describe the
//!   exact effect. There is no `--requests file.json` and deliberately no
//!   escape hatch, following [ADR-0061](../../../docs/adrs/adr-0061.md)'s
//!   handling of force-push: the dangerous form must be unreachable, not
//!   merely discouraged. This still holds for the destructive verbs added by
//!   ADR-0077 — they gained typed variants, not a passthrough.
//! - **A distinct gate operation per risk class.** Additive verbs check
//!   [`DriveOperation::SheetsStructure`]; the four destructive verbs check
//!   [`DriveOperation::SheetsDelete`] instead — never folded together, and
//!   never reusing `SheetsWrite` either. See each variant's doc comment for
//!   why reuse would be silent privilege widening. [`StructureVerb::gate_operation`]
//!   is the single place this split is decided.
//!
//! ADR-0075 §3/§4 originally kept `deleteSheet`/`deleteDimension`/
//! `deleteRange` unreachable at the type level, pinned by a
//! `no_destructive_request_is_reachable` grep-guard test. ADR-0077
//! supersedes that: those requests are now reachable, but only through this
//! module's gated, validated path — never through a raw passthrough, and
//! never under the `sheets-structure` operation an existing `allow` rule may
//! already grant.
//!
//! Shape follows `write.rs` exactly: a public wrapper that logs, an `_inner`
//! that classifies then mutates, and `--dry-run` as an early return *after*
//! the gate so a preview and a real run share one classification by
//! construction. One difference is deliberate and tested: a dry run here does
//! issue a single `spreadsheets.get`, because describing a structural effect
//! honestly requires the sheet's real current dimensions. It still issues no
//! `batchUpdate`, and a gate-blocked attempt still issues no Sheets call at
//! all. `--dry-run` for a destructive verb stays structural-only — no
//! `values.get` read and no cell content in its output or the request log —
//! and instead states a fixed caveat that formulas elsewhere in the workbook
//! may reference what would be deleted, which cannot be checked from the
//! sheet's own dimensions (ADR-0077).

use std::path::PathBuf;
use std::time::{Duration, Instant};

use serde::Serialize;

use crate::cli::drive::format::{write_scalar_jsonl, JsonlSerialize};
use crate::drive::client::DriveClient;
use crate::drive::files_api::FilesApi;
use crate::drive::lease::check::{
    conclude_native_leased_write, gate_optional_leased_write, recovery_note, FromLeaseRefusal,
    LeaseGateRefusal, LeasedWrite,
};
use crate::drive::lease::ledger::LeaseBackup;
use crate::drive::sheets::api::{
    applied_reply_unreadable_line, BatchUpdateOutcome, RetryHint, SheetsApi,
};
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::format::{normalize_hex_for_display, parse_hex_color};
use crate::drive::sheets::grid_range;
use crate::drive::sheets::target_gate;
use crate::drive::sheets::types::{
    AddSheetRequest, BatchUpdateRequestItem, BatchUpdateResponse, ColorStyle,
    DeleteDimensionRequest, DeleteRangeRequest, DeleteSheetRequest, Dimension, DimensionRange,
    DuplicateSheetRequest, GridProperties, GridPropertiesUpdate, GridRange, InsertDimensionRequest,
    InsertRangeRequest, IterativeCalculationSettings, MoveDimensionRequest, NewSheetProperties,
    RecalculationInterval, SheetProperties, SheetPropertiesUpdate, ShiftDimension, Spreadsheet,
    SpreadsheetPropertiesUpdate, UpdateSheetPropertiesRequest, UpdateSpreadsheetPropertiesRequest,
};
use crate::drive::types::SheetTargetRefusal;
use crate::drive::write_gate::{self, DecidingRule, DriveOperation, FolderPermissionRule};
use crate::request_log::{self, DriveMutationOutcome};

/// Which structural mutation to perform.
///
/// Unlike `write.rs`'s [`WriteVerb`](crate::drive::sheets::write::WriteVerb),
/// which is fieldless with its arguments in the options struct, these verbs
/// take disjoint arguments, so the enum carries them. That also means an
/// impossible combination — a `--title` on an insert, say — is not
/// representable.
// `PartialEq`-only, not `Eq` (issue #1836):
// `UpdateWorkbookProperties::iterative_calculation_convergence_threshold`
// carries an `f64`, which has no meaningful `Eq` — see `Spreadsheet`'s own
// doc comment (`types.rs`) for the same reasoning applied to `Color`.
#[derive(Debug, Clone, PartialEq)]
pub enum StructureVerb {
    /// Add a new sheet to the workbook.
    AddSheet {
        /// Title for the new sheet.
        title: String,
        /// Zero-based position; `None` appends.
        index: Option<i64>,
        /// Initial row count; `None` takes Sheets' default.
        rows: Option<i64>,
        /// Initial column count; `None` takes Sheets' default.
        columns: Option<i64>,
    },
    /// Rename an existing sheet.
    RenameSheet {
        /// Current title of the sheet to rename.
        sheet: String,
        /// The new title.
        new_title: String,
    },
    /// Insert empty rows, shifting existing ones down.
    InsertRows {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based row to insert before.
        at: i64,
        /// How many rows to insert.
        count: i64,
    },
    /// Insert empty columns, shifting existing ones right.
    InsertColumns {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based column to insert before.
        at: i64,
        /// How many columns to insert.
        count: i64,
    },
    /// Insert empty cells into a rectangular range, shifting existing cells
    /// down or right within the same grid (issue #1838).
    ///
    /// All four bounds are required together: this crate only ever sends a
    /// fully-bounded [`GridRange`]. Whole rows and columns belong to
    /// [`Self::InsertRows`] and [`Self::InsertColumns`].
    InsertRange {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based first row, inclusive.
        start_row: i64,
        /// 1-based last row, inclusive.
        end_row: i64,
        /// 1-based first column, inclusive.
        start_column: i64,
        /// 1-based last column, inclusive.
        end_column: i64,
        /// Which way existing cells shift to make room.
        shift: ShiftDimension,
    },
    /// Move a contiguous block of rows to a new position within the same
    /// sheet, shifting the rows in between to close the gap (issue #1834).
    MoveRows {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based first row of the block to move, inclusive.
        at: i64,
        /// How many rows the block spans.
        count: i64,
        /// 1-based row the block moves in front of, numbered as the sheet
        /// stands *before* the move (the API's own `destinationIndex`
        /// convention, translated by `move_destination_index`).
        before: i64,
    },
    /// Move a contiguous block of columns to a new position within the same
    /// sheet, shifting the columns in between to close the gap (issue
    /// #1834).
    MoveColumns {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based first column of the block to move, inclusive.
        at: i64,
        /// How many columns the block spans.
        count: i64,
        /// 1-based column the block moves in front of, numbered as the
        /// sheet stands *before* the move.
        before: i64,
    },
    /// Delete an entire sheet from the workbook.
    DeleteSheet {
        /// Title of the sheet to delete.
        sheet: String,
    },
    /// Delete whole rows, shifting the remainder up to close the gap.
    DeleteRows {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based first row to delete, inclusive.
        at: i64,
        /// How many rows to delete.
        count: i64,
    },
    /// Delete whole columns, shifting the remainder left to close the gap.
    DeleteColumns {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based first column to delete, inclusive.
        at: i64,
        /// How many columns to delete.
        count: i64,
    },
    /// Delete a rectangular cell range, shifting the remainder along one
    /// axis to close the gap.
    ///
    /// All four bounds are required together: this crate only ever sends a
    /// fully-bounded [`GridRange`]. An open-ended range on one axis would
    /// degenerate into [`Self::DeleteRows`]/[`Self::DeleteColumns`]
    /// semantics and is out of scope here.
    DeleteRange {
        /// Title of the sheet to modify.
        sheet: String,
        /// 1-based first row, inclusive.
        start_row: i64,
        /// 1-based last row, inclusive.
        end_row: i64,
        /// 1-based first column, inclusive.
        start_column: i64,
        /// 1-based last column, inclusive.
        end_column: i64,
        /// Which way to shift the remaining cells afterward.
        shift: ShiftDimension,
    },
    /// Copy an existing sheet within the same workbook.
    DuplicateSheet {
        /// Title of the sheet to copy.
        sheet: String,
        /// Title for the copy; `None` takes Sheets' own "Copy of X" default.
        title: Option<String>,
        /// Zero-based position for the copy; `None` appends.
        index: Option<i64>,
    },
    /// Move an existing sheet to a new position among its siblings.
    ReorderSheet {
        /// Title of the sheet to move.
        sheet: String,
        /// The new zero-based position.
        index: i64,
    },
    /// Hide or show an existing sheet.
    SetSheetVisibility {
        /// Title of the sheet to modify.
        sheet: String,
        /// `true` hides it, `false` shows it.
        hidden: bool,
    },
    /// Change a sheet's view properties — frozen rows/columns, tab color,
    /// right-to-left layout, and whether gridlines are hidden (issue #1835).
    /// Every field is independently optional; the caller sets whichever it
    /// passed, and `build_request`'s `fields` mask names exactly those.
    UpdateSheetProperties {
        /// Title of the sheet to modify.
        sheet: String,
        /// Rows to freeze at the top, when changing it.
        freeze_rows: Option<i64>,
        /// Columns to freeze at the left, when changing it.
        freeze_columns: Option<i64>,
        /// The new tab color, `#RRGGBB`, when setting it.
        tab_color: Option<String>,
        /// Clear the tab color back to none. Mutually exclusive with
        /// `tab_color` (the CLI's `clap::ArgGroup` conflict enforces this;
        /// `validate_verb_args` refuses the combination defensively too).
        clear_tab_color: bool,
        /// The new right-to-left flag, when changing it.
        right_to_left: Option<bool>,
        /// The new hide-gridlines flag, when changing it.
        hide_gridlines: Option<bool>,
    },
    /// Change workbook-level properties: locale, time zone, auto-recalc
    /// and/or iterative calculation (issue #1836). The one verb in this
    /// enum with no sheet target — see the module doc comment.
    UpdateWorkbookProperties {
        /// The new locale, e.g. `"en_US"`. `None` leaves it unchanged.
        locale: Option<String>,
        /// The new IANA time zone, e.g. `"America/New_York"`. `None` leaves
        /// it unchanged.
        time_zone: Option<String>,
        /// The new auto-recalculation interval. `None` leaves it unchanged.
        auto_recalc: Option<RecalculationInterval>,
        /// Turns iterative calculation on or off. `None` leaves it
        /// unchanged; the two sub-fields below are only meaningful
        /// alongside `Some(IterativeCalculationToggle::On)` —
        /// `validate_verb_args` refuses every other combination.
        iterative_calculation: Option<IterativeCalculationToggle>,
        /// Maximum calculation rounds, for `iterative_calculation ==
        /// Some(On)`. `None` takes Sheets' own default.
        iterative_calculation_max_iterations: Option<i64>,
        /// Convergence threshold, for `iterative_calculation ==
        /// Some(On)`. `None` takes Sheets' own default.
        iterative_calculation_convergence_threshold: Option<f64>,
    },
}

/// Which way `update-workbook-properties --iterative-calculation` sets
/// iterative calculation.
///
/// Not [`RecalculationInterval`]-style wire vocabulary: the API has no
/// boolean or enum field for this (see
/// [`IterativeCalculationSettings`]'s doc comment) — this type exists purely
/// to carry the caller's on/off *intent* through to `build_request`, which
/// turns it into the right combination of
/// [`SpreadsheetPropertiesUpdate::iterative_calculation_settings`] and
/// `fields`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IterativeCalculationToggle {
    /// Turn iterative calculation on (or update its settings; it is
    /// already on).
    On,
    /// Turn iterative calculation off.
    Off,
}

impl StructureVerb {
    /// The `operation` this verb records in the request log.
    ///
    /// `build_drive_mutation_record` shapes `command` as `["drive",
    /// <operation>]`, so these read as `drive sheets-add-sheet` in the log
    /// even though the CLI spells them `drive sheets add-sheet`.
    const fn log_operation(&self) -> &'static str {
        match self {
            Self::AddSheet { .. } => "sheets-add-sheet",
            Self::RenameSheet { .. } => "sheets-rename-sheet",
            Self::InsertRows { .. } => "sheets-insert-rows",
            Self::InsertColumns { .. } => "sheets-insert-columns",
            Self::InsertRange { .. } => "sheets-insert-range",
            Self::MoveRows { .. } => "sheets-move-rows",
            Self::MoveColumns { .. } => "sheets-move-columns",
            Self::DeleteSheet { .. } => "sheets-delete-sheet",
            Self::DeleteRows { .. } => "sheets-delete-rows",
            Self::DeleteColumns { .. } => "sheets-delete-columns",
            Self::DeleteRange { .. } => "sheets-delete-range",
            Self::DuplicateSheet { .. } => "sheets-duplicate-sheet",
            Self::ReorderSheet { .. } => "sheets-reorder-sheet",
            Self::SetSheetVisibility { hidden: true, .. } => "sheets-hide-sheet",
            Self::SetSheetVisibility { hidden: false, .. } => "sheets-show-sheet",
            Self::UpdateSheetProperties { .. } => "sheets-update-sheet-properties",
            Self::UpdateWorkbookProperties { .. } => "sheets-update-workbook-properties",
        }
    }

    /// Which [`DriveOperation`] gates this verb.
    ///
    /// The single place the additive/destructive split is decided — see the
    /// module doc comment and [`DriveOperation::SheetsDelete`]'s doc comment
    /// for why the two must never share an operation.
    const fn gate_operation(&self) -> DriveOperation {
        match self {
            Self::AddSheet { .. }
            | Self::RenameSheet { .. }
            | Self::InsertRows { .. }
            | Self::InsertColumns { .. }
            | Self::InsertRange { .. }
            | Self::MoveRows { .. }
            | Self::MoveColumns { .. }
            | Self::DuplicateSheet { .. }
            | Self::ReorderSheet { .. }
            | Self::SetSheetVisibility { .. }
            | Self::UpdateSheetProperties { .. }
            | Self::UpdateWorkbookProperties { .. } => DriveOperation::SheetsStructure,
            Self::DeleteSheet { .. }
            | Self::DeleteRows { .. }
            | Self::DeleteColumns { .. }
            | Self::DeleteRange { .. } => DriveOperation::SheetsDelete,
        }
    }

    /// The CLI subcommand that spells this verb, for error messages that
    /// name the command the user actually typed — `write.rs::describe`'s
    /// convention.
    const fn label(&self) -> &'static str {
        match self {
            Self::AddSheet { .. } => "add-sheet",
            Self::RenameSheet { .. } => "rename-sheet",
            Self::InsertRows { .. } => "insert-rows",
            Self::InsertColumns { .. } => "insert-columns",
            Self::InsertRange { .. } => "insert-range",
            Self::MoveRows { .. } => "move-rows",
            Self::MoveColumns { .. } => "move-columns",
            Self::DeleteSheet { .. } => "delete-sheet",
            Self::DeleteRows { .. } => "delete-rows",
            Self::DeleteColumns { .. } => "delete-columns",
            Self::DeleteRange { .. } => "delete-range",
            Self::DuplicateSheet { .. } => "duplicate-sheet",
            Self::ReorderSheet { .. } => "reorder-sheet",
            Self::SetSheetVisibility { hidden: true, .. } => "hide-sheet",
            Self::SetSheetVisibility { hidden: false, .. } => "show-sheet",
            Self::UpdateSheetProperties { .. } => "update-sheet-properties",
            Self::UpdateWorkbookProperties { .. } => "update-workbook-properties",
        }
    }

    /// The title of the sheet this verb acts on: the one being created for
    /// `AddSheet`, the existing target otherwise; `None` for
    /// `UpdateWorkbookProperties`, which acts on the workbook itself and
    /// resolves no sheet at all (see the module doc comment).
    fn sheet_title(&self) -> Option<&str> {
        match self {
            Self::AddSheet { title, .. } => Some(title),
            Self::RenameSheet { sheet, .. }
            | Self::InsertRows { sheet, .. }
            | Self::InsertColumns { sheet, .. }
            | Self::InsertRange { sheet, .. }
            | Self::MoveRows { sheet, .. }
            | Self::MoveColumns { sheet, .. }
            | Self::DeleteSheet { sheet }
            | Self::DeleteRows { sheet, .. }
            | Self::DeleteColumns { sheet, .. }
            | Self::DeleteRange { sheet, .. }
            | Self::DuplicateSheet { sheet, .. }
            | Self::ReorderSheet { sheet, .. }
            | Self::SetSheetVisibility { sheet, .. }
            | Self::UpdateSheetProperties { sheet, .. } => Some(sheet),
            Self::UpdateWorkbookProperties { .. } => None,
        }
    }

    /// The title this verb moves the sheet *to*, or `None` for every verb
    /// that renames nothing.
    ///
    /// The companion to [`Self::sheet_title`], which necessarily reports the
    /// title a rename started from — without this the request log could say
    /// which tab was renamed but not to what, the one structural effect a
    /// record could not otherwise reconstruct. `DuplicateSheet`'s explicit
    /// `--title`, when given, is the same kind of fact for the same reason:
    /// the copy's name is not recoverable from `sheet_title` alone, which
    /// necessarily names the *source*.
    fn new_sheet_title(&self) -> Option<&String> {
        match self {
            Self::RenameSheet { new_title, .. } => Some(new_title),
            Self::DuplicateSheet { title, .. } => title.as_ref(),
            Self::AddSheet { .. }
            | Self::InsertRows { .. }
            | Self::InsertColumns { .. }
            | Self::InsertRange { .. }
            | Self::MoveRows { .. }
            | Self::MoveColumns { .. }
            | Self::DeleteSheet { .. }
            | Self::DeleteRows { .. }
            | Self::DeleteColumns { .. }
            | Self::DeleteRange { .. }
            | Self::ReorderSheet { .. }
            | Self::SetSheetVisibility { .. }
            | Self::UpdateSheetProperties { .. }
            | Self::UpdateWorkbookProperties { .. } => None,
        }
    }

    /// The axis an insert, a row/column delete or a row/column move runs
    /// along, or `None` for the verbs with no single axis (`add-sheet`,
    /// `rename-sheet`, `delete-sheet`, `delete-range`).
    const fn dimension(&self) -> Option<Dimension> {
        match self {
            Self::InsertRows { .. } | Self::DeleteRows { .. } | Self::MoveRows { .. } => {
                Some(Dimension::Rows)
            }
            Self::InsertColumns { .. } | Self::DeleteColumns { .. } | Self::MoveColumns { .. } => {
                Some(Dimension::Columns)
            }
            Self::AddSheet { .. }
            | Self::RenameSheet { .. }
            | Self::DeleteSheet { .. }
            | Self::InsertRange { .. }
            | Self::DeleteRange { .. }
            | Self::DuplicateSheet { .. }
            | Self::ReorderSheet { .. }
            | Self::SetSheetVisibility { .. }
            | Self::UpdateSheetProperties { .. }
            | Self::UpdateWorkbookProperties { .. } => None,
        }
    }
}

/// Per-call options.
#[derive(Debug, Clone)]
pub struct StructureOptions {
    /// Spreadsheet id.
    pub spreadsheet_id: String,
    /// Which mutation to perform.
    pub verb: StructureVerb,
    /// Classify and describe only; never call `batchUpdate`.
    pub dry_run: bool,
    /// The lease token presented via `--lease`. Checked only when the
    /// deciding rule requires one
    /// ([`write_gate::decided_rule_requires_lease`], ADR-0080 §1/§9);
    /// `None` is only ever valid when it does not.
    pub lease_token: Option<String>,
    /// Path to the lease ledger the token is checked against. Production
    /// callers pass `crate::drive::lease::ledger::ledger_path`'s own
    /// result; tests pass a path under a `tempdir`.
    pub ledger_path: PathBuf,
}

/// The sheet a verb resolved to, plus its dimensions at that moment.
///
/// Captured before the mutation so [`describe`] can state the *change*
/// ("1000 rows -> 1003") rather than only the request, which is the whole
/// point of a structural dry run.
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct SheetSnapshot {
    /// The sheet's stable numeric id.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sheet_id: Option<i64>,
    /// Its title at the time of the attempt.
    pub title: String,
    /// Allocated rows, when the API reported them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub row_count: Option<i64>,
    /// Allocated columns, when the API reported them.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub column_count: Option<i64>,
    /// Rows frozen at the top, when the API reported them (issue #1835).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frozen_row_count: Option<i64>,
    /// Columns frozen at the left, when the API reported them (issue #1835).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub frozen_column_count: Option<i64>,
    /// Whether the sheet is right-to-left, when the API reported it (issue
    /// #1835).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub right_to_left: Option<bool>,
    /// Whether gridlines are hidden, when the API reported it (issue #1835).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hide_gridlines: Option<bool>,
}

impl SheetSnapshot {
    fn from_properties(props: &SheetProperties) -> Self {
        let grid = props.grid_properties.as_ref();
        Self {
            sheet_id: props.sheet_id,
            title: props.title.clone(),
            row_count: grid.and_then(|g| g.row_count),
            column_count: grid.and_then(|g| g.column_count),
            frozen_row_count: grid.and_then(|g| g.frozen_row_count),
            frozen_column_count: grid.and_then(|g| g.frozen_column_count),
            right_to_left: props.right_to_left,
            hide_gridlines: grid.and_then(|g| g.hide_gridlines),
        }
    }
}

/// What happened (or, under `--dry-run`, would happen).
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
#[serde(tag = "status", rename_all = "kebab-case")]
pub enum StructureResult {
    /// `--dry-run`, and the gate would allow it.
    WouldChange {
        /// The target sheet as it stands now. `None` for an `add-sheet`,
        /// which has no existing sheet to snapshot.
        ///
        /// Boxed (issue #1835): `SheetSnapshot` grew enough with
        /// `update-sheet-properties`'s frozen-row/column and layout fields
        /// that this enum otherwise trips `clippy::result_large_err`, the
        /// same reasoning `Changed`'s own `backup` field is already boxed
        /// for.
        #[serde(skip_serializing_if = "Option::is_none")]
        sheet: Option<Box<SheetSnapshot>>,
        /// How many sheets the workbook currently has.
        sheet_count: usize,
    },
    /// The target is not a Google Sheet. Checked client-side before the
    /// gate: restructuring a PDF isn't disallowed, it's meaningless.
    RefusedNotASpreadsheet {
        /// The target's actual MIME type.
        mime_type: String,
    },
    /// The target is a shortcut, which we do not follow.
    RefusedShortcut,
    /// The target has no parents this account can see, so the folder gate
    /// has no ancestor chain to evaluate. Distinct from `Blocked`; see
    /// `write.rs`'s variant of the same name.
    RefusedNoVisibleParents,
    /// The named sheet does not exist in this workbook.
    ///
    /// Not the client-side validation ADR-0073 §7 rejects: §7 is about A1
    /// *grammar*, where a naive validator rejects legal forms. Here the
    /// server's own authoritative sheet list is already in hand, and without
    /// this check a `--dry-run` would promise a change the real run fails.
    RefusedSheetNotFound {
        /// The title that was not found.
        title: String,
        /// The titles that do exist, so the message can be actionable.
        available: Vec<String>,
    },
    /// `add-sheet` was given a title the workbook already uses, or
    /// `rename-sheet`'s new title collides with a *different* existing
    /// sheet. Sheets rejects a duplicate title, and catching it here keeps
    /// the dry run truthful.
    RefusedSheetExists {
        /// The colliding title.
        title: String,
    },
    /// A numeric argument (`--at`, `--count`, `--rows`, `--columns`,
    /// `--index`) is out of range for what the workbook actually contains —
    /// checked against the same `spreadsheets.get` response already fetched
    /// for the dry run, so this costs nothing extra and is exactly as
    /// correct as the server's own eventual rejection would be (ADR-0075
    /// §6's reasoning for the sheet-existence/duplicate-title checks,
    /// applied to a numeric bound instead of a title). Also reused for
    /// `update-workbook-properties`' argument-combination checks (issue
    /// #1836, e.g. "needs at least one property to set"), which need no
    /// workbook state at all — `format.rs::FormatResult::RefusedInvalidRange`
    /// is the same broadening for `format-cells`' "at least one property"
    /// check.
    RefusedInvalidRange {
        /// What was wrong and why.
        detail: String,
    },
    /// The folder write-permission gate refused it.
    Blocked {
        /// The rule that decided the refusal, if any (`None` means the bare
        /// default policy — every write defaults deny).
        decided_by: Option<DecidingRule>,
    },
    /// No `--lease` was presented, and the deciding rule requires one
    /// (ADR-0080 §9).
    RefusedNoLease,
    /// The presented lease has expired, or was never a token this ledger
    /// knows about.
    RefusedLeaseExpired,
    /// The presented lease is bound to a different file id.
    RefusedLeaseWrongFile,
    /// The file has moved since the lease's recorded `version` — the
    /// staleness check (ADR-0080 §6).
    RefusedLeaseStale,
    /// The workbook is already in the requested state (`hide-sheet` on a
    /// hidden sheet, `show-sheet` on a visible one), so no request is
    /// sent. Reported identically by a dry run and a real run, and
    /// distinct from `Changed` so a script can tell a no-op from a change.
    Unchanged {
        /// Why nothing needed to change.
        detail: String,
    },
    /// The mutation succeeded.
    Changed {
        /// The sheet acted on, as it stood *before* the change.
        ///
        /// Boxed for the same `clippy::result_large_err` reason as
        /// `WouldChange`'s own `sheet` field (issue #1835).
        #[serde(skip_serializing_if = "Option::is_none")]
        sheet: Option<Box<SheetSnapshot>>,
        /// The sheet id, which for `add-sheet` the server assigns and is
        /// only knowable from the reply.
        #[serde(skip_serializing_if = "Option::is_none")]
        sheet_id: Option<i64>,
        /// Where the lease this write presented backed the file up at
        /// `drive lease acquire` time — the copy to restore from after a
        /// destructive verb. `None` when the deciding write-permission
        /// rule set `require_lease: false`, in which case no backup was
        /// taken (ADR-0080 §13) and the outcome must not claim one.
        ///
        /// Read straight off the ledger record the write was checked
        /// against (`drive::lease::check::LeaseGrant`), never
        /// assumed, so the recovery message a real-run delete prints is
        /// only ever true. Boxed only to keep the enum under clippy's
        /// `result_large_err` threshold — `LeaseBackup::Bytes` carries a
        /// path plus a hash, and this enum is a `Result` error type inside
        /// the engine.
        #[serde(skip_serializing_if = "Option::is_none")]
        backup: Option<Box<LeaseBackup>>,
    },
    /// The API answered 2xx — the mutation **was applied** — but its reply
    /// could not be read (issue #2021). Distinct from [`Self::Failed`]: no
    /// structural verb is safe to re-run blind (a second `add-sheet` or
    /// `delete-rows` compounds). The server-assigned id of an added or
    /// duplicated sheet was in that reply, so it is unknown.
    AppliedReplyUnreadable {
        /// What was applied, e.g. `delete-rows 'Q2' (ROWS 5:7)`.
        summary: String,
        /// Why the reply could not be read.
        detail: String,
        /// The sheet acted on, as it stood *before* the change — plan-time
        /// data, so it survives the lost reply exactly as [`Self::Changed`]
        /// carries it.
        #[serde(skip_serializing_if = "Option::is_none")]
        sheet: Option<Box<SheetSnapshot>>,
        /// The target sheet's id, from the pre-resolved snapshot. `None` for
        /// `add-sheet`/`duplicate-sheet`, whose id [`Self::Changed`] reads
        /// from the reply — the one thing lost here.
        #[serde(skip_serializing_if = "Option::is_none")]
        sheet_id: Option<i64>,
        /// The lease backup, exactly as [`Self::Changed`]'s own `backup`
        /// field: a destructive verb's recovery note names it, since the
        /// delete happened whether or not its reply was readable.
        #[serde(skip_serializing_if = "Option::is_none")]
        backup: Option<Box<LeaseBackup>>,
    },
    /// An API or validation error.
    Failed {
        /// A human-readable summary of what failed.
        detail: String,
    },
}

impl FromLeaseRefusal for StructureResult {
    fn from_no_lease() -> Self {
        Self::RefusedNoLease
    }
    fn from_lease_expired() -> Self {
        Self::RefusedLeaseExpired
    }
    fn from_lease_wrong_file() -> Self {
        Self::RefusedLeaseWrongFile
    }
    fn from_lease_stale() -> Self {
        Self::RefusedLeaseStale
    }
    fn from_lease_failed(detail: String) -> Self {
        Self::Failed { detail }
    }
}

impl StructureResult {
    /// The `status` string the request log records.
    ///
    /// Hand-written rather than derived from the `#[serde(tag)]` shape,
    /// matching `WriteResult`/`MoveResult`'s precedent of keeping the log's
    /// vocabulary decoupled from the wire format.
    fn log_status(&self) -> &'static str {
        match self {
            Self::WouldChange { .. } => "would-change",
            Self::RefusedNotASpreadsheet { .. } => "refused-not-a-spreadsheet",
            Self::RefusedShortcut => "refused-shortcut",
            Self::RefusedNoVisibleParents => "refused-no-visible-parents",
            Self::RefusedSheetNotFound { .. } => "refused-sheet-not-found",
            Self::RefusedSheetExists { .. } => "refused-sheet-exists",
            Self::RefusedInvalidRange { .. } => "refused-invalid-range",
            Self::Blocked { .. } => "blocked",
            Self::RefusedNoLease => LeaseGateRefusal::NoLease.log_status(),
            Self::RefusedLeaseExpired => LeaseGateRefusal::Expired.log_status(),
            Self::RefusedLeaseWrongFile => LeaseGateRefusal::WrongFile.log_status(),
            Self::RefusedLeaseStale => LeaseGateRefusal::Stale.log_status(),
            Self::Unchanged { .. } => "unchanged",
            Self::Changed { .. } => "changed",
            Self::AppliedReplyUnreadable { .. } => "applied-reply-unreadable",
            Self::Failed { .. } => "failed",
        }
    }
}

/// The full outcome of one attempt.
///
/// `PartialEq`-only, not `Eq` (issue #1836) — it embeds [`StructureVerb`],
/// which is `PartialEq`-only for the same reason.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct StructureOutcome {
    /// The spreadsheet acted on.
    pub spreadsheet_id: String,
    /// Its Drive file name, when the metadata fetch got that far.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file_name: Option<String>,
    /// The folder the gate evaluated against, when exactly one parent
    /// resolved it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resolved_folder_id: Option<String>,
    /// Which mutation was attempted.
    ///
    /// Not serialised: the caller already knows which verb it invoked, and
    /// the JSON shape is a stable output contract. It is carried so
    /// [`describe`] can render an outcome from the outcome alone, rather
    /// than taking a verb a caller could mismatch against it.
    #[serde(skip)]
    pub verb: StructureVerb,
    /// What happened.
    pub result: StructureResult,
}

impl JsonlSerialize for StructureOutcome {
    fn write_jsonl(&self, out: &mut dyn std::io::Write) -> anyhow::Result<()> {
        write_scalar_jsonl(self, out)
    }
}

/// Converts a 1-based inclusive `--at` into the API's zero-based half-open
/// [`DimensionRange`].
///
/// The single conversion site, on purpose. `--at` is 1-based because that is
/// what A1 and the spreadsheet UI show the user; `DimensionRange` is
/// 0-based half-open because that is the API. Inlining this at a call site
/// is how the obvious off-by-one in this feature would get in.
fn dimension_range(sheet_id: i64, dimension: Dimension, at: i64, count: i64) -> DimensionRange {
    let start = at - 1;
    DimensionRange {
        sheet_id,
        dimension,
        start_index: start,
        end_index: start + count,
    }
}

/// Converts a 1-based `--before` into the API's zero-based, pre-move
/// `destinationIndex`.
///
/// The single conversion site, on purpose — see [`dimension_range`]'s doc
/// comment for why inlining this at a call site is how an off-by-one gets
/// in. `moveDimension` numbers its destination in the sheet's coordinates
/// *before* the source is lifted out, which is exactly what `--before`
/// means, so the conversion is the 1-based/0-based shift and nothing else.
const fn move_destination_index(before: i64) -> i64 {
    before - 1
}

/// The block's landing span after a move, given `--before`'s pre-move
/// numbering, the block's `count`, and its inclusive pre-move last index.
///
/// The single computation site, on purpose — [`describe_would_move`] (the
/// dry-run preview) and [`describe_moved`] (the real-run message) both need
/// it, and a formula duplicated between them could drift so the preview and
/// the confirmation disagree about where the block ended up.
/// `validate_move_bounds` refuses every `before` in `at..=at + count`, so
/// callers may assume exactly one of the two branches applies.
const fn move_landing_span(before: i64, count: i64, last: i64) -> (i64, i64) {
    if before > last {
        // Downward: the block lands immediately before where `before` used
        // to sit — `count` short of the number typed, since the rows/
        // columns between the block and the destination slide back to
        // close the gap.
        (before - count, before - 1)
    } else {
        // Upward (`before < at`): the block lands exactly on the number
        // typed.
        (before, before + count - 1)
    }
}

/// Runs one structural mutation, logging every attempt that isn't a dry run.
///
/// Never returns `Err`: every failure is a [`StructureResult`] variant, so
/// the caller renders one shape and the log records one shape. Exit code
/// stays 0 regardless, matching ADR-0073 §13.
pub async fn structure(
    drive: &DriveClient,
    sheets: &SheetsClient,
    opts: &StructureOptions,
    rules: &[FolderPermissionRule],
) -> StructureOutcome {
    let started = Instant::now();
    let outcome = structure_inner(drive, sheets, opts, rules).await;
    // The single logging site, and the only reason a dry run leaves no
    // record — `structure_inner` never logs.
    if !opts.dry_run {
        record_attempt(&outcome, opts, started.elapsed());
    }
    outcome
}

async fn structure_inner(
    drive: &DriveClient,
    sheets: &SheetsClient,
    opts: &StructureOptions,
    rules: &[FolderPermissionRule],
) -> StructureOutcome {
    let bare = |result| StructureOutcome {
        spreadsheet_id: opts.spreadsheet_id.clone(),
        file_name: None,
        resolved_folder_id: None,
        verb: opts.verb.clone(),
        result,
    };

    // ── Target resolution, pre-gate refusals, and the gate itself ──────
    // Shared with `write.rs` via `target_gate::resolve`, so this whole
    // shape — the metadata fetch, the shortcut/non-spreadsheet checks, and
    // the file-id-then-ancestor-chain gate lookup — can't quietly drift
    // between the two engines.
    let (target, decision, resolved_folder_id, requires_lease) = match target_gate::resolve(
        drive,
        &opts.spreadsheet_id,
        opts.verb.gate_operation(),
        rules,
    )
    .await
    {
        target_gate::TargetGateOutcome::MetadataFetchFailed { detail } => {
            return bare(StructureResult::Failed { detail })
        }
        target_gate::TargetGateOutcome::Refused { target, refusal } => {
            let result = match refusal {
                SheetTargetRefusal::Shortcut => StructureResult::RefusedShortcut,
                SheetTargetRefusal::NotASpreadsheet { mime_type } => {
                    StructureResult::RefusedNotASpreadsheet { mime_type }
                }
                SheetTargetRefusal::NoVisibleParents => StructureResult::RefusedNoVisibleParents,
            };
            return StructureOutcome {
                spreadsheet_id: opts.spreadsheet_id.clone(),
                file_name: Some(target.name),
                resolved_folder_id: None,
                verb: opts.verb.clone(),
                result,
            };
        }
        // A chain that could not be resolved is a refusal, never a silent
        // allow — ADR-0071 §3's highest-priority invariant.
        target_gate::TargetGateOutcome::GateFetchFailed { target, detail } => {
            return StructureOutcome {
                spreadsheet_id: opts.spreadsheet_id.clone(),
                file_name: Some(target.name),
                resolved_folder_id: None,
                verb: opts.verb.clone(),
                result: StructureResult::Failed { detail },
            };
        }
        target_gate::TargetGateOutcome::Gated {
            target,
            decision,
            resolved_folder_id,
            requires_lease,
        } => (target, decision, resolved_folder_id, requires_lease),
    };

    let gated = |result| StructureOutcome {
        spreadsheet_id: opts.spreadsheet_id.clone(),
        file_name: Some(target.name.clone()),
        resolved_folder_id: resolved_folder_id.clone(),
        verb: opts.verb.clone(),
        result,
    };

    if decision.verdict == write_gate::Verdict::Deny {
        return gated(StructureResult::Blocked {
            decided_by: decision.decided_by,
        });
    }

    // ── Resolve the workbook ───────────────────────────────────────────
    // After the gate on purpose: a blocked attempt makes zero Sheets calls,
    // preserving ADR-0073's "a refusal is exactly as auditable as a success"
    // consequence. This *is* a read, so a dry run reaches it — that is what
    // lets `describe` state real dimensions rather than guess.
    let api = SheetsApi::new(sheets);
    let workbook = match api.get_spreadsheet(&opts.spreadsheet_id).await {
        Ok(workbook) => workbook,
        Err(err) => {
            return gated(StructureResult::Failed {
                detail: format!("{err:#}"),
            })
        }
    };

    let sheet = match resolve_sheet(&workbook, &opts.verb) {
        Ok(sheet) => sheet,
        Err(result) => return gated(result),
    };
    let sheet_count = workbook.sheets.len();

    if let Err(result) = validate_verb_args(&workbook, &opts.verb, sheet.as_ref()) {
        return gated(result);
    }

    // Before the dry-run branch, so a dry run reports the no-op the real
    // run would, and before the lease check, since nothing is written.
    if let Some(detail) = already_applied(&workbook, &opts.verb, sheet.as_ref()) {
        return gated(StructureResult::Unchanged { detail });
    }

    if opts.dry_run {
        // A move, not a clone: this branch always returns, so `sheet` is
        // never read again on it — the later uses below are only reachable
        // on the disjoint non-dry-run path.
        return gated(StructureResult::WouldChange {
            sheet: sheet.map(Box::new),
            sheet_count,
        });
    }

    // ── The request ────────────────────────────────────────────────────
    // Built before the gate, not after: a sheet that resolved by title but
    // reported no `sheetId` (a server contract violation `build_request`
    // refuses on) is the one fallible step between here and the mutating
    // call, and the gate must be the *last* fallible step before it (see
    // `gate_leased_write`'s doc comment) — otherwise a request that was
    // always going to fail to build would still fsync a `pending` audit
    // record for a write that never happens (#1688).
    let request = match build_request(&opts.verb, sheet.as_ref()) {
        Ok(request) => request,
        Err(detail) => return gated(StructureResult::Failed { detail }),
    };

    // The lease check (ADR-0080 §9) sits here: after the permission gate
    // and the `--dry-run` branch, before the mutating call — see
    // `content_edit.rs::edit_inner`'s doc comment for the full reasoning,
    // shared verbatim by every leased engine. Sheets has no revision field
    // of any kind (§6), so the staleness check is a fresh `files.get`
    // immediately before `batchUpdate`, not a reuse of the metadata
    // `target_gate::resolve` fetched before the (potentially slow)
    // ancestor-chain walk and workbook fetch above.
    let files_api = FilesApi::new(drive);
    let leased = LeasedWrite {
        log_prefix: "drive sheets structure",
        operation: opts.verb.log_operation(),
        ledger_path: &opts.ledger_path,
        file_id: &opts.spreadsheet_id,
    };
    let lease_grant = match gate_optional_leased_write(
        leased,
        &files_api,
        requires_lease,
        opts.lease_token.as_deref(),
    )
    .await
    {
        Ok(grant) => grant,
        Err(err) => return gated(err.into_result()),
    };

    let result = match conclude_native_leased_write(
        leased,
        &lease_grant,
        &files_api,
        api.batch_update(&opts.spreadsheet_id, vec![request]).await,
        |err| format!("{err:#}"),
    )
    .await
    {
        Ok(BatchUpdateOutcome::Applied(response)) => StructureResult::Changed {
            sheet_id: added_sheet_id(&response).or_else(|| sheet.as_ref().and_then(|s| s.sheet_id)),
            sheet: sheet.map(Box::new),
            backup: lease_grant
                .as_ref()
                .map(|grant| Box::new(grant.backup.clone())),
        },
        // Every structural verb is `RetryHint::NotIdempotent` (see `describe_lines`).
        Ok(BatchUpdateOutcome::AppliedReplyUnreadable { detail }) => {
            StructureResult::AppliedReplyUnreadable {
                summary: applied_summary(&opts.verb),
                detail,
                // `Changed`'s fallback minus the reply: for an add/duplicate
                // the id `Changed` reports is the *new* sheet's, which only
                // the lost reply knew, so the source's id must not stand in.
                sheet_id: if adds_a_sheet(&opts.verb) {
                    None
                } else {
                    sheet.as_ref().and_then(|s| s.sheet_id)
                },
                sheet: sheet.map(Box::new),
                backup: lease_grant
                    .as_ref()
                    .map(|grant| Box::new(grant.backup.clone())),
            }
        }
        Err(err) => StructureResult::Failed {
            detail: format!("{err:#}"),
        },
    };
    drop(lease_grant);
    gated(result)
}

/// Finds the sheet a verb targets, or classifies why it cannot.
///
/// `add-sheet` inverts the check: it needs the title *not* to exist, and
/// returns `Ok(None)` because there is no existing sheet to snapshot.
/// `rename-sheet` checks both directions: the *current* title must exist,
/// and the *new* title must not already belong to some other sheet — the
/// same duplicate-title refusal `add-sheet` gets, since Sheets rejects a
/// duplicate title regardless of which verb produced it. Renaming a sheet
/// to the title it already has is not a collision (it names itself, not a
/// different sheet) and is allowed through as a no-op mutation.
///
/// `update-workbook-properties` returns `Ok(None)` immediately, before even
/// looking at the sheet list — [`StructureVerb::sheet_title`] returns `None`
/// for it, since it names no sheet at all.
fn resolve_sheet(
    workbook: &Spreadsheet,
    verb: &StructureVerb,
) -> Result<Option<SheetSnapshot>, StructureResult> {
    let Some(wanted) = verb.sheet_title() else {
        return Ok(None);
    };
    let found = workbook
        .sheets
        .iter()
        .filter_map(|sheet| sheet.properties.as_ref())
        .find(|props| props.title == wanted);

    match verb {
        StructureVerb::AddSheet { .. } => match found {
            Some(_) => Err(StructureResult::RefusedSheetExists {
                title: wanted.to_string(),
            }),
            None => Ok(None),
        },
        StructureVerb::RenameSheet { new_title, .. } => match found {
            Some(props) => {
                let collides = new_title != wanted && workbook.has_sheet_titled(new_title);
                if collides {
                    return Err(StructureResult::RefusedSheetExists {
                        title: new_title.clone(),
                    });
                }
                Ok(Some(SheetSnapshot::from_properties(props)))
            }
            None => Err(StructureResult::RefusedSheetNotFound {
                title: wanted.to_string(),
                available: workbook.sheet_titles(),
            }),
        },
        // Like `add-sheet`, a given `--title` must not already be in use —
        // and unlike `rename-sheet`, colliding with the *source's own*
        // title is still a collision: the source keeps its name, so a copy
        // asking for that same name would land on an existing sheet either
        // way.
        StructureVerb::DuplicateSheet { title, .. } => match found {
            Some(props) => {
                if let Some(new_title) = title {
                    let collides = workbook.has_sheet_titled(new_title);
                    if collides {
                        return Err(StructureResult::RefusedSheetExists {
                            title: new_title.clone(),
                        });
                    }
                }
                Ok(Some(SheetSnapshot::from_properties(props)))
            }
            None => Err(StructureResult::RefusedSheetNotFound {
                title: wanted.to_string(),
                available: workbook.sheet_titles(),
            }),
        },
        _ => match found {
            Some(props) => Ok(Some(SheetSnapshot::from_properties(props))),
            None => Err(StructureResult::RefusedSheetNotFound {
                title: wanted.to_string(),
                available: workbook.sheet_titles(),
            }),
        },
    }
}

/// Why `verb` would change nothing, when the workbook is already in the
/// state it asks for. Only `hide-sheet`/`show-sheet` can tell: their whole
/// effect is one flag the fetched workbook already reports.
fn already_applied(
    workbook: &Spreadsheet,
    verb: &StructureVerb,
    sheet: Option<&SheetSnapshot>,
) -> Option<String> {
    let StructureVerb::SetSheetVisibility {
        sheet: title,
        hidden,
    } = verb
    else {
        return None;
    };
    let target_id = sheet.and_then(|s| s.sheet_id)?;
    let currently_hidden = workbook
        .sheets
        .iter()
        .filter_map(|s| s.properties.as_ref())
        .find(|props| props.sheet_id == Some(target_id))?
        .hidden
        .unwrap_or(false);
    (currently_hidden == *hidden).then(|| {
        let state = if *hidden { "hidden" } else { "shown" };
        format!("sheet '{title}' is already {state}")
    })
}

/// Validates the numeric arguments a verb carries against the workbook's
/// actual state, so a dry run can never promise a change the real run then
/// rejects. Runs after [`resolve_sheet`] (which is why it can read the
/// target sheet's real dimensions) and before the `--dry-run` early return,
/// so both share this classification exactly like the gate above it.
fn validate_verb_args(
    workbook: &Spreadsheet,
    verb: &StructureVerb,
    sheet: Option<&SheetSnapshot>,
) -> Result<(), StructureResult> {
    let invalid = |detail: String| Err(StructureResult::RefusedInvalidRange { detail });

    match verb {
        StructureVerb::AddSheet {
            index,
            rows,
            columns,
            ..
        } => {
            if let Some(rows) = rows {
                if *rows < 1 {
                    return invalid(format!("--rows must be at least 1, got {rows}"));
                }
            }
            if let Some(columns) = columns {
                if *columns < 1 {
                    return invalid(format!("--columns must be at least 1, got {columns}"));
                }
            }
            if let Some(index) = index {
                let max = workbook.sheets.len() as i64;
                if *index < 0 || *index > max {
                    return invalid(format!(
                        "--index must be between 0 and {max} inclusive (the workbook has \
                         {max} sheet(s)), got {index}"
                    ));
                }
            }
            Ok(())
        }
        StructureVerb::RenameSheet { .. }
        | StructureVerb::DeleteSheet { .. }
        | StructureVerb::DuplicateSheet { index: None, .. }
        | StructureVerb::SetSheetVisibility { hidden: false, .. } => Ok(()),
        StructureVerb::InsertRows { at, count, .. } => {
            validate_insert_bounds(Dimension::Rows, *at, *count, sheet)
        }
        StructureVerb::InsertColumns { at, count, .. } => {
            validate_insert_bounds(Dimension::Columns, *at, *count, sheet)
        }
        StructureVerb::MoveRows {
            at, count, before, ..
        } => validate_move_bounds(Dimension::Rows, *at, *count, *before, sheet),
        StructureVerb::MoveColumns {
            at, count, before, ..
        } => validate_move_bounds(Dimension::Columns, *at, *count, *before, sheet),
        StructureVerb::DeleteRows { at, count, .. } => {
            validate_delete_dimension_bounds(Dimension::Rows, *at, *count, sheet)
        }
        StructureVerb::DeleteColumns { at, count, .. } => {
            validate_delete_dimension_bounds(Dimension::Columns, *at, *count, sheet)
        }
        StructureVerb::InsertRange {
            start_row,
            end_row,
            start_column,
            end_column,
            ..
        }
        | StructureVerb::DeleteRange {
            start_row,
            end_row,
            start_column,
            end_column,
            ..
        } => validate_range_bounds(*start_row, *end_row, *start_column, *end_column, sheet),
        StructureVerb::DuplicateSheet {
            index: Some(index), ..
        } => {
            // Same bound as `add-sheet`'s `--index`: a duplicate also adds
            // one sheet, so the valid positions are identical.
            let max = workbook.sheets.len() as i64;
            if *index < 0 || *index > max {
                return invalid(format!(
                    "--index must be between 0 and {max} inclusive (the workbook has \
                     {max} sheet(s)), got {index}"
                ));
            }
            Ok(())
        }
        StructureVerb::ReorderSheet { index, .. } => {
            // Unlike `add-sheet`/`duplicate-sheet`, this repositions an
            // *existing* sheet rather than adding one, so the top of the
            // valid range is one less.
            let len = workbook.sheets.len() as i64;
            let max = len - 1;
            if *index < 0 || *index > max {
                return invalid(format!(
                    "--index must be between 0 and {max} inclusive (the workbook has \
                     {len} sheet(s)), got {index}"
                ));
            }
            Ok(())
        }
        StructureVerb::SetSheetVisibility {
            sheet: title,
            hidden: true,
        } => {
            let target_id = sheet.and_then(|s| s.sheet_id);
            let another_stays_visible = workbook
                .sheets
                .iter()
                .filter_map(|s| s.properties.as_ref())
                .filter(|props| props.sheet_id != target_id)
                .any(|props| !props.hidden.unwrap_or(false));
            if !another_stays_visible {
                return invalid(format!(
                    "hiding '{title}' would leave the workbook with no visible sheets; \
                     Sheets requires at least one"
                ));
            }
            Ok(())
        }
        StructureVerb::UpdateSheetProperties {
            sheet: _title,
            freeze_rows,
            freeze_columns,
            tab_color,
            clear_tab_color,
            right_to_left,
            hide_gridlines,
        } => {
            if freeze_rows.is_none()
                && freeze_columns.is_none()
                && tab_color.is_none()
                && !clear_tab_color
                && right_to_left.is_none()
                && hide_gridlines.is_none()
            {
                return invalid(
                    "update-sheet-properties requires at least one property to change".to_string(),
                );
            }
            if tab_color.is_some() && *clear_tab_color {
                return invalid(
                    "--tab-color and --clear-tab-color are mutually exclusive".to_string(),
                );
            }
            if let Some(hex) = tab_color {
                if let Err(detail) = parse_hex_color(hex) {
                    return invalid(detail);
                }
            }
            if let Some(rows) = freeze_rows {
                check_freeze_bound(
                    "--freeze-rows",
                    "row",
                    *rows,
                    sheet.and_then(|s| s.row_count),
                )?;
            }
            if let Some(columns) = freeze_columns {
                check_freeze_bound(
                    "--freeze-columns",
                    "column",
                    *columns,
                    sheet.and_then(|s| s.column_count),
                )?;
            }
            Ok(())
        }
        StructureVerb::UpdateWorkbookProperties {
            locale,
            time_zone,
            auto_recalc,
            iterative_calculation,
            iterative_calculation_max_iterations,
            iterative_calculation_convergence_threshold,
        } => {
            let touches_iterative_settings = iterative_calculation_max_iterations.is_some()
                || iterative_calculation_convergence_threshold.is_some();
            if touches_iterative_settings
                && *iterative_calculation != Some(IterativeCalculationToggle::On)
            {
                return invalid(
                    "--iterative-calculation-max-iterations/\
                     --iterative-calculation-convergence-threshold require \
                     --iterative-calculation on"
                        .to_string(),
                );
            }
            if let Some(max_iterations) = iterative_calculation_max_iterations {
                if *max_iterations < 1 {
                    return invalid(format!(
                        "--iterative-calculation-max-iterations must be at least 1, got \
                         {max_iterations}"
                    ));
                }
            }
            if let Some(threshold) = iterative_calculation_convergence_threshold {
                if !threshold.is_finite() || *threshold <= 0.0 {
                    return invalid(format!(
                        "--iterative-calculation-convergence-threshold must be a positive, \
                         finite number, got {threshold}"
                    ));
                }
            }
            // Checked locally because the API will not: an unrecognised zone
            // is accepted with a 200 and the workbook is silently reset to
            // `Etc/GMT`, discarding its previous zone (issue #1938). An
            // unknown `--locale`, by contrast, is a 400 from the API.
            if let Some(tz) = time_zone {
                if tz.parse::<chrono_tz::Tz>().is_err() {
                    return invalid(format!(
                        "--time-zone '{tz}' is not a recognised IANA time zone name \
                         (for example 'America/New_York' or 'Europe/London'); the \
                         Sheets API would silently reset the workbook to 'Etc/GMT' \
                         instead of rejecting it"
                    ));
                }
            }
            if locale.is_none()
                && time_zone.is_none()
                && auto_recalc.is_none()
                && iterative_calculation.is_none()
            {
                return invalid(
                    "update-workbook-properties needs at least one property to set \
                     (--locale, --time-zone, --auto-recalc, --iterative-calculation)"
                        .to_string(),
                );
            }
            Ok(())
        }
    }
}

/// The `--count >= 1` / `--at >= 1` / overflow checks shared by
/// [`validate_insert_bounds`], [`validate_move_bounds`] and
/// [`validate_delete_dimension_bounds`] — every span-based verb needs them
/// verbatim, so they live in one place rather than three, and returns the
/// inclusive last index (`at - 1 + count`) so callers that need it (move,
/// delete) don't recompute it.
///
/// Keeps `dimension_range`'s `at - 1 + count` total, so the one pure
/// conversion stays infallible and every value that reaches it is already
/// known to fit. Deliberately an *arithmetic* bound and not a ceiling on how
/// many rows may be added: the workbook's own state implies no upper bound
/// on `--count`, so inventing one would be the client-side validation
/// ADR-0073 §7 rejects, with Sheets the authority on how large a sheet may
/// actually get.
fn validate_span_start(dimension: Dimension, at: i64, count: i64) -> Result<i64, StructureResult> {
    let invalid = |detail: String| StructureResult::RefusedInvalidRange { detail };

    if count < 1 {
        return Err(invalid(format!("--count must be at least 1, got {count}")));
    }
    if at < 1 {
        return Err(invalid(format!("--at must be at least 1, got {at}")));
    }
    at.checked_sub(1)
        .and_then(|start| start.checked_add(count))
        .ok_or_else(|| {
            invalid(format!(
                "--at {at} with --count {count} overflows the {noun} index space",
                noun = dimension.noun(),
            ))
        })
}

/// Validates a `--freeze-rows`/`--freeze-columns` value: non-negative, and,
/// when the sheet's current count is known, strictly less than it — Sheets
/// requires at least one row/column to stay unfrozen and rejects a request
/// that would freeze the whole grid. Shared by both flags in
/// [`validate_verb_args`]'s `UpdateSheetProperties` arm (issue #1835) so the
/// bound and its wording can't drift between them.
fn check_freeze_bound(
    flag: &str,
    noun: &str,
    value: i64,
    current: Option<i64>,
) -> Result<(), StructureResult> {
    if value < 0 {
        return Err(StructureResult::RefusedInvalidRange {
            detail: format!("{flag} must be at least 0, got {value}"),
        });
    }
    if let Some(current) = current {
        if value >= current {
            return Err(StructureResult::RefusedInvalidRange {
                detail: format!(
                    "{flag} {value} would freeze every {noun}; the sheet has {current} \
                     {noun}(s), so the most that can be frozen is {}",
                    current - 1
                ),
            });
        }
    }
    Ok(())
}

/// The `InsertRows`/`InsertColumns` half of [`validate_verb_args`], split
/// out so each caller supplies its own [`Dimension`] directly rather than
/// recovering it from the verb.
fn validate_insert_bounds(
    dimension: Dimension,
    at: i64,
    count: i64,
    sheet: Option<&SheetSnapshot>,
) -> Result<(), StructureResult> {
    let invalid = |detail: String| Err(StructureResult::RefusedInvalidRange { detail });

    validate_span_start(dimension, at, count)?;
    let current = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    };
    if let Some(current) = current {
        // `at == current + 1` is a legal append (insert after the last
        // row/column); anything past that names a position that does not
        // exist and is not immediately after one that does.
        let max_at = current + 1;
        if at > max_at {
            return invalid(format!(
                "--at {at} is past the end of the sheet, which has {current} {noun}(s); \
                 the furthest valid position is {max_at}",
                noun = dimension.noun(),
            ));
        }
    }
    Ok(())
}

/// The `MoveRows`/`MoveColumns` half of [`validate_verb_args`].
///
/// Three bounds, and the third is the one a move adds. The source block must
/// already exist in full (delete's rule), and `--before` may name the
/// append boundary one past the last row/column (insert's rule) — but a
/// destination *inside* the block, or immediately after it, describes a
/// position the block already occupies. `moveDimension` accepts those
/// happily and changes nothing, so refusing them is the same "never promise
/// a change the real run then rejects" rule read the other way round: never
/// report having moved something that did not move. That check needs no
/// sheet size, only the relationship between `--at`, `--count` and
/// `--before`, so it runs whether or not the sheet's dimensions are known.
fn validate_move_bounds(
    dimension: Dimension,
    at: i64,
    count: i64,
    before: i64,
    sheet: Option<&SheetSnapshot>,
) -> Result<(), StructureResult> {
    let invalid = |detail: String| Err(StructureResult::RefusedInvalidRange { detail });

    let last = validate_span_start(dimension, at, count)?;
    if before < 1 {
        return invalid(format!("--before must be at least 1, got {before}"));
    }
    // `before == at + count` is the no-op boundary: the block already sits
    // immediately before that row/column, so lifting it out and putting it
    // back lands it exactly where it was. `before == at - 1` is one further
    // out and is a real move.
    // `before - 1 <= last` rather than `before <= last + 1`: `last` is only
    // known not to overflow `at - 1 + count`, so adding to it could, while
    // `before` is already known to be at least 1.
    if before >= at && before - 1 <= last {
        return invalid(format!(
            "--before {before} is inside or immediately after the block being moved \
             ({noun}s {at}-{last}), so nothing would move",
            noun = dimension.noun(),
        ));
    }
    let current = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    };
    if let Some(current) = current {
        if last > current {
            return invalid(format!(
                "--at {at} with --count {count} reaches {noun} {last}, past the end of the \
                 sheet, which has {current} {noun}(s)",
                noun = dimension.noun(),
            ));
        }
        // The same append boundary insert allows: `before == current + 1`
        // moves the block to the very end.
        let max_before = current + 1;
        if before > max_before {
            return invalid(format!(
                "--before {before} is past the end of the sheet, which has {current} \
                 {noun}(s); the furthest valid position is {max_before}",
                noun = dimension.noun(),
            ));
        }
    }
    Ok(())
}

/// The `DeleteRows`/`DeleteColumns` half of [`validate_verb_args`].
///
/// Mirrors [`validate_insert_bounds`], but deletion has no append-boundary
/// case: every row/column named must already exist, so the exclusive end
/// index may never exceed the sheet's current size.
fn validate_delete_dimension_bounds(
    dimension: Dimension,
    at: i64,
    count: i64,
    sheet: Option<&SheetSnapshot>,
) -> Result<(), StructureResult> {
    let invalid = |detail: String| Err(StructureResult::RefusedInvalidRange { detail });

    let last = validate_span_start(dimension, at, count)?;
    let current = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    };
    if let Some(current) = current {
        if last > current {
            return invalid(format!(
                "--at {at} with --count {count} reaches {noun} {last}, past the end of the \
                 sheet, which has {current} {noun}(s)",
                noun = dimension.noun(),
            ));
        }
    }
    Ok(())
}

/// The `InsertRange`/`DeleteRange` half of [`validate_verb_args`].
///
/// Checks both axes are well-ordered and within the sheet's current bounds —
/// the same "never promise a change the real run then rejects" reasoning as
/// [`validate_insert_bounds`], applied to a rectangle instead of a span.
fn validate_range_bounds(
    start_row: i64,
    end_row: i64,
    start_column: i64,
    end_column: i64,
    sheet: Option<&SheetSnapshot>,
) -> Result<(), StructureResult> {
    let invalid = |detail: String| Err(StructureResult::RefusedInvalidRange { detail });

    if start_row < 1 {
        return invalid(format!("--start-row must be at least 1, got {start_row}"));
    }
    if start_column < 1 {
        return invalid(format!(
            "--start-column must be at least 1, got {start_column}"
        ));
    }
    if end_row < start_row {
        return invalid(format!(
            "--end-row ({end_row}) must be at or after --start-row ({start_row})"
        ));
    }
    if end_column < start_column {
        return invalid(format!(
            "--end-column ({end_column}) must be at or after --start-column ({start_column})"
        ));
    }
    if let Some(current) = sheet.and_then(|s| s.row_count) {
        if end_row > current {
            return invalid(format!(
                "--end-row {end_row} is past the end of the sheet, which has {current} row(s)"
            ));
        }
    }
    if let Some(current) = sheet.and_then(|s| s.column_count) {
        if end_column > current {
            return invalid(format!(
                "--end-column {end_column} is past the end of the sheet, which has {current} \
                 column(s)"
            ));
        }
    }
    Ok(())
}

/// Builds the single `batchUpdate` request a verb sends.
///
/// Every verb produces exactly one request, which is why partial application
/// is not observable here and why one log record per verb is also one record
/// per request.
fn build_request(
    verb: &StructureVerb,
    sheet: Option<&SheetSnapshot>,
) -> Result<BatchUpdateRequestItem, String> {
    // Every verb but `add-sheet` addresses a sheet by its numeric id, and
    // the `fields` mask on `spreadsheets.get` always requests it. A sheet
    // that resolved by title but reported no id is a server contract
    // violation, not a user error — fail rather than guess at 0, which is a
    // real sheet id.
    let sheet_id = |verb_name: &str| -> Result<i64, String> {
        sheet.and_then(|s| s.sheet_id).ok_or_else(|| {
            format!("Sheets did not report a sheetId for the target sheet, so {verb_name} cannot address it")
        })
    };

    match verb {
        StructureVerb::AddSheet {
            title,
            index,
            rows,
            columns,
        } => {
            let grid_properties = (rows.is_some() || columns.is_some()).then_some(GridProperties {
                row_count: *rows,
                column_count: *columns,
                ..Default::default()
            });
            Ok(BatchUpdateRequestItem::AddSheet(AddSheetRequest {
                properties: NewSheetProperties {
                    title: title.clone(),
                    index: *index,
                    grid_properties,
                },
            }))
        }
        StructureVerb::RenameSheet { new_title, .. } => Ok(
            BatchUpdateRequestItem::UpdateSheetProperties(UpdateSheetPropertiesRequest {
                properties: SheetPropertiesUpdate {
                    sheet_id: sheet_id("rename-sheet")?,
                    title: Some(new_title.clone()),
                    ..Default::default()
                },
                // Exactly the one field we set. A wider mask would blank
                // every property it named but we left unpopulated.
                fields: "title".to_string(),
            }),
        ),
        StructureVerb::InsertRows { at, count, .. } => Ok(BatchUpdateRequestItem::InsertDimension(
            InsertDimensionRequest {
                range: dimension_range(sheet_id("insert-rows")?, Dimension::Rows, *at, *count),
                inherit_from_before: false,
            },
        )),
        StructureVerb::InsertColumns { at, count, .. } => Ok(
            BatchUpdateRequestItem::InsertDimension(InsertDimensionRequest {
                range: dimension_range(
                    sheet_id("insert-columns")?,
                    Dimension::Columns,
                    *at,
                    *count,
                ),
                inherit_from_before: false,
            }),
        ),
        StructureVerb::InsertRange {
            start_row,
            end_row,
            start_column,
            end_column,
            shift,
            ..
        } => Ok(BatchUpdateRequestItem::InsertRange(InsertRangeRequest {
            range: grid_range(
                sheet_id("insert-range")?,
                *start_row,
                *end_row,
                *start_column,
                *end_column,
            ),
            shift_dimension: *shift,
        })),
        StructureVerb::MoveRows {
            at, count, before, ..
        } => Ok(BatchUpdateRequestItem::MoveDimension(
            MoveDimensionRequest {
                source: dimension_range(sheet_id("move-rows")?, Dimension::Rows, *at, *count),
                destination_index: move_destination_index(*before),
            },
        )),
        StructureVerb::MoveColumns {
            at, count, before, ..
        } => Ok(BatchUpdateRequestItem::MoveDimension(
            MoveDimensionRequest {
                source: dimension_range(sheet_id("move-columns")?, Dimension::Columns, *at, *count),
                destination_index: move_destination_index(*before),
            },
        )),
        StructureVerb::DeleteSheet { .. } => {
            Ok(BatchUpdateRequestItem::DeleteSheet(DeleteSheetRequest {
                sheet_id: sheet_id("delete-sheet")?,
            }))
        }
        StructureVerb::DeleteRows { at, count, .. } => Ok(BatchUpdateRequestItem::DeleteDimension(
            DeleteDimensionRequest {
                range: dimension_range(sheet_id("delete-rows")?, Dimension::Rows, *at, *count),
            },
        )),
        StructureVerb::DeleteColumns { at, count, .. } => Ok(
            BatchUpdateRequestItem::DeleteDimension(DeleteDimensionRequest {
                range: dimension_range(
                    sheet_id("delete-columns")?,
                    Dimension::Columns,
                    *at,
                    *count,
                ),
            }),
        ),
        StructureVerb::DeleteRange {
            start_row,
            end_row,
            start_column,
            end_column,
            shift,
            ..
        } => Ok(BatchUpdateRequestItem::DeleteRange(DeleteRangeRequest {
            range: grid_range(
                sheet_id("delete-range")?,
                *start_row,
                *end_row,
                *start_column,
                *end_column,
            ),
            shift_dimension: *shift,
        })),
        StructureVerb::DuplicateSheet { title, index, .. } => Ok(
            BatchUpdateRequestItem::DuplicateSheet(DuplicateSheetRequest {
                source_sheet_id: sheet_id("duplicate-sheet")?,
                insert_sheet_index: *index,
                new_sheet_name: title.clone(),
            }),
        ),
        StructureVerb::ReorderSheet { index, .. } => Ok(
            BatchUpdateRequestItem::UpdateSheetProperties(UpdateSheetPropertiesRequest {
                properties: SheetPropertiesUpdate {
                    sheet_id: sheet_id("reorder-sheet")?,
                    index: Some(*index),
                    ..Default::default()
                },
                fields: "index".to_string(),
            }),
        ),
        StructureVerb::SetSheetVisibility { hidden, .. } => Ok(
            BatchUpdateRequestItem::UpdateSheetProperties(UpdateSheetPropertiesRequest {
                properties: SheetPropertiesUpdate {
                    sheet_id: sheet_id(if *hidden { "hide-sheet" } else { "show-sheet" })?,
                    hidden: Some(*hidden),
                    ..Default::default()
                },
                fields: "hidden".to_string(),
            }),
        ),
        StructureVerb::UpdateSheetProperties {
            freeze_rows,
            freeze_columns,
            tab_color,
            clear_tab_color,
            right_to_left,
            hide_gridlines,
            ..
        } => {
            let mut fields = Vec::new();
            let mut grid = GridPropertiesUpdate::default();
            if let Some(rows) = freeze_rows {
                grid.frozen_row_count = Some(*rows);
                fields.push("gridProperties.frozenRowCount");
            }
            if let Some(columns) = freeze_columns {
                grid.frozen_column_count = Some(*columns);
                fields.push("gridProperties.frozenColumnCount");
            }
            if let Some(hide) = hide_gridlines {
                grid.hide_gridlines = Some(*hide);
                fields.push("gridProperties.hideGridlines");
            }
            let mut tab_color_style = None;
            if let Some(hex) = tab_color {
                // Already validated in `validate_verb_args`; re-parsing here
                // rather than threading the parsed `Color` through keeps this
                // function the sole place a request is assembled from a
                // verb, matching every sibling arm's shape.
                let color = parse_hex_color(hex)
                    .map_err(|detail| format!("update-sheet-properties: {detail}"))?;
                tab_color_style = Some(ColorStyle::rgb(color));
                fields.push("tabColorStyle");
            } else if *clear_tab_color {
                fields.push("tabColorStyle");
            }
            if right_to_left.is_some() {
                fields.push("rightToLeft");
            }
            if fields.is_empty() {
                // `validate_verb_args` already refuses this before
                // `build_request` is ever reached; this is an unreachable
                // defensive fallback, not a real path.
                // omni-dev: coverage ignore reason="validate_verb_args refuses an UpdateSheetProperties verb that set none of its six properties before structure_inner ever reaches build_request, and every one of those six pushes a fields entry, so fields is never empty here"
                return Err("update-sheet-properties: no property was set".to_string());
                // omni-dev: coverage end
            }
            Ok(BatchUpdateRequestItem::UpdateSheetProperties(
                UpdateSheetPropertiesRequest {
                    properties: SheetPropertiesUpdate {
                        sheet_id: sheet_id("update-sheet-properties")?,
                        grid_properties: (grid != GridPropertiesUpdate::default()).then_some(grid),
                        tab_color_style,
                        right_to_left: *right_to_left,
                        ..Default::default()
                    },
                    fields: fields.join(","),
                },
            ))
        }
        StructureVerb::UpdateWorkbookProperties {
            locale,
            time_zone,
            auto_recalc,
            iterative_calculation,
            iterative_calculation_max_iterations,
            iterative_calculation_convergence_threshold,
        } => {
            // `validate_verb_args` already refused an empty field set and
            // every invalid iterative-calculation combination, so every
            // branch below is infallible and `fields` is guaranteed
            // non-empty.
            let mut properties = SpreadsheetPropertiesUpdate::default();
            let mut fields = Vec::new();
            if let Some(locale) = locale {
                properties.locale = Some(locale.clone());
                fields.push("locale");
            }
            if let Some(time_zone) = time_zone {
                properties.time_zone = Some(time_zone.clone());
                fields.push("timeZone");
            }
            if let Some(auto_recalc) = auto_recalc {
                properties.auto_recalc = Some(*auto_recalc);
                fields.push("autoRecalc");
            }
            match iterative_calculation {
                Some(IterativeCalculationToggle::On) => {
                    properties.iterative_calculation_settings =
                        Some(IterativeCalculationSettings {
                            max_iterations: *iterative_calculation_max_iterations,
                            convergence_threshold: *iterative_calculation_convergence_threshold,
                        });
                    fields.push("iterativeCalculationSettings");
                }
                // `properties.iterative_calculation_settings` stays `None`
                // here, and `fields` still names the property — an absent
                // key on a masked field clears it, which is how "off" is
                // spelled (see `IterativeCalculationSettings`'s doc
                // comment).
                Some(IterativeCalculationToggle::Off) => {
                    fields.push("iterativeCalculationSettings");
                }
                None => {}
            }
            Ok(BatchUpdateRequestItem::UpdateSpreadsheetProperties(
                UpdateSpreadsheetPropertiesRequest {
                    properties,
                    fields: fields.join(","),
                },
            ))
        }
    }
}

/// A human-readable summary of the fields an `update-workbook-properties`
/// verb sets, e.g. `"locale -> 'en_US', auto-recalc -> ON_CHANGE"`.
///
/// Shared by the dry-run preview ([`describe_would_change`]), the real-run
/// confirmation ([`describe_changed`]) and the request log's
/// `fields_changed` (`record_attempt`), so the three can never describe a
/// different set of fields than the request actually carries — the same
/// "describe from one source of truth" discipline `dimension_range_label`/
/// `grid_range_label` use for the other structural verbs.
///
/// Panics if `verb` is not [`StructureVerb::UpdateWorkbookProperties`];
/// every call site matches on the verb first, so this is never reached
/// otherwise.
fn workbook_properties_summary(verb: &StructureVerb) -> String {
    let StructureVerb::UpdateWorkbookProperties {
        locale,
        time_zone,
        auto_recalc,
        iterative_calculation,
        iterative_calculation_max_iterations,
        iterative_calculation_convergence_threshold,
    } = verb
    // omni-dev: coverage ignore reason="every call site matches on the verb as UpdateWorkbookProperties before calling workbook_properties_summary, so this else-arm exists only to destructure the already-known variant"
    else {
        unreachable!("workbook_properties_summary called on a non-UpdateWorkbookProperties verb")
    };
    // omni-dev: coverage end

    let mut parts = Vec::new();
    if let Some(locale) = locale {
        parts.push(format!("locale -> '{locale}'"));
    }
    if let Some(time_zone) = time_zone {
        parts.push(format!("time zone -> '{time_zone}'"));
    }
    if let Some(auto_recalc) = auto_recalc {
        parts.push(format!("auto-recalc -> {}", auto_recalc.as_str()));
    }
    match iterative_calculation {
        Some(IterativeCalculationToggle::On) => {
            let bounds = IterativeCalculationSettings {
                max_iterations: *iterative_calculation_max_iterations,
                convergence_threshold: *iterative_calculation_convergence_threshold,
            }
            .describe_bounds();
            parts.push(format!("iterative calculation -> on{bounds}"));
        }
        Some(IterativeCalculationToggle::Off) => {
            parts.push("iterative calculation -> off".to_string());
        }
        None => {}
    }
    parts.join(", ")
}

/// Converts 1-based inclusive row/column bounds into the API's zero-based
/// half-open [`GridRange`]. The [`dimension_range`] of `DeleteRange`: the
/// single conversion site for the same reason.
fn grid_range(
    sheet_id: i64,
    start_row: i64,
    end_row: i64,
    start_column: i64,
    end_column: i64,
) -> GridRange {
    GridRange {
        sheet_id,
        start_row_index: Some(start_row - 1),
        end_row_index: Some(end_row),
        start_column_index: Some(start_column - 1),
        end_column_index: Some(end_column),
    }
}

/// The `sheetId` the server assigned to a newly added sheet, if this reply
/// carries one — via `addSheet` or `duplicateSheet`, whichever this batch
/// happened to contain (`structure.rs` never sends both in one request, so
/// there is no ambiguity to resolve between them).
fn added_sheet_id(response: &BatchUpdateResponse) -> Option<i64> {
    response
        .replies
        .iter()
        .find_map(|reply| reply.add_sheet.as_ref().or(reply.duplicate_sheet.as_ref()))
        .and_then(|added| added.properties.as_ref())
        .and_then(|props| props.sheet_id)
}

/// Whether this verb creates a sheet whose id the server assigns in the
/// reply (`addSheet`/`duplicateSheet`, the two [`added_sheet_id`] reads).
const fn adds_a_sheet(verb: &StructureVerb) -> bool {
    matches!(
        verb,
        StructureVerb::AddSheet { .. } | StructureVerb::DuplicateSheet { .. }
    )
}

/// What an [`StructureResult::AppliedReplyUnreadable`] says was applied,
/// e.g. `delete-rows 'Q2' (ROWS 5:7)` or `rename-sheet 'Q2' to 'Q3'` — the
/// verb the user typed plus the same sheet/span context the request log
/// records, so they know which part of the spreadsheet to check.
fn applied_summary(verb: &StructureVerb) -> String {
    let mut summary = verb.label().to_string();
    if let Some(title) = verb.sheet_title() {
        summary.push_str(&format!(" '{title}'"));
    }
    if let Some(new_title) = verb.new_sheet_title() {
        summary.push_str(&format!(" to '{new_title}'"));
    }
    if let Some(span) = dimension_range_label(verb).or_else(|| grid_range_label(verb)) {
        summary.push_str(&format!(" ({span})"));
    }
    summary
}

/// The `dimension_range` context value the request log records, e.g.
/// `"ROWS 5:7"` — the structural analogue of a cell verb's A1 `range`, for
/// effects A1 cannot express. 1-based inclusive, matching the CLI's `--at`.
///
/// Total over every `--at`/`--count` the CLI can parse, which is load-bearing
/// rather than defensive: [`record_attempt`] logs *attempts*, so this runs on
/// the refusal path too — with exactly the values
/// [`validate_insert_bounds`] just rejected. Arithmetic that only holds for
/// validated input would panic while recording the refusal of the input that
/// broke it. A span that cannot be computed is omitted (the log key is
/// omit-if-absent) rather than recorded inverted; the `refused-invalid-range`
/// status and its `detail` already carry the numbers the user typed.
fn dimension_range_label(verb: &StructureVerb) -> Option<String> {
    let dimension = verb.dimension()?;
    let (at, count) = match verb {
        StructureVerb::InsertRows { at, count, .. }
        | StructureVerb::InsertColumns { at, count, .. }
        | StructureVerb::DeleteRows { at, count, .. }
        | StructureVerb::DeleteColumns { at, count, .. }
        | StructureVerb::MoveRows { at, count, .. }
        | StructureVerb::MoveColumns { at, count, .. } => (*at, *count),
        _ => return None,
    };
    // A span is only meaningful for a positive count. `count < 1` is a
    // refusal `validate_insert_bounds` has already classified, and
    // `at + count - 1` computes cleanly for it while meaning nothing — an
    // *inverted* span, which is the misleading answer rather than the
    // missing one.
    if count < 1 {
        return None;
    }
    let end = at.checked_add(count).and_then(|end| end.checked_sub(1))?;
    Some(dimension.span_label(at, end))
}

/// The `grid_range` context value the request log records for a
/// `insert-range` or `delete-range` verb, e.g. `"rows 2-10, columns 2-4"` — 1-based inclusive,
/// matching the CLI's `--start-row`/`--end-row`/`--start-column`/
/// `--end-column`. `None` for every other verb.
fn grid_range_label(verb: &StructureVerb) -> Option<String> {
    match verb {
        StructureVerb::InsertRange {
            start_row,
            end_row,
            start_column,
            end_column,
            ..
        }
        | StructureVerb::DeleteRange {
            start_row,
            end_row,
            start_column,
            end_column,
            ..
        } => Some(format!(
            "rows {start_row}-{end_row}, columns {start_column}-{end_column}"
        )),
        _ => None,
    }
}

/// Emits the `kind: "drivemutation"` record.
///
/// Inside the engine, never the CLI layer, so a future MCP caller cannot
/// bypass it — and so a `Blocked` outcome, which makes zero Sheets calls,
/// still leaves a trace. Same reasoning as `write.rs::record_attempt`.
fn record_attempt(outcome: &StructureOutcome, opts: &StructureOptions, duration: Duration) {
    request_log::record_drive_mutation(mutation_record(outcome, opts, duration));
}

/// The record [`record_attempt`] emits, split out so a test can pin what an
/// outcome logs without reading the log file back.
fn mutation_record(
    outcome: &StructureOutcome,
    opts: &StructureOptions,
    duration: Duration,
) -> DriveMutationOutcome {
    let error = match &outcome.result {
        StructureResult::Failed { detail }
        | StructureResult::AppliedReplyUnreadable { detail, .. } => Some(detail.clone()),
        _ => None,
    };
    let decided_by = match &outcome.result {
        StructureResult::Blocked { decided_by } => decided_by.as_ref(),
        _ => None,
    };
    let decided_by = write_gate::decided_by_log_fields(decided_by);
    let sheet_id = match &outcome.result {
        StructureResult::Changed { sheet_id, .. }
        | StructureResult::AppliedReplyUnreadable { sheet_id, .. } => *sheet_id,
        StructureResult::WouldChange { sheet, .. } => sheet.as_ref().and_then(|s| s.sheet_id),
        _ => None,
    };
    // The destination `dimension_range` cannot carry: it names the span that
    // moved, not where it went.
    let move_to = match &opts.verb {
        StructureVerb::MoveRows { before, .. } | StructureVerb::MoveColumns { before, .. } => {
            Some(*before)
        }
        _ => None,
    };
    // `format.rs`'s field, reused here rather than duplicated: the only
    // structural verbs (issues #1835/#1836) that can set more than one
    // field in a single request, so `sheet_title`/`dimension_range`/
    // `grid_range` alone can't name the effect.
    //
    // An applied-but-unreadable write keeps the verb's own field list when it
    // has one (it names more than the summary does) and otherwise records
    // the summary, so every applied write says what it applied.
    let fields_changed = match &opts.verb {
        StructureVerb::UpdateWorkbookProperties { .. } => {
            Some(workbook_properties_summary(&opts.verb))
        }
        _ => fields_changed_label(&opts.verb),
    }
    .or_else(|| match &outcome.result {
        StructureResult::AppliedReplyUnreadable { summary, .. } => Some(summary.clone()),
        _ => None,
    });

    DriveMutationOutcome {
        operation: opts.verb.log_operation(),
        file_id: outcome.spreadsheet_id.clone(),
        file_name: outcome.file_name.clone().unwrap_or_default(),
        status: outcome.result.log_status().to_string(),
        resolved_folder_id: outcome.resolved_folder_id.clone(),
        decided_by_folder_id: decided_by.folder_id,
        decided_by_depth: decided_by.depth,
        decided_by_file_id: decided_by.file_id,
        sheet_id,
        sheet_title: opts.verb.sheet_title().map(ToString::to_string),
        sheet_new_title: opts.verb.new_sheet_title().map(ToString::to_string),
        dimension_range: dimension_range_label(&opts.verb),
        move_to,
        grid_range: grid_range_label(&opts.verb),
        fields_changed,
        error,
        duration,
        ..Default::default()
    }
}

/// The `fields_changed` context value the request log records for an
/// `update-sheet-properties` verb, e.g. `"frozenRowCount=2,
/// tabColorStyle=#FF8800"` — a comma-joined list of the properties this verb
/// set, reusing the `fields_changed` context key `format.rs` already writes
/// for `format-cells`/`update-borders`/etc. rather than adding a new one
/// (docs/log.md). `None` for every other verb.
///
/// Runs on the refusal path too, like [`dimension_range_label`]/
/// [`grid_range_label`]: `record_attempt` logs attempts, not only successes,
/// so this reports what the verb *asked* to change even when the request was
/// never built.
fn fields_changed_label(verb: &StructureVerb) -> Option<String> {
    let StructureVerb::UpdateSheetProperties {
        freeze_rows,
        freeze_columns,
        tab_color,
        clear_tab_color,
        right_to_left,
        hide_gridlines,
        ..
    } = verb
    else {
        return None;
    };
    let mut parts = Vec::new();
    if let Some(rows) = freeze_rows {
        parts.push(format!("frozenRowCount={rows}"));
    }
    if let Some(columns) = freeze_columns {
        parts.push(format!("frozenColumnCount={columns}"));
    }
    if let Some(hide) = hide_gridlines {
        parts.push(format!("hideGridlines={hide}"));
    }
    if let Some(hex) = tab_color {
        parts.push(format!("tabColorStyle={hex}"));
    } else if *clear_tab_color {
        parts.push("tabColorStyle=cleared".to_string());
    }
    if let Some(rtl) = right_to_left {
        parts.push(format!("rightToLeft={rtl}"));
    }
    if parts.is_empty() {
        return None;
    }
    Some(parts.join(", "))
}

/// Renders an outcome as human-readable text.
///
/// Joins [`describe_lines`]; see it for why the line structure, and not just
/// the finished string, is what this module produces.
#[must_use]
pub fn describe(outcome: &StructureOutcome) -> String {
    describe_lines(outcome).join("\n")
}

/// Renders an outcome as its individual lines, **none of which contains a
/// newline**.
///
/// Lives here rather than in the CLI layer so the CLI and a future MCP
/// caller describe an outcome identically.
///
/// The `WouldChange` arms are the substance of this module's answer to "what
/// does `--dry-run` show for an effect that isn't a range": the sheet's real
/// current dimensions, the resulting ones, and — for an insert — the shift
/// that no bounded range could express. That shift is a second line, which
/// is why this is the line list and `describe` the convenience over it.
///
/// Returning the lines rather than one pre-joined string is what lets the
/// CLI sanitize each one and then supply the separators itself. Every line
/// here interpolates untrusted text — a Drive-supplied file name, sheet
/// titles read out of the workbook, raw API error details — so a newline
/// arriving inside one of those values must not be able to pass for a line
/// break this module chose. Filtering a joined string cannot tell the two
/// apart; filtering the parts before joining them cannot confuse them.
/// `no_describe_line_contains_a_newline` pins the guarantee.
#[must_use]
pub fn describe_lines(outcome: &StructureOutcome) -> Vec<String> {
    let verb = &outcome.verb;
    let book = outcome.file_name.as_deref().map_or_else(
        || format!("'{}'", outcome.spreadsheet_id),
        |n| format!("'{n}'"),
    );

    match &outcome.result {
        StructureResult::WouldChange { sheet, sheet_count } => {
            describe_would_change(verb, sheet.as_deref(), *sheet_count, &book)
        }
        StructureResult::RefusedNotASpreadsheet { mime_type } => vec![format!(
            "Refused: {book} is not a Google Sheet (mimeType: {mime_type}); \
             `drive sheets {}` only works on spreadsheets",
            verb.label()
        )],
        StructureResult::RefusedShortcut => vec![format!(
            "Refused: {book} is a shortcut; `drive sheets {}` doesn't follow shortcuts — \
             resolve the target spreadsheet's id and use that instead",
            verb.label()
        )],
        StructureResult::RefusedNoVisibleParents => {
            let op = verb.gate_operation();
            vec![format!(
                "Refused: {book} has no parent folder visible to this account, so no folder \
                 rule can apply to it. This is normal for a Sheet shared by link or email. \
                 Grant it by id instead: add {{\"file_id\": \"<spreadsheet id>\", \"allow\": \
                 [\"{op}\"]}} to write_permissions.rules. (Adding it to a folder in your own \
                 Drive and granting that folder `{op}` also works.)"
            )]
        }
        StructureResult::RefusedSheetNotFound { title, available } => {
            vec![grid_range::no_sheet_refusal(&book, title, available)]
        }
        StructureResult::RefusedSheetExists { title } => {
            vec![format!(
                "Refused: {book} already has a sheet titled '{title}'"
            )]
        }
        StructureResult::RefusedInvalidRange { detail } => vec![format!("Refused: {detail}")],
        StructureResult::Blocked { decided_by } => {
            let op = verb.gate_operation();
            let action = if matches!(op, DriveOperation::SheetsDelete) {
                "destructive edits"
            } else {
                "structural edits"
            };
            vec![match decided_by {
                Some(rule) => format!(
                    "Blocked: {action} to {book} refused by rule on {} {}{}",
                    rule.kind_label(),
                    rule.id(),
                    rule.depth_suffix()
                ),
                None => format!(
                    "Blocked: {action} to {book} refused by default policy (no matching rule \
                     for {op})"
                ),
            }]
        }
        StructureResult::RefusedNoLease => LeaseGateRefusal::NoLease
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        StructureResult::RefusedLeaseExpired => LeaseGateRefusal::Expired
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        StructureResult::RefusedLeaseWrongFile => LeaseGateRefusal::WrongFile
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        StructureResult::RefusedLeaseStale => LeaseGateRefusal::Stale
            .describe_line(&outcome.spreadsheet_id, &book)
            .into_iter()
            .collect(),
        StructureResult::Changed {
            sheet,
            sheet_id,
            backup,
        } => {
            vec![describe_changed(
                verb,
                sheet.as_deref(),
                *sheet_id,
                backup.as_deref(),
                &book,
            )]
        }
        StructureResult::AppliedReplyUnreadable {
            summary,
            detail,
            sheet: _,
            sheet_id,
            backup,
        } => {
            // Not idempotent, for every verb: a second add/duplicate/insert/
            // delete compounds, and even a rename or reorder is only safe
            // once the user has seen what the first one did.
            // The ` (sheetId N)` suffix `describe_changed` gives, when known.
            let summary =
                sheet_id.map_or_else(|| summary.clone(), |id| format!("{summary} (sheetId {id})"));
            let mut first =
                applied_reply_unreadable_line(&summary, &book, RetryHint::NotIdempotent, detail);
            // The delete happened, so it owes the same recovery note
            // `describe_changed` gives a readable one.
            if matches!(verb.gate_operation(), DriveOperation::SheetsDelete) {
                let recovery = recovery_note(
                    backup.as_deref(),
                    matches!(verb, StructureVerb::DeleteSheet { .. }),
                );
                first.push_str(&format!("; {recovery}"));
            }
            let mut lines = vec![first];
            if adds_a_sheet(verb) {
                lines.push(
                    "  the new sheet's id was in the unreadable reply; check the spreadsheet's \
                     tabs to find it"
                        .to_string(),
                );
            }
            lines
        }
        StructureResult::Unchanged { detail } => vec![format!("Unchanged: {detail} in {book}")],
        StructureResult::Failed { detail } => vec![format!("Failed: {detail}")],
    }
}

fn describe_would_change(
    verb: &StructureVerb,
    sheet: Option<&SheetSnapshot>,
    sheet_count: usize,
    book: &str,
) -> Vec<String> {
    let id = sheet
        .and_then(|s| s.sheet_id)
        .map_or_else(String::new, |id| format!(" (sheetId {id})"));

    match verb {
        StructureVerb::AddSheet {
            title,
            index,
            rows,
            columns,
        } => {
            let size = match (rows, columns) {
                (Some(r), Some(c)) => format!(" ({r} x {c})"),
                (Some(r), None) => format!(" ({r} rows)"),
                (None, Some(c)) => format!(" ({c} columns)"),
                (None, None) => String::new(),
            };
            let position = index.map_or_else(
                || " at the end".to_string(),
                |index| format!(" at index {index}"),
            );
            vec![format!(
                "Would add sheet '{title}'{size}{position} of {book} \
                 ({sheet_count} sheet(s) -> {})",
                sheet_count + 1
            )]
        }
        StructureVerb::RenameSheet {
            sheet: from,
            new_title,
        } => {
            vec![format!(
                "Would rename sheet '{from}'{id} to '{new_title}' in {book}"
            )]
        }
        StructureVerb::InsertRows {
            sheet: from,
            at,
            count,
        } => describe_would_insert(Dimension::Rows, from, &id, *at, *count, sheet, book),
        StructureVerb::InsertColumns {
            sheet: from,
            at,
            count,
        } => describe_would_insert(Dimension::Columns, from, &id, *at, *count, sheet, book),
        StructureVerb::InsertRange {
            sheet: from,
            start_row,
            end_row,
            start_column,
            end_column,
            shift,
        } => vec![describe_would_insert_range(
            from,
            &id,
            *start_row,
            *end_row,
            *start_column,
            *end_column,
            *shift,
            book,
        )],
        StructureVerb::MoveRows {
            sheet: from,
            at,
            count,
            before,
        } => describe_would_move(
            Dimension::Rows,
            from,
            &id,
            *at,
            *count,
            *before,
            sheet,
            book,
        ),
        StructureVerb::MoveColumns {
            sheet: from,
            at,
            count,
            before,
        } => describe_would_move(
            Dimension::Columns,
            from,
            &id,
            *at,
            *count,
            *before,
            sheet,
            book,
        ),
        StructureVerb::DeleteSheet { sheet: from } => {
            vec![format!(
                "Would delete sheet '{from}'{id} from {book} ({sheet_count} sheet(s) -> {}); \
                 {FORMULA_CAVEAT}",
                sheet_count.saturating_sub(1)
            )]
        }
        StructureVerb::DeleteRows {
            sheet: from,
            at,
            count,
        } => describe_would_delete_dimension(Dimension::Rows, from, &id, *at, *count, sheet, book),
        StructureVerb::DeleteColumns {
            sheet: from,
            at,
            count,
        } => {
            describe_would_delete_dimension(Dimension::Columns, from, &id, *at, *count, sheet, book)
        }
        StructureVerb::DeleteRange {
            sheet: from,
            start_row,
            end_row,
            start_column,
            end_column,
            shift,
        } => vec![describe_would_delete_range(
            from,
            &id,
            *start_row,
            *end_row,
            *start_column,
            *end_column,
            *shift,
            book,
        )],
        StructureVerb::DuplicateSheet {
            sheet: from,
            title,
            index,
        } => {
            let to = title.as_deref().map_or_else(
                || " as a copy Sheets names automatically".to_string(),
                |title| format!(" as '{title}'"),
            );
            let position = index.map_or_else(
                // Confirmed against the live API: unlike `add-sheet`,
                // `duplicateSheetRequest` does not default to appending —
                // an omitted index lands the copy at the *front* (index 0).
                || " at the front (Sheets' default; not the end)".to_string(),
                |index| format!(" at index {index}"),
            );
            vec![format!(
                "Would duplicate sheet '{from}'{id}{to}{position} of {book} \
                 ({sheet_count} sheet(s) -> {})",
                sheet_count + 1
            )]
        }
        StructureVerb::ReorderSheet { sheet: from, index } => {
            vec![format!(
                "Would move sheet '{from}'{id} to index {index} in {book}"
            )]
        }
        StructureVerb::SetSheetVisibility {
            sheet: from,
            hidden,
        } => {
            let verb_word = if *hidden { "hide" } else { "show" };
            vec![format!("Would {verb_word} sheet '{from}'{id} in {book}")]
        }
        StructureVerb::UpdateSheetProperties {
            sheet: from,
            freeze_rows,
            freeze_columns,
            tab_color,
            clear_tab_color,
            right_to_left,
            hide_gridlines,
        } => {
            let fragments = update_sheet_properties_fragments(
                freeze_rows,
                freeze_columns,
                tab_color,
                *clear_tab_color,
                *right_to_left,
                *hide_gridlines,
                sheet,
            );
            vec![format!(
                "Would update sheet '{from}'{id} in {book}: {}",
                fragments.join(", ")
            )]
        }
        StructureVerb::UpdateWorkbookProperties { .. } => vec![format!(
            "Would update workbook properties of {book}: {}",
            workbook_properties_summary(verb)
        )],
    }
}

/// One `"<label> <before> -> <after>"` fragment, or `"<label> -> <after>"`
/// when `before` is `None` — the shape every `update-sheet-properties`
/// property reduces to (issue #1835). Shared so the four properties that
/// carry a "before" value from the snapshot can't phrase it four different
/// ways.
fn before_after_fragment(
    label: &str,
    before: Option<impl std::fmt::Display>,
    after: impl std::fmt::Display,
) -> String {
    match before {
        Some(before) => format!("{label} {before} -> {after}"),
        None => format!("{label} -> {after}"),
    }
}

/// The `hide_gridlines` before/after label: `true`/`false` read as
/// "hidden"/"shown" rather than as bare booleans.
fn gridlines_label(hidden: bool) -> &'static str {
    if hidden {
        "hidden"
    } else {
        "shown"
    }
}

/// The fragments shared by [`describe_would_change`]'s and
/// [`describe_changed`]'s `UpdateSheetProperties` arms (issue #1835) — one
/// per property the verb actually set, each stated as a before->after where
/// the snapshot knows the current value and as just the target otherwise.
/// Kept as one function so the dry-run preview and the real-run report can
/// never phrase the same effect two different ways.
fn update_sheet_properties_fragments(
    freeze_rows: &Option<i64>,
    freeze_columns: &Option<i64>,
    tab_color: &Option<String>,
    clear_tab_color: bool,
    right_to_left: Option<bool>,
    hide_gridlines: Option<bool>,
    sheet: Option<&SheetSnapshot>,
) -> Vec<String> {
    let mut fragments = Vec::new();
    if let Some(rows) = freeze_rows {
        fragments.push(before_after_fragment(
            "frozen rows",
            sheet.and_then(|s| s.frozen_row_count),
            rows,
        ));
    }
    if let Some(columns) = freeze_columns {
        fragments.push(before_after_fragment(
            "frozen columns",
            sheet.and_then(|s| s.frozen_column_count),
            columns,
        ));
    }
    if let Some(hex) = tab_color {
        fragments.push(format!("tab color -> {}", normalize_hex_for_display(hex)));
    } else if clear_tab_color {
        fragments.push("tab color cleared".to_string());
    }
    if let Some(rtl) = right_to_left {
        fragments.push(before_after_fragment(
            "right-to-left",
            sheet.and_then(|s| s.right_to_left),
            rtl,
        ));
    }
    if let Some(hide) = hide_gridlines {
        fragments.push(before_after_fragment(
            "gridlines",
            sheet.and_then(|s| s.hide_gridlines).map(gridlines_label),
            gridlines_label(hide),
        ));
    }
    fragments
}

/// The insert arms of [`describe_would_change`].
///
/// This is where a structural dry run earns its keep: it names the resulting
/// dimension *and* the shift, which is the part of the effect no bounded
/// range could express and the reason ADR-0073 §12 called this out.
// One parameter per fact the message needs (dimension, the two labels
// already formatted by the caller, the insert's own `at`/`count`, the
// target's dimensions, and the workbook name) — bundling them into a struct
// would just move the same fields one level out for a private helper with a
// single call site.
#[allow(clippy::too_many_arguments)]
fn describe_would_insert(
    dimension: Dimension,
    from: &str,
    id: &str,
    at: i64,
    count: i64,
    sheet: Option<&SheetSnapshot>,
    book: &str,
) -> Vec<String> {
    let summary = format!(
        "Would insert {count} {noun}(s) before {noun} {at} of '{from}'{id} in {book}",
        noun = dimension.noun(),
    );
    let before = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    };
    // The shift line is the trustworthy half of a structural preview, so it
    // is omitted outright when it cannot be stated — an unknown current size,
    // or a resulting size that does not fit. A wrong number here would be
    // worse than a missing one.
    let Some(before) = before else {
        return vec![summary];
    };
    let Some(after) = before.checked_add(count) else {
        return vec![summary];
    };
    // `at > before` only at the append boundary (`at == before + 1`,
    // enforced by `validate_verb_args`): there is nothing after the last
    // row/column to shift, so "existing N-M shift" would print an inverted,
    // self-contradictory range instead of the truth.
    let existing = if at <= before {
        format!(
            "; existing {plural} {at}-{before} shift {direction}",
            plural = plural(dimension),
            // An insert always pushes the existing rows/columns forward.
            direction = shift_word(dimension, true),
        )
    } else {
        format!(
            "; appended at the end, no existing {plural} shift",
            plural = plural(dimension)
        )
    };
    vec![
        summary,
        format!(
            "  ({before} {plural} -> {after}{existing})",
            plural = plural(dimension),
        ),
    ]
}

/// The move arms of [`describe_would_change`].
///
/// Same shape and the same reason as [`describe_would_insert`]: the summary
/// names the block and its destination, and the second line names the
/// shift — which for a move is the whole point, since `--before` is numbered
/// in the sheet's *pre-move* coordinates and the block therefore does not
/// land on the number the user typed. Spelling out where the block ends up,
/// and which rows/columns slid past it, is what stops that convention being
/// a trap.
// One parameter per fact the message needs, with a single call site — see
// `describe_would_insert`'s note.
#[allow(clippy::too_many_arguments)]
fn describe_would_move(
    dimension: Dimension,
    from: &str,
    id: &str,
    at: i64,
    count: i64,
    before: i64,
    sheet: Option<&SheetSnapshot>,
    book: &str,
) -> Vec<String> {
    let Some(last) = at.checked_add(count).and_then(|end| end.checked_sub(1)) else {
        return vec![format!(
            "Would move {count} {noun}(s) from {noun} {at} of '{from}'{id} in {book}",
            noun = dimension.noun(),
        )];
    };
    let summary = format!(
        "Would move {count} {noun}(s) {at}-{last} of '{from}'{id} in {book} to before \
         {noun} {before}",
        noun = dimension.noun(),
    );
    let current = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    };
    // The shift line is the trustworthy half of a structural preview, so it
    // is omitted outright when the current size is unknown rather than
    // guessed at — `describe_would_insert`'s rule.
    let Some(current) = current else {
        return vec![summary];
    };
    // `validate_move_bounds` refuses every `before` in `at..=at + count`, so
    // exactly one of these two branches applies. Each yields the same five
    // facts — the shifted range's old and new bounds, and which way it
    // moved — which the single `format!` below turns into the line.
    let (land_first, land_last) = move_landing_span(before, count, last);
    let (shift_first, shift_last, shifted_first, shifted_last, forward) = if before > last {
        // Downward: the rows/columns strictly between the block and the
        // destination slide back to close the gap — `count` short of the
        // number typed, which is the convention this line exists to spell
        // out.
        (last + 1, before - 1, at, before - 1 - count, false)
    } else {
        // Upward (`before < at`): the block lands exactly on the number
        // typed, and everything from there to the block's old start slides
        // forward by `count`.
        (before, at - 1, before + count, at - 1 + count, true)
    };
    let detail = format!(
        "  ({current} {plural} unchanged; {plural} {shift_first}-{shift_last} shift \
         {direction} to {shifted_first}-{shifted_last}; moved {plural} land at {land_first}-\
         {land_last})",
        plural = plural(dimension),
        direction = shift_word(dimension, forward),
    );
    vec![summary, detail]
}

/// A destructive `--dry-run` cannot check whether some formula elsewhere in
/// the workbook references what would be deleted — that would need reading
/// every other sheet's formulas, not just this verb's own target, and ADR-0077
/// keeps a destructive dry run structural-only (no extra `values.get` read,
/// no cell content in its output or the request log). This fixed caveat is
/// the honest substitute.
const FORMULA_CAVEAT: &str =
    "formulas elsewhere in the workbook that reference this may break, which cannot be \
     checked automatically";

/// Shared by [`describe_would_insert_range`] and [`describe_inserted_range`]
/// so the wording can't drift between the preview and the post-execution
/// message; tense differs (the dry run hasn't happened yet) so this is two
/// constants rather than one, unlike [`FORMULA_CAVEAT`].
const INSERT_RANGE_EDGE_CAVEAT_DRY_RUN: &str =
    "cells pushed past the sheet's grid extent may be dropped by Sheets";
const INSERT_RANGE_EDGE_CAVEAT: &str =
    "cells pushed past the sheet's grid extent may have been dropped by Sheets";

/// The `DeleteRows`/`DeleteColumns` arm of [`describe_would_change`].
///
/// Mirrors [`describe_would_insert`]'s shape (a summary line plus a shift
/// line), shrinking instead of growing and shifting the opposite direction.
/// Unlike insert, deletion has no append-boundary case — every row/column
/// named already exists — so the "nothing remains after" branch replaces
/// insert's "appended at the end" one.
#[allow(clippy::too_many_arguments)]
fn describe_would_delete_dimension(
    dimension: Dimension,
    from: &str,
    id: &str,
    at: i64,
    count: i64,
    sheet: Option<&SheetSnapshot>,
    book: &str,
) -> Vec<String> {
    let Some(last) = at.checked_add(count).and_then(|end| end.checked_sub(1)) else {
        return vec![format!(
            "Would delete {count} {noun}(s) from {noun} {at} of '{from}'{id} in {book}",
            noun = dimension.noun(),
        )];
    };
    let summary = format!(
        "Would delete {count} {noun}(s) {at}-{last} of '{from}'{id} in {book}",
        noun = dimension.noun(),
    );
    let before = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    };
    let Some(before) = before else {
        return vec![summary];
    };
    let Some(after) = before.checked_sub(count) else {
        return vec![summary];
    };
    let existing = if last < before {
        format!(
            "; existing {plural} {next}-{before} shift {direction}",
            plural = plural(dimension),
            next = last + 1,
            direction = shift_word(dimension, false),
        )
    } else {
        format!(
            "; nothing remains after the deleted {plural}",
            plural = plural(dimension)
        )
    };
    vec![
        summary,
        format!(
            "  ({before} {plural} -> {after}{existing}; {FORMULA_CAVEAT})",
            plural = plural(dimension),
        ),
    ]
}

/// The `DeleteRange` arm of [`describe_would_change`].
///
/// `deleteRange` never changes the sheet's `rowCount`/`columnCount` — it
/// shifts cells within the same bounded grid — so unlike the dimension
/// deletes there is no "before -> after" size line to add; the rectangle and
/// shift direction already say the whole effect in one line.
#[allow(clippy::too_many_arguments)]
fn describe_would_delete_range(
    from: &str,
    id: &str,
    start_row: i64,
    end_row: i64,
    start_column: i64,
    end_column: i64,
    shift: ShiftDimension,
    book: &str,
) -> String {
    let direction = shift_word(shift.into(), false);
    format!(
        "Would delete rows {start_row}-{end_row}, columns {start_column}-{end_column} of \
         '{from}'{id} in {book}, shifting remaining cells {direction} to close the gap; \
         {FORMULA_CAVEAT}"
    )
}

/// The `InsertRange` arm of [`describe_would_change`].
#[allow(clippy::too_many_arguments)]
fn describe_would_insert_range(
    from: &str,
    id: &str,
    start_row: i64,
    end_row: i64,
    start_column: i64,
    end_column: i64,
    shift: ShiftDimension,
    book: &str,
) -> String {
    let direction = shift_word(shift.into(), true);
    format!(
        "Would insert empty cells at rows {start_row}-{end_row}, columns {start_column}-{end_column} \
         of '{from}'{id} in {book}, shifting existing cells {direction}; \
         {INSERT_RANGE_EDGE_CAVEAT_DRY_RUN}"
    )
}

fn describe_changed(
    verb: &StructureVerb,
    sheet: Option<&SheetSnapshot>,
    sheet_id: Option<i64>,
    backup: Option<&LeaseBackup>,
    book: &str,
) -> String {
    let id = sheet_id.map_or_else(String::new, |id| format!(" (sheetId {id})"));
    let recovery = recovery_note(backup, matches!(verb, StructureVerb::DeleteSheet { .. }));
    match verb {
        StructureVerb::AddSheet { title, .. } => {
            format!("Added sheet '{title}'{id} to {book}")
        }
        StructureVerb::RenameSheet {
            sheet: from,
            new_title,
        } => {
            format!("Renamed sheet '{from}' to '{new_title}'{id} in {book}")
        }
        StructureVerb::InsertRows {
            sheet: from,
            at,
            count,
        } => describe_inserted(Dimension::Rows, from, &id, *at, *count, sheet, book),
        StructureVerb::InsertColumns {
            sheet: from,
            at,
            count,
        } => describe_inserted(Dimension::Columns, from, &id, *at, *count, sheet, book),
        StructureVerb::InsertRange {
            sheet: from,
            start_row,
            end_row,
            start_column,
            end_column,
            shift,
        } => describe_inserted_range(
            from,
            &id,
            *start_row,
            *end_row,
            *start_column,
            *end_column,
            *shift,
            book,
        ),
        StructureVerb::MoveRows {
            sheet: from,
            at,
            count,
            before,
        } => describe_moved(Dimension::Rows, from, &id, *at, *count, *before, book),
        StructureVerb::MoveColumns {
            sheet: from,
            at,
            count,
            before,
        } => describe_moved(Dimension::Columns, from, &id, *at, *count, *before, book),
        StructureVerb::DeleteSheet { sheet: from } => {
            format!("Deleted sheet '{from}'{id} from {book}; {recovery}")
        }
        StructureVerb::DeleteRows {
            sheet: from,
            at,
            count,
        } => describe_deleted_dimension(
            Dimension::Rows,
            from,
            &id,
            *at,
            *count,
            sheet,
            book,
            &recovery,
        ),
        StructureVerb::DeleteColumns {
            sheet: from,
            at,
            count,
        } => describe_deleted_dimension(
            Dimension::Columns,
            from,
            &id,
            *at,
            *count,
            sheet,
            book,
            &recovery,
        ),
        StructureVerb::DeleteRange {
            sheet: from,
            start_row,
            end_row,
            start_column,
            end_column,
            shift,
        } => describe_deleted_range(
            from,
            &id,
            *start_row,
            *end_row,
            *start_column,
            *end_column,
            *shift,
            book,
            &recovery,
        ),
        StructureVerb::DuplicateSheet {
            sheet: from, title, ..
        } => {
            let to = title
                .as_deref()
                .map_or_else(String::new, |title| format!(" as '{title}'"));
            format!("Duplicated sheet '{from}'{to}{id} in {book}")
        }
        StructureVerb::ReorderSheet { sheet: from, index } => {
            format!("Moved sheet '{from}'{id} to index {index} in {book}")
        }
        StructureVerb::SetSheetVisibility {
            sheet: from,
            hidden,
        } => {
            let verb_word = if *hidden { "Hid" } else { "Showed" };
            format!("{verb_word} sheet '{from}'{id} in {book}")
        }
        StructureVerb::UpdateSheetProperties {
            sheet: from,
            freeze_rows,
            freeze_columns,
            tab_color,
            clear_tab_color,
            right_to_left,
            hide_gridlines,
        } => {
            let fragments = update_sheet_properties_fragments(
                freeze_rows,
                freeze_columns,
                tab_color,
                *clear_tab_color,
                *right_to_left,
                *hide_gridlines,
                sheet,
            );
            format!(
                "Updated sheet '{from}'{id} in {book}: {}",
                fragments.join(", ")
            )
        }
        StructureVerb::UpdateWorkbookProperties { .. } => format!(
            "Updated workbook properties of {book}: {}",
            workbook_properties_summary(verb)
        ),
    }
}

/// The insert arms of [`describe_changed`].
// Same shape as `describe_would_insert`, for the same reason: one parameter
// per fact the message needs, with a single call site.
#[allow(clippy::too_many_arguments)]
fn describe_inserted(
    dimension: Dimension,
    from: &str,
    id: &str,
    at: i64,
    count: i64,
    sheet: Option<&SheetSnapshot>,
    book: &str,
) -> String {
    let now = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    }
    .and_then(|before| before.checked_add(count))
    .map_or_else(String::new, |after| {
        format!(" ({after} {} now)", plural(dimension))
    });
    format!(
        "Inserted {count} {noun}(s) before {noun} {at} of '{from}'{id} in {book}{now}",
        noun = dimension.noun(),
    )
}

/// The move arms of [`describe_changed`].
///
/// One line, like [`describe_inserted`], but it still names the landing
/// span: `--before` is pre-move numbering, so "moved rows 2-3 to before row
/// 6" alone would leave the reader to redo the arithmetic that
/// [`describe_would_move`] already does for the preview. It takes no
/// [`SheetSnapshot`], unlike every other `describe_*` helper here: a move
/// changes neither the row nor the column count, so there is no "now N
/// rows" tail the sheet's dimensions could supply — the landing span is
/// determined by the block's own numbers alone.
fn describe_moved(
    dimension: Dimension,
    from: &str,
    id: &str,
    at: i64,
    count: i64,
    before: i64,
    book: &str,
) -> String {
    let last = at.checked_add(count).and_then(|end| end.checked_sub(1));
    let range = last.map_or_else(|| at.to_string(), |last| format!("{at}-{last}"));
    let now = last.map_or_else(String::new, |last| {
        let (land_first, land_last) = move_landing_span(before, count, last);
        format!(" (now {} {land_first}-{land_last})", plural(dimension))
    });
    format!(
        "Moved {count} {noun}(s) {range} of '{from}'{id} in {book} to before {noun} \
         {before}{now}",
        noun = dimension.noun(),
    )
}

/// The `DeleteRows`/`DeleteColumns` arm of [`describe_changed`].
#[allow(clippy::too_many_arguments)]
fn describe_deleted_dimension(
    dimension: Dimension,
    from: &str,
    id: &str,
    at: i64,
    count: i64,
    sheet: Option<&SheetSnapshot>,
    book: &str,
    recovery: &str,
) -> String {
    let last = at.checked_add(count).and_then(|end| end.checked_sub(1));
    let range = last.map_or_else(|| at.to_string(), |last| format!("{at}-{last}"));
    let now = match dimension {
        Dimension::Rows => sheet.and_then(|s| s.row_count),
        Dimension::Columns => sheet.and_then(|s| s.column_count),
    }
    .and_then(|before| before.checked_sub(count))
    .map_or_else(String::new, |after| {
        format!(" ({after} {} now)", plural(dimension))
    });
    format!(
        "Deleted {count} {noun}(s) {range} of '{from}'{id} in {book}{now}; {recovery}",
        noun = dimension.noun(),
    )
}

/// The `DeleteRange` arm of [`describe_changed`].
#[allow(clippy::too_many_arguments)]
fn describe_deleted_range(
    from: &str,
    id: &str,
    start_row: i64,
    end_row: i64,
    start_column: i64,
    end_column: i64,
    shift: ShiftDimension,
    book: &str,
    recovery: &str,
) -> String {
    let direction = shift_word(shift.into(), false);
    format!(
        "Deleted rows {start_row}-{end_row}, columns {start_column}-{end_column} of '{from}'{id} \
         in {book}, shifted remaining cells {direction}; {recovery}"
    )
}

/// The `InsertRange` arm of [`describe_changed`].
#[allow(clippy::too_many_arguments)]
fn describe_inserted_range(
    from: &str,
    id: &str,
    start_row: i64,
    end_row: i64,
    start_column: i64,
    end_column: i64,
    shift: ShiftDimension,
    book: &str,
) -> String {
    let direction = shift_word(shift.into(), true);
    format!(
        "Inserted empty cells at rows {start_row}-{end_row}, columns {start_column}-{end_column} \
         of '{from}'{id} in {book}, shifting existing cells {direction}; \
         {INSERT_RANGE_EDGE_CAVEAT}"
    )
}

const fn plural(dimension: Dimension) -> &'static str {
    match dimension {
        Dimension::Rows => "rows",
        Dimension::Columns => "columns",
    }
}

/// The direction word for a shift along `dimension`: `forward` is the
/// direction rows/columns move when something is inserted or a block moves
/// upward past them (`down`/`right`); the other way (a downward move's
/// displaced rows/columns closing the gap, or a deletion closing the gap
/// left behind) is `!forward` (`up`/`left`). Shared by every `describe_*`
/// preview/post-execution message in this module (insert, move, delete
/// dimension, delete/insert range) so the direction vocabulary can't drift
/// apart between them.
const fn shift_word(dimension: Dimension, forward: bool) -> &'static str {
    match (dimension, forward) {
        (Dimension::Rows, true) => "down",
        (Dimension::Rows, false) => "up",
        (Dimension::Columns, true) => "right",
        (Dimension::Columns, false) => "left",
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::sheets::client::SHEETS_API_URL;
    use crate::drive::test_support::{seed_lease, seed_lease_with_backup};
    use crate::drive::types::GOOGLE_SHEET_MIME_TYPE;
    use crate::drive::write_gate::Verdict;
    use crate::test_support::env::MapEnv;
    use crate::utils::secret::Secret;
    use std::collections::HashSet;

    fn test_credentials() -> DriveCredentials {
        DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        }
    }

    /// Both clients against one wiremock server, sharing an OAuth session.
    ///
    /// `replace_session` must run before the derive: it swaps the Drive
    /// client's whole transport, so deriving first would leave the Sheets
    /// client pointed at the real `oauth2.googleapis.com`.
    async fn clients(server: &wiremock::MockServer) -> (DriveClient, SheetsClient) {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token", "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;
        let mut drive = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut drive,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        let env = MapEnv::new().with(SHEETS_API_URL, &server.uri());
        let sheets = SheetsClient::from_drive_client_with(&env, &drive).unwrap();
        (drive, sheets)
    }

    /// `version: "1"` throughout — matches [`opts`]'s default seeded
    /// lease, so any test reaching the mutating call has a live, non-stale
    /// lease by construction (ADR-0080 §9).
    fn mount_file(id: &str, mime_type: &str, parents: &[&str]) -> wiremock::Mock {
        let parents: Vec<&str> = parents.to_vec();
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!("/drive/v3/files/{id}")))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": id, "name": id, "mimeType": mime_type, "parents": parents,
                    "version": "1",
                })),
            )
    }

    fn mount_folder(id: &str) -> wiremock::Mock {
        mount_file(id, "application/vnd.google-apps.folder", &[])
    }

    fn allow_rule(folder: &str) -> FolderPermissionRule {
        FolderPermissionRule {
            folder_id: Some(folder.to_string()),
            file_id: None,
            recursive: true,
            allow: std::iter::once(DriveOperation::SheetsStructure).collect(),
            deny: HashSet::default(),
            require_lease: true,
        }
    }

    /// The `spreadsheets.get` reply body shared by [`mount_workbook`] and
    /// its variants: `Q1` (1000 x 26) fixed, plus whatever `Q2` object the
    /// caller supplies — the one thing every variant actually varies.
    fn workbook_body(q2: serde_json::Value) -> serde_json::Value {
        serde_json::json!({
            "spreadsheetId": "sheet-1",
            "properties": {"title": "Budget"},
            "sheets": [
                {"properties": {
                    "sheetId": 0, "title": "Q1", "index": 0,
                    "gridProperties": {"rowCount": 1000, "columnCount": 26}}},
                q2,
            ],
        })
    }

    /// The `Q2` sheet object [`mount_workbook`] mounts: 500 x 10, no extra
    /// properties.
    fn default_q2() -> serde_json::Value {
        serde_json::json!({"properties": {
            "sheetId": 118_293, "title": "Q2", "index": 1,
            "gridProperties": {"rowCount": 500, "columnCount": 10}}})
    }

    /// [`default_q2`], but hidden — what `show-sheet` needs to have
    /// something to show.
    fn hidden_q2() -> serde_json::Value {
        serde_json::json!({"properties": {
            "sheetId": 118_293, "title": "Q2", "index": 1, "hidden": true,
            "gridProperties": {"rowCount": 500, "columnCount": 10}}})
    }

    /// A `spreadsheets.get` reply with two sheets, `Q1` (1000 x 26) and
    /// `Q2` (500 x 10).
    fn mount_workbook() -> wiremock::Mock {
        mount_workbook_with_q2(default_q2())
    }

    fn mount_batch_update(body: serde_json::Value) -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(body))
    }

    /// Seeds a fresh, isolated ledger with a live lease for `"sheet-1"` at
    /// version `"1"` (matching [`mount_file`]'s default) and returns
    /// options carrying it. Every existing test built before the lease
    /// (ADR-0080 §9) reaches its mutating call this way by construction —
    /// see [`opts_for`]'s doc comment for why this doesn't need touching
    /// each test individually. A test exercising the lease *refusal* paths
    /// builds `StructureOptions` directly instead (see the
    /// "the Drive write lease" test section below).
    fn opts(verb: StructureVerb, dry_run: bool) -> StructureOptions {
        opts_for("sheet-1", verb, dry_run)
    }

    /// [`opts`], generalised over the spreadsheet id.
    ///
    /// The backing ledger directory is deliberately leaked (`into_path`,
    /// not dropped) rather than threaded through every caller as a
    /// `tempfile::TempDir` binding: it must outlive the `.await` on
    /// `structure(...)`, and plumbing that lifetime through several dozen
    /// pre-existing tests — none of which are *about* the lease — would
    /// dwarf the fix in size for no reviewing benefit. The leak costs a
    /// few bytes of `/tmp` per test process, cleaned up by the OS.
    fn opts_for(spreadsheet_id: &str, verb: StructureVerb, dry_run: bool) -> StructureOptions {
        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, spreadsheet_id, "1");
        StructureOptions {
            spreadsheet_id: spreadsheet_id.to_string(),
            verb,
            dry_run,
            lease_token: Some(token),
            ledger_path,
        }
    }

    fn rename() -> StructureVerb {
        StructureVerb::RenameSheet {
            sheet: "Q2".to_string(),
            new_title: "Q3".to_string(),
        }
    }

    fn insert_rows() -> StructureVerb {
        StructureVerb::InsertRows {
            sheet: "Q2".to_string(),
            at: 5,
            count: 3,
        }
    }

    /// Rows 2-3 of `Q2` moved to before row 6 — a downward move, the case
    /// where `--before`'s pre-move numbering and the block's landing
    /// position differ.
    fn move_rows() -> StructureVerb {
        StructureVerb::MoveRows {
            sheet: "Q2".to_string(),
            at: 2,
            count: 2,
            before: 6,
        }
    }

    fn add_sheet() -> StructureVerb {
        StructureVerb::AddSheet {
            title: "Q3".to_string(),
            index: None,
            rows: None,
            columns: None,
        }
    }

    fn delete_sheet() -> StructureVerb {
        StructureVerb::DeleteSheet {
            sheet: "Q2".to_string(),
        }
    }

    fn delete_rows() -> StructureVerb {
        StructureVerb::DeleteRows {
            sheet: "Q2".to_string(),
            at: 5,
            count: 3,
        }
    }

    fn delete_columns() -> StructureVerb {
        StructureVerb::DeleteColumns {
            sheet: "Q2".to_string(),
            at: 3,
            count: 2,
        }
    }

    fn insert_range() -> StructureVerb {
        StructureVerb::InsertRange {
            sheet: "Q2".to_string(),
            start_row: 2,
            end_row: 4,
            start_column: 2,
            end_column: 3,
            shift: ShiftDimension::Rows,
        }
    }

    /// [`insert_range`]'s twin with the other shift axis, so the `COLUMNS`
    /// wire value and "shift ... right" wording get exercised too — `Rows`
    /// is otherwise the only [`ShiftDimension`] any test ever names, mirroring
    /// [`delete_range_columns_shift`].
    fn insert_range_columns_shift() -> StructureVerb {
        StructureVerb::InsertRange {
            sheet: "Q2".to_string(),
            start_row: 2,
            end_row: 4,
            start_column: 2,
            end_column: 3,
            shift: ShiftDimension::Columns,
        }
    }

    fn delete_range() -> StructureVerb {
        StructureVerb::DeleteRange {
            sheet: "Q2".to_string(),
            start_row: 2,
            end_row: 4,
            start_column: 2,
            end_column: 3,
            shift: ShiftDimension::Rows,
        }
    }

    /// [`delete_range`]'s twin with the other shift axis, so the `COLUMNS`
    /// wire value and "shift ... left" wording get exercised too — `Rows` is
    /// otherwise the only [`ShiftDimension`] any test ever names.
    fn delete_range_columns_shift() -> StructureVerb {
        StructureVerb::DeleteRange {
            sheet: "Q2".to_string(),
            start_row: 2,
            end_row: 4,
            start_column: 2,
            end_column: 3,
            shift: ShiftDimension::Columns,
        }
    }

    fn duplicate_sheet() -> StructureVerb {
        StructureVerb::DuplicateSheet {
            sheet: "Q2".to_string(),
            title: Some("Q2 Copy".to_string()),
            index: Some(1),
        }
    }

    fn duplicate_sheet_default() -> StructureVerb {
        StructureVerb::DuplicateSheet {
            sheet: "Q2".to_string(),
            title: None,
            index: None,
        }
    }

    fn reorder_sheet() -> StructureVerb {
        StructureVerb::ReorderSheet {
            sheet: "Q2".to_string(),
            index: 0,
        }
    }

    fn hide_sheet() -> StructureVerb {
        StructureVerb::SetSheetVisibility {
            sheet: "Q2".to_string(),
            hidden: true,
        }
    }

    fn show_sheet() -> StructureVerb {
        StructureVerb::SetSheetVisibility {
            sheet: "Q2".to_string(),
            hidden: false,
        }
    }

    fn update_workbook_properties() -> StructureVerb {
        StructureVerb::UpdateWorkbookProperties {
            locale: Some("en_US".to_string()),
            time_zone: Some("America/New_York".to_string()),
            auto_recalc: Some(RecalculationInterval::OnChange),
            iterative_calculation: None,
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: None,
        }
    }

    fn delete_allow_rule(folder: &str) -> FolderPermissionRule {
        FolderPermissionRule {
            folder_id: Some(folder.to_string()),
            file_id: None,
            recursive: true,
            allow: std::iter::once(DriveOperation::SheetsDelete).collect(),
            deny: HashSet::default(),
            require_lease: true,
        }
    }

    // ── the safety property this module now enforces ───────────────────
    //
    // ADR-0075 §3/§4 kept every destructive `batchUpdate` request
    // unreachable at the type level, pinned by a
    // `no_destructive_request_is_reachable` grep-guard test. ADR-0077
    // (issue #1623) supersedes that: the requests are now reachable, but
    // only through `StructureVerb::gate_operation` routing them to
    // `DriveOperation::SheetsDelete` — never `SheetsStructure`, and never
    // through a raw passthrough (there still isn't one). The tests below are
    // what replace the old grep-guard: they pin the *new* invariant instead
    // of the old absence.

    #[test]
    fn every_delete_verb_gates_on_sheets_delete_not_sheets_structure() {
        for verb in [
            StructureVerb::DeleteSheet {
                sheet: "Q1".to_string(),
            },
            StructureVerb::DeleteRows {
                sheet: "Q1".to_string(),
                at: 1,
                count: 1,
            },
            StructureVerb::DeleteColumns {
                sheet: "Q1".to_string(),
                at: 1,
                count: 1,
            },
            StructureVerb::DeleteRange {
                sheet: "Q1".to_string(),
                start_row: 1,
                end_row: 2,
                start_column: 1,
                end_column: 2,
                shift: ShiftDimension::Rows,
            },
        ] {
            assert_eq!(verb.gate_operation(), DriveOperation::SheetsDelete);
        }
    }

    #[test]
    fn every_additive_verb_still_gates_on_sheets_structure() {
        for verb in [
            add_sheet(),
            StructureVerb::RenameSheet {
                sheet: "Q1".to_string(),
                new_title: "Q2".to_string(),
            },
            StructureVerb::InsertRows {
                sheet: "Q1".to_string(),
                at: 1,
                count: 1,
            },
            StructureVerb::InsertColumns {
                sheet: "Q1".to_string(),
                at: 1,
                count: 1,
            },
            StructureVerb::InsertRange {
                sheet: "Q1".to_string(),
                start_row: 1,
                end_row: 2,
                start_column: 1,
                end_column: 2,
                shift: ShiftDimension::Rows,
            },
            StructureVerb::MoveRows {
                sheet: "Q1".to_string(),
                at: 1,
                count: 1,
                before: 3,
            },
            StructureVerb::MoveColumns {
                sheet: "Q1".to_string(),
                at: 1,
                count: 1,
                before: 3,
            },
            StructureVerb::DuplicateSheet {
                sheet: "Q1".to_string(),
                title: None,
                index: None,
            },
            StructureVerb::ReorderSheet {
                sheet: "Q1".to_string(),
                index: 0,
            },
            StructureVerb::SetSheetVisibility {
                sheet: "Q1".to_string(),
                hidden: true,
            },
            StructureVerb::UpdateSheetProperties {
                sheet: "Q1".to_string(),
                freeze_rows: None,
                freeze_columns: None,
                tab_color: None,
                clear_tab_color: false,
                right_to_left: Some(true),
                hide_gridlines: None,
            },
            StructureVerb::UpdateWorkbookProperties {
                locale: Some("en_US".to_string()),
                time_zone: None,
                auto_recalc: None,
                iterative_calculation: None,
                iterative_calculation_max_iterations: None,
                iterative_calculation_convergence_threshold: None,
            },
        ] {
            assert_eq!(verb.gate_operation(), DriveOperation::SheetsStructure);
        }
    }

    // ── the 1-based/0-based conversion, the obvious off-by-one ─────────

    #[test]
    fn at_is_one_based_inclusive_and_becomes_zero_based_half_open() {
        // "insert 3 rows before row 5" == indices [4, 7).
        let range = dimension_range(7, Dimension::Rows, 5, 3);
        assert_eq!(range.start_index, 4);
        assert_eq!(range.end_index, 7);
        assert_eq!(range.sheet_id, 7);
        assert_eq!(range.dimension, Dimension::Rows);
    }

    #[test]
    fn inserting_at_row_one_starts_at_index_zero() {
        // The boundary case, and the reason `inherit_from_before` is fixed
        // at false: the API rejects `true` when start_index is 0.
        let range = dimension_range(0, Dimension::Rows, 1, 1);
        assert_eq!(range.start_index, 0);
        assert_eq!(range.end_index, 1);
    }

    #[test]
    fn a_single_insert_spans_exactly_one_index() {
        let range = dimension_range(0, Dimension::Columns, 3, 1);
        assert_eq!((range.start_index, range.end_index), (2, 3));
    }

    #[test]
    fn dimension_range_label_is_one_based_inclusive_like_the_flag() {
        // Insert 3 rows at row 5 => rows 5, 6, 7 are the new ones.
        assert_eq!(
            dimension_range_label(&insert_rows()).as_deref(),
            Some("ROWS 5:7")
        );
        assert_eq!(
            dimension_range_label(&StructureVerb::InsertColumns {
                sheet: "Q2".to_string(),
                at: 2,
                count: 1,
            })
            .as_deref(),
            Some("COLUMNS 2:2")
        );
        // Verbs that span no dimension record none.
        assert_eq!(dimension_range_label(&rename()), None);
        assert_eq!(dimension_range_label(&add_sheet()), None);
    }

    #[test]
    fn dimension_range_label_omits_a_span_it_cannot_compute() {
        // `record_attempt` logs attempts, refused ones included, so this is
        // reached with arguments no validation let through. An uncomputable
        // span is omitted rather than recorded inverted — the omit-if-absent
        // log key already expresses "no span", and the refusal's own detail
        // carries the numbers.
        for (at, count) in [(i64::MAX, 5), (1, i64::MIN), (-1, i64::MIN)] {
            assert_eq!(
                dimension_range_label(&StructureVerb::InsertRows {
                    sheet: "Q2".to_string(),
                    at,
                    count,
                }),
                None,
                "--at {at} --count {count} must not produce a span"
            );
        }
    }

    // ── refusals that must precede the gate and the network ────────────

    #[tokio::test]
    async fn non_spreadsheet_is_refused_before_any_gate_or_sheets_call() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", "application/pdf", &["parent-1"])
            .mount(&server)
            .await;
        // No mock for parent-1 (the gate never runs) and none for any Sheets
        // endpoint, even though the rule below would otherwise permit this.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedNotASpreadsheet { .. }
        ));
        let text = describe(&outcome);
        assert!(text.contains("is not a Google Sheet"), "{text}");
        assert!(text.contains("drive sheets rename-sheet"), "{text}");
    }

    #[tokio::test]
    async fn shortcut_is_refused_with_its_own_message() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file(
            "sheet-1",
            "application/vnd.google-apps.shortcut",
            &["parent-1"],
        )
        .mount(&server)
        .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::RefusedShortcut));
        let text = describe(&outcome);
        assert!(text.contains("is a shortcut"), "{text}");
    }

    #[tokio::test]
    async fn a_sheet_with_no_visible_parents_is_refused_distinctly_from_blocked() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &[])
            .mount(&server)
            .await;
        let outcome = structure(&drive, &sheets, &opts(rename(), false), &[]).await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedNoVisibleParents
        ));
        let text = describe(&outcome);
        assert!(text.contains("no parent folder visible"), "{text}");
        // Names the operation the operator would have to grant, so the
        // message is actionable rather than merely accurate.
        assert!(text.contains("sheets-structure"), "{text}");
    }

    /// The same message for a delete verb must name `sheets-delete`, not
    /// `sheets-structure` — suggesting the wrong operation here would send an
    /// operator to grant a capability that does not cover what they asked
    /// for.
    #[tokio::test]
    async fn a_delete_verbs_no_visible_parents_message_names_sheets_delete() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &[])
            .mount(&server)
            .await;
        let outcome = structure(&drive, &sheets, &opts(delete_sheet(), false), &[]).await;
        let text = describe(&outcome);
        assert!(text.contains("sheets-delete"), "{text}");
        assert!(!text.contains("sheets-structure"), "{text}");
    }

    // ── the gate ───────────────────────────────────────────────────────

    #[tokio::test]
    async fn denied_target_makes_zero_sheets_calls() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // Deliberately no `spreadsheets.get` mock and no `batchUpdate` mock:
        // a blocked attempt must not reach the Sheets API at all, which is
        // what keeps a refusal exactly as auditable as a success.
        let outcome = structure(&drive, &sheets, &opts(rename(), false), &[]).await;
        assert!(matches!(
            outcome.result,
            StructureResult::Blocked { decided_by: None }
        ));
        let text = describe(&outcome);
        assert!(text.contains("default policy"), "{text}");
    }

    #[tokio::test]
    async fn a_blocked_delete_names_destructive_edits_and_sheets_delete() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let outcome = structure(&drive, &sheets, &opts(delete_sheet(), false), &[]).await;
        assert!(matches!(
            outcome.result,
            StructureResult::Blocked { decided_by: None }
        ));
        let text = describe(&outcome);
        assert!(text.contains("destructive edits"), "{text}");
        assert!(text.contains("default policy"), "{text}");
        assert!(text.contains("sheets-delete"), "{text}");
        assert!(!text.contains("structural edits"), "{text}");
    }

    #[tokio::test]
    async fn a_sheets_write_rule_alone_does_not_permit_a_structural_edit() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // The non-widening property, observed end to end rather than only in
        // the gate's unit tests: a folder granted cell writes must not gain
        // the power to restructure the workbook.
        let rules = [FolderPermissionRule {
            folder_id: Some("parent-1".to_string()),
            file_id: None,
            recursive: true,
            allow: std::iter::once(DriveOperation::SheetsWrite).collect(),
            deny: HashSet::default(),
            require_lease: true,
        }];
        let outcome = structure(&drive, &sheets, &opts(rename(), false), &rules).await;
        assert!(matches!(outcome.result, StructureResult::Blocked { .. }));
    }

    /// The property ADR-0077 exists to protect: a folder granted
    /// `sheets-structure` before deletion existed must not silently gain the
    /// power to destroy data now that it does.
    #[tokio::test]
    async fn a_sheets_structure_rule_alone_does_not_permit_deletion() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let rules = [allow_rule("parent-1")]; // grants SheetsStructure only
        for verb in [delete_sheet(), delete_rows(), delete_range()] {
            let outcome = structure(&drive, &sheets, &opts(verb, false), &rules).await;
            assert!(matches!(outcome.result, StructureResult::Blocked { .. }));
        }
    }

    /// The converse: `sheets-delete` must not grant the additive verbs
    /// either — the two operations are siblings, not a hierarchy.
    #[tokio::test]
    async fn a_sheets_delete_rule_alone_does_not_permit_a_structural_edit() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let rules = [delete_allow_rule("parent-1")];
        let outcome = structure(&drive, &sheets, &opts(rename(), false), &rules).await;
        assert!(matches!(outcome.result, StructureResult::Blocked { .. }));
    }

    #[tokio::test]
    async fn an_explicit_deny_is_reported_with_the_deciding_rule() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        let rules = [FolderPermissionRule {
            folder_id: Some("parent-1".to_string()),
            file_id: None,
            recursive: true,
            allow: HashSet::default(),
            deny: std::iter::once(DriveOperation::SheetsStructure).collect(),
            require_lease: true,
        }];
        let outcome = structure(&drive, &sheets, &opts(rename(), false), &rules).await;
        let StructureResult::Blocked { decided_by } = &outcome.result else {
            panic!("expected Blocked, got {:?}", outcome.result);
        };
        let rule = decided_by.as_ref().expect("an explicit rule decided this");
        assert_eq!(rule.kind_label(), "folder");
        assert_eq!(rule.id(), "parent-1");
        assert_eq!(rule.depth_suffix(), " (depth 0)");
    }

    #[tokio::test]
    async fn ancestor_chain_fetch_failure_produces_failed_not_allow() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/parent-1"))
            .respond_with(wiremock::ResponseTemplate::new(500))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Failed { .. }));
    }

    // ── --dry-run ──────────────────────────────────────────────────────

    /// A dry run must never issue `batchUpdate`.
    ///
    /// It *does* issue one `spreadsheets.get` — deliberately, and unlike
    /// `sheets write`'s dry run, which touches Sheets not at all. Describing
    /// a structural effect honestly needs the sheet's real dimensions, and a
    /// read is not a mutation. The absent `batchUpdate` mock is what proves
    /// the distinction: wiremock fails an unmatched request.
    #[tokio::test]
    async fn dry_run_reads_the_workbook_but_never_calls_batch_update() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().expect(1).mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(insert_rows(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::WouldChange { .. }
        ));
    }

    #[tokio::test]
    async fn dry_run_names_the_resulting_dimensions_and_the_shift() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(insert_rows(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        // The answer to "what does --dry-run show when the effect isn't a
        // range": the real before/after, plus the shift a range can't express.
        assert!(
            text.contains("Would insert 3 row(s) before row 5"),
            "{text}"
        );
        assert!(text.contains("500 rows -> 503"), "{text}");
        assert!(text.contains("shift down"), "{text}");
        assert!(text.contains("sheetId 118293"), "{text}");
    }

    /// A destructive dry run must never issue `batchUpdate` either, and stays
    /// structural-only (ADR-0077): no `values.get`, no cell content, just the
    /// same single `spreadsheets.get` an additive dry run already issues.
    #[tokio::test]
    async fn dry_run_never_calls_batch_update_for_a_delete_verb() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        for verb in [delete_sheet(), delete_rows(), delete_range()] {
            let outcome = structure(
                &drive,
                &sheets,
                &opts(verb, true),
                &[delete_allow_rule("parent-1")],
            )
            .await;
            assert!(matches!(
                outcome.result,
                StructureResult::WouldChange { .. }
            ));
        }
    }

    #[tokio::test]
    async fn dry_run_names_the_deleted_dimensions_and_the_shift_plus_the_caveat() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_rows(), true),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("Would delete 3 row(s) 5-7"), "{text}");
        assert!(text.contains("500 rows -> 497"), "{text}");
        assert!(text.contains("shift up"), "{text}");
        assert!(
            text.contains("formulas elsewhere in the workbook"),
            "{text}"
        );
    }

    #[tokio::test]
    async fn dry_run_names_the_deleted_sheet_and_the_caveat() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_sheet(), true),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("Would delete sheet 'Q2'"), "{text}");
        assert!(text.contains("2 sheet(s) -> 1"), "{text}");
        assert!(
            text.contains("formulas elsewhere in the workbook"),
            "{text}"
        );
    }

    #[tokio::test]
    async fn dry_run_names_the_deleted_range_and_the_shift() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_range(), true),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(
            text.contains("Would delete rows 2-4, columns 2-3"),
            "{text}"
        );
        assert!(text.contains("shifting remaining cells up"), "{text}");
    }

    #[tokio::test]
    async fn dry_run_surfaces_the_same_blocked_reasoning_as_a_real_denied_run() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // The gate precedes the dry-run early return, so a preview of a
        // denied edit reports the denial rather than a rosy preview.
        let dry = structure(&drive, &sheets, &opts(rename(), true), &[]).await;
        let wet = structure(&drive, &sheets, &opts(rename(), false), &[]).await;
        assert_eq!(dry.result, wet.result);
        assert!(matches!(dry.result, StructureResult::Blocked { .. }));
    }

    // ── resolving the target sheet ─────────────────────────────────────

    #[tokio::test]
    async fn a_missing_sheet_is_refused_and_lists_what_does_exist() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::RenameSheet {
            sheet: "Nope".to_string(),
            new_title: "Q3".to_string(),
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedSheetNotFound { .. }
        ));
        let text = describe(&outcome);
        assert!(text.contains("no sheet titled 'Nope'"), "{text}");
        assert!(text.contains("'Q1'"), "{text}");
        assert!(text.contains("'Q2'"), "{text}");
    }

    /// A duplicate title is caught before `batchUpdate` rather than left to
    /// the server, so a dry run cannot promise a change the real run fails.
    #[tokio::test]
    async fn add_sheet_refuses_a_title_the_workbook_already_uses() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::AddSheet {
            title: "Q1".to_string(),
            index: None,
            rows: None,
            columns: None,
        };
        // No batchUpdate mock: the refusal must short-circuit the mutation.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedSheetExists { .. }
        ));
        assert!(describe(&outcome).contains("already has a sheet titled 'Q1'"));
    }

    /// The rename analogue of the `add-sheet` test above: renaming to a
    /// title a *different* sheet already has must be caught before
    /// `batchUpdate`, not left to a dry run that then can't be trusted.
    #[tokio::test]
    async fn rename_sheet_refuses_a_title_another_sheet_already_uses() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::RenameSheet {
            sheet: "Q2".to_string(),
            new_title: "Q1".to_string(),
        };
        // No batchUpdate mock: the refusal must short-circuit the mutation,
        // and the same must hold for a --dry-run preview of it.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedSheetExists { .. }
        ));
        assert!(describe(&outcome).contains("already has a sheet titled 'Q1'"));

        let dry = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert_eq!(dry.result, outcome.result);
    }

    /// Renaming a sheet to the title it already has names itself, not a
    /// different sheet, so it must not be refused as a duplicate.
    #[tokio::test]
    async fn rename_sheet_to_its_own_current_title_is_not_a_duplicate() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let verb = StructureVerb::RenameSheet {
            sheet: "Q2".to_string(),
            new_title: "Q2".to_string(),
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));
    }

    // ── argument validation ──────────────────────────────────────────────

    #[tokio::test]
    async fn insert_rows_refuses_a_count_below_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::InsertRows {
            sheet: "Q2".to_string(),
            at: 5,
            count: 0,
        };
        // No batchUpdate mock: the refusal must short-circuit the mutation.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("--count"), "{detail}");
        assert!(describe(&outcome).starts_with("Refused: --count"));
    }

    #[tokio::test]
    async fn insert_columns_refuses_an_at_below_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::InsertColumns {
            sheet: "Q2".to_string(),
            at: 0,
            count: 1,
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("--at"), "{detail}");
    }

    /// `Q2` has 500 rows (from `mount_workbook`); `--at 502` names a
    /// position that does not exist and is not immediately after one that
    /// does, so it must be refused rather than sent to `batchUpdate` or
    /// promised by a `--dry-run`.
    #[tokio::test]
    async fn insert_rows_refuses_an_at_past_the_sheets_end() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::InsertRows {
            sheet: "Q2".to_string(),
            at: 502,
            count: 1,
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("500 row(s)"), "{detail}");
        assert!(detail.contains("501"), "{detail}");

        let dry = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert_eq!(dry.result, outcome.result);
    }

    #[test]
    fn an_at_and_count_that_would_overflow_the_index_space_are_refused() {
        let sheet = SheetSnapshot {
            sheet_id: Some(1),
            title: "Q2".to_string(),
            row_count: Some(500),
            column_count: Some(26),
            ..Default::default()
        };
        // Both halves of `at - 1 + count`, since either can be the one that
        // overflows: a huge `--at` (refused for being past the end too, but
        // only *after* this check) and a huge `--count` at a legal `--at`
        // (which nothing else bounds — see the comment on the guard).
        for (at, count) in [(i64::MAX, 5), (500, i64::MAX)] {
            let Err(StructureResult::RefusedInvalidRange { detail }) =
                validate_insert_bounds(Dimension::Rows, at, count, Some(&sheet))
            else {
                panic!("expected RefusedInvalidRange for --at {at} --count {count}");
            };
            assert!(detail.contains("overflows the row index space"), "{detail}");
        }
    }

    #[tokio::test]
    async fn a_refused_out_of_range_insert_still_records_without_panicking() {
        // The regression that matters for `dimension_range_label`: this runs
        // with `dry_run: false`, so `record_attempt` builds a log record from
        // the very arguments `validate_insert_bounds` just rejected. Computing
        // the span with plain arithmetic panics here rather than in the
        // mutation it refused to make.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::InsertRows {
                    sheet: "Q2".to_string(),
                    at: i64::MAX,
                    count: 5,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::RefusedInvalidRange { .. }),
            "{:?}",
            outcome.result
        );
    }

    /// `--at` equal to `row_count + 1` is a legal append (insert after the
    /// last row), the one boundary value the check above must not reject —
    /// and the dry-run message must not print an inverted "existing rows
    /// 501-500 shift down".
    #[tokio::test]
    async fn insert_rows_allows_at_equal_to_row_count_plus_one_as_an_append() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::InsertRows {
            sheet: "Q2".to_string(),
            at: 501,
            count: 2,
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::WouldChange { .. }
        ));
        let text = describe(&outcome);
        assert!(text.contains("500 rows -> 502"), "{text}");
        assert!(text.contains("appended at the end"), "{text}");
        assert!(!text.contains("501-500"), "{text}");
    }

    #[tokio::test]
    async fn add_sheet_refuses_non_positive_rows_and_columns() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::AddSheet {
            title: "Q3".to_string(),
            index: None,
            rows: Some(0),
            columns: None,
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("--rows"), "{detail}");
    }

    /// `mount_workbook` has 2 sheets, so 0/1/2 are the only valid indices
    /// (2 means "append", the same as omitting `--index`).
    #[tokio::test]
    async fn add_sheet_refuses_an_out_of_range_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::AddSheet {
            title: "Q3".to_string(),
            index: Some(3),
            rows: None,
            columns: None,
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("--index"), "{detail}");
    }

    #[tokio::test]
    async fn add_sheet_allows_an_index_equal_to_the_sheet_count() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = StructureVerb::AddSheet {
            title: "Q3".to_string(),
            index: Some(2),
            rows: None,
            columns: None,
        };
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::WouldChange { .. }
        ));
    }

    // ── the mutation ───────────────────────────────────────────────────

    #[tokio::test]
    async fn rename_sends_a_title_masked_update_for_the_resolved_sheet_id() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        // Resolved by title to the numeric id the API addresses.
        assert_eq!(update["properties"]["sheetId"], 118_293);
        assert_eq!(update["properties"]["title"], "Q3");
        // The mask names exactly the one field we set; a wider mask would
        // blank every property it named but we left unpopulated.
        assert_eq!(update["fields"], "title");
        assert_eq!(body["requests"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn insert_rows_sends_a_zero_based_half_open_range() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(insert_rows(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let insert = &body["requests"][0]["insertDimension"];
        assert_eq!(insert["range"]["dimension"], "ROWS");
        assert_eq!(insert["range"]["sheetId"], 118_293);
        // `--at 5 --count 3` on the wire, 1-based inclusive to 0-based
        // half-open.
        assert_eq!(insert["range"]["startIndex"], 4);
        assert_eq!(insert["range"]["endIndex"], 7);
        assert_eq!(insert["inheritFromBefore"], false);
    }

    #[tokio::test]
    async fn delete_sheet_sends_the_resolved_sheet_id() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_sheet(), false),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));
        assert!(describe(&outcome).contains("Deleted sheet 'Q2'"));
        // `seed_lease` records a bytes backup, so the message names its
        // path; the Drive-copy and no-lease wordings have their own tests
        // in the lease section below.
        assert!(describe(&outcome).contains("backed the file up when it was acquired"));
        assert!(describe(&outcome).contains("/tmp/test-backup"));
        assert!(describe(&outcome).contains("Google Drive's own version history"));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        assert_eq!(body["requests"][0]["deleteSheet"]["sheetId"], 118_293);
        assert_eq!(body["requests"].as_array().unwrap().len(), 1);
    }

    #[tokio::test]
    async fn delete_rows_sends_a_zero_based_half_open_range() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_rows(), false),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let delete = &body["requests"][0]["deleteDimension"];
        assert_eq!(delete["range"]["dimension"], "ROWS");
        assert_eq!(delete["range"]["sheetId"], 118_293);
        // `--at 5 --count 3` on the wire, 1-based inclusive to 0-based
        // half-open — same conversion as insert, same site.
        assert_eq!(delete["range"]["startIndex"], 4);
        assert_eq!(delete["range"]["endIndex"], 7);
    }

    #[tokio::test]
    async fn delete_columns_sends_a_zero_based_half_open_range() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_columns(), false),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));
        assert!(describe(&outcome).contains("Deleted 2 column(s) 3-4"));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let delete = &body["requests"][0]["deleteDimension"];
        assert_eq!(delete["range"]["dimension"], "COLUMNS");
        assert_eq!(delete["range"]["sheetId"], 118_293);
        // `--at 3 --count 2` on the wire, 1-based inclusive to 0-based
        // half-open.
        assert_eq!(delete["range"]["startIndex"], 2);
        assert_eq!(delete["range"]["endIndex"], 4);
    }

    #[tokio::test]
    async fn insert_range_sends_a_zero_based_half_open_grid_range() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(insert_range(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));
        assert!(describe(&outcome).contains("shifting existing cells down"));
        assert!(describe(&outcome).contains("may have been dropped by Sheets"));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        assert_eq!(
            body["requests"][0]["insertRange"],
            serde_json::json!({
                "range": {
                    "sheetId": 118_293,
                    "startRowIndex": 1,
                    "endRowIndex": 4,
                    "startColumnIndex": 1,
                    "endColumnIndex": 3,
                },
                "shiftDimension": "ROWS",
            })
        );
    }

    #[tokio::test]
    async fn insert_range_with_columns_shift_sends_the_column_direction() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(insert_range_columns_shift(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));
        assert!(describe(&outcome).contains("shifting existing cells right"));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        assert_eq!(
            body["requests"][0]["insertRange"]["shiftDimension"],
            "COLUMNS"
        );
    }

    #[tokio::test]
    async fn insert_range_dry_run_at_the_grid_edge_warns_without_mutating() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::InsertRange {
                    sheet: "Q2".to_string(),
                    start_row: 500,
                    end_row: 500,
                    start_column: 10,
                    end_column: 10,
                    shift: ShiftDimension::Columns,
                },
                true,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::WouldChange { .. }
        ));
        let text = describe(&outcome);
        assert!(text.contains("shifting existing cells right"), "{text}");
        assert!(text.contains("may be dropped by Sheets"), "{text}");
        assert!(server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .all(|request| !request.url.path().ends_with(":batchUpdate")));
    }

    #[tokio::test]
    async fn insert_range_dry_run_with_rows_shift_warns_without_mutating() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::InsertRange {
                    sheet: "Q2".to_string(),
                    start_row: 500,
                    end_row: 500,
                    start_column: 10,
                    end_column: 10,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::WouldChange { .. }
        ));
        let text = describe(&outcome);
        assert!(text.contains("shifting existing cells down"), "{text}");
        assert!(text.contains("may be dropped by Sheets"), "{text}");
        assert!(server
            .received_requests()
            .await
            .unwrap()
            .iter()
            .all(|request| !request.url.path().ends_with(":batchUpdate")));
    }

    #[tokio::test]
    async fn delete_range_sends_a_zero_based_half_open_grid_range() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_range(), false),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let delete = &body["requests"][0]["deleteRange"];
        assert_eq!(delete["range"]["sheetId"], 118_293);
        // `--start-row 2 --end-row 4 --start-column 2 --end-column 3` on the
        // wire, 1-based inclusive to 0-based half-open.
        assert_eq!(delete["range"]["startRowIndex"], 1);
        assert_eq!(delete["range"]["endRowIndex"], 4);
        assert_eq!(delete["range"]["startColumnIndex"], 1);
        assert_eq!(delete["range"]["endColumnIndex"], 3);
        assert_eq!(delete["shiftDimension"], "ROWS");
    }

    #[tokio::test]
    async fn delete_range_with_columns_shift_sends_the_column_direction() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(delete_range_columns_shift(), false),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));
        assert!(describe(&outcome).contains("shifted remaining cells left"));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        assert_eq!(
            body["requests"][0]["deleteRange"]["shiftDimension"],
            "COLUMNS"
        );
    }

    #[tokio::test]
    async fn delete_dimension_past_the_end_of_the_sheet_is_refused() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // Q2 has 500 rows; deleting 5 rows starting at 499 reaches row 503.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRows {
                    sheet: "Q2".to_string(),
                    at: 499,
                    count: 5,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedInvalidRange { .. }
        ));
    }

    #[tokio::test]
    async fn delete_range_with_end_before_start_is_refused() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRange {
                    sheet: "Q2".to_string(),
                    start_row: 5,
                    end_row: 2,
                    start_column: 1,
                    end_column: 2,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedInvalidRange { .. }
        ));
    }

    #[tokio::test]
    async fn delete_dimension_refuses_a_non_positive_count() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRows {
                    sheet: "Q2".to_string(),
                    at: 1,
                    count: 0,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("--count must be at least 1"), "{detail}");
    }

    #[tokio::test]
    async fn delete_dimension_refuses_an_at_below_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteColumns {
                    sheet: "Q2".to_string(),
                    at: 0,
                    count: 1,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("--at must be at least 1"), "{detail}");
    }

    #[tokio::test]
    async fn delete_dimension_refuses_an_at_and_count_that_overflow_the_index_space() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRows {
                    sheet: "Q2".to_string(),
                    at: i64::MAX,
                    count: 2,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("overflows the row index space"), "{detail}");
    }

    #[tokio::test]
    async fn delete_range_refuses_a_start_row_below_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRange {
                    sheet: "Q2".to_string(),
                    start_row: 0,
                    end_row: 2,
                    start_column: 1,
                    end_column: 2,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--start-row must be at least 1"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn delete_range_refuses_a_start_column_below_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRange {
                    sheet: "Q2".to_string(),
                    start_row: 1,
                    end_row: 2,
                    start_column: 0,
                    end_column: 2,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--start-column must be at least 1"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn delete_range_refuses_an_end_column_before_start_column() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // Rows are well-ordered on their own; only the columns are inverted,
        // so this is refused for a different reason than
        // `delete_range_with_end_before_start_is_refused`.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRange {
                    sheet: "Q2".to_string(),
                    start_row: 1,
                    end_row: 2,
                    start_column: 5,
                    end_column: 2,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--end-column (2) must be at or after --start-column (5)"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn delete_range_refuses_an_end_row_past_the_end_of_the_sheet() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // Q2 has 500 rows.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRange {
                    sheet: "Q2".to_string(),
                    start_row: 1,
                    end_row: 501,
                    start_column: 1,
                    end_column: 2,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--end-row 501 is past the end of the sheet"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn delete_range_refuses_an_end_column_past_the_end_of_the_sheet() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // Q2 has 10 columns.
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DeleteRange {
                    sheet: "Q2".to_string(),
                    start_row: 1,
                    end_row: 2,
                    start_column: 1,
                    end_column: 11,
                    shift: ShiftDimension::Rows,
                },
                true,
            ),
            &[delete_allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--end-column 11 is past the end of the sheet"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn add_sheet_reports_the_server_assigned_sheet_id() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({
            "spreadsheetId": "sheet-1",
            "replies": [{"addSheet": {"properties": {"sheetId": 999, "title": "Q3"}}}],
        }))
        .mount(&server)
        .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(add_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        // The one fact the reply carries that the request did not know.
        assert!(matches!(
            outcome.result,
            StructureResult::Changed {
                sheet_id: Some(999),
                ..
            }
        ));
        assert!(describe(&outcome).contains("sheetId 999"));
    }

    #[tokio::test]
    async fn add_sheet_omits_grid_properties_when_no_size_was_asked_for() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let _ = structure(
            &drive,
            &sheets,
            &opts(add_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let props = &body["requests"][0]["addSheet"]["properties"];
        // Omitted, not zeroed: Sheets' own default (1000 x 26) should apply
        // rather than a size we invented.
        assert!(props.get("gridProperties").is_none(), "{props}");
        assert!(props.get("index").is_none(), "{props}");
        assert_eq!(props["title"], "Q3");
    }

    #[tokio::test]
    async fn a_batch_update_failure_is_reported_as_failed_not_changed() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
                    "error": {
                        "code": 403,
                        "message": "The caller does not have permission",
                        "status": "PERMISSION_DENIED",
                    }
                })),
            )
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::Failed { detail } = &outcome.result else {
            panic!("expected Failed, got {:?}", outcome.result);
        };
        // The `google.rpc` envelope has no `errors[]`, so the scope hint has
        // to match on `status` — ADR-0073 §2.
        assert!(detail.contains("drive auth login"), "{detail}");
    }

    // ── duplicate-sheet / reorder-sheet / hide-show-sheet (issue #1643) ─

    #[tokio::test]
    async fn duplicate_sheet_apply_sends_source_title_and_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(duplicate_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let dup = &body["requests"][0]["duplicateSheet"];
        assert_eq!(dup["sourceSheetId"], 118_293);
        assert_eq!(dup["insertSheetIndex"], 1);
        assert_eq!(dup["newSheetName"], "Q2 Copy");
    }

    #[tokio::test]
    async fn duplicate_sheet_apply_with_default_title_and_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(duplicate_sheet_default(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let dup = &body["requests"][0]["duplicateSheet"];
        assert!(dup.get("insertSheetIndex").is_none());
        assert!(dup.get("newSheetName").is_none());
    }

    #[tokio::test]
    async fn duplicate_sheet_dry_run_names_title_and_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(duplicate_sheet(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("Would duplicate sheet 'Q2'"), "{text}");
        assert!(text.contains("as 'Q2 Copy'"), "{text}");
        assert!(text.contains("at index 1"), "{text}");
        let requests = server.received_requests().await.unwrap();
        assert!(!requests
            .iter()
            .any(|r| r.url.path().ends_with(":batchUpdate")));
    }

    #[tokio::test]
    async fn duplicate_sheet_dry_run_uses_defaults_when_omitted() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(duplicate_sheet_default(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(
            text.contains("as a copy Sheets names automatically"),
            "{text}"
        );
        assert!(text.contains("at the front"), "{text}");
    }

    #[tokio::test]
    async fn duplicate_sheet_refuses_a_missing_source_sheet() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DuplicateSheet {
                    sheet: "Nope".to_string(),
                    title: None,
                    index: None,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedSheetNotFound { .. }
        ));
    }

    #[tokio::test]
    async fn duplicate_sheet_refuses_a_colliding_new_title() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DuplicateSheet {
                    sheet: "Q2".to_string(),
                    title: Some("Q1".to_string()),
                    index: None,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedSheetExists { ref title } if title == "Q1"
        ));
    }

    #[tokio::test]
    async fn duplicate_sheet_refuses_an_out_of_range_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::DuplicateSheet {
                    sheet: "Q2".to_string(),
                    title: None,
                    index: Some(99),
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--index must be between 0 and 2"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn reorder_sheet_apply_sends_index_masked_update() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(reorder_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        assert_eq!(update["properties"]["sheetId"], 118_293);
        assert_eq!(update["properties"]["index"], 0);
        assert_eq!(update["fields"], "index");
    }

    #[tokio::test]
    async fn reorder_sheet_dry_run_names_the_target_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(reorder_sheet(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("Would move sheet 'Q2'"), "{text}");
        assert!(text.contains("to index 0"), "{text}");
    }

    #[tokio::test]
    async fn reorder_sheet_refuses_an_out_of_range_index() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::ReorderSheet {
                    sheet: "Q2".to_string(),
                    index: 5,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("--index must be between 0 and 1"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn hide_sheet_apply_sends_hidden_true() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(hide_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        assert_eq!(update["properties"]["sheetId"], 118_293);
        assert_eq!(update["properties"]["hidden"], true);
        assert_eq!(update["fields"], "hidden");
    }

    #[tokio::test]
    async fn show_sheet_apply_sends_hidden_false() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook_with_q2(hidden_q2()).mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(show_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        assert_eq!(update["properties"]["hidden"], false);
    }

    #[tokio::test]
    async fn hide_sheet_dry_run_names_the_hide() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(hide_sheet(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("Would hide sheet 'Q2'"), "{text}");
    }

    #[tokio::test]
    async fn show_sheet_dry_run_names_the_show() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook_with_q2(hidden_q2()).mount(&server).await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(show_sheet(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("Would show sheet 'Q2'"), "{text}");
    }

    /// Hiding a hidden sheet or showing a visible one sends nothing and
    /// says so, in a dry run exactly as in a real run, rather than
    /// reporting a change that did not happen.
    #[tokio::test]
    async fn a_visibility_no_op_is_unchanged_in_dry_run_and_real_run() {
        for (verb, q2, state) in [
            (hide_sheet(), hidden_q2(), "hidden"),
            (show_sheet(), default_q2(), "shown"),
        ] {
            for dry_run in [true, false] {
                let server = wiremock::MockServer::start().await;
                let (drive, sheets) = clients(&server).await;
                mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
                    .mount(&server)
                    .await;
                mount_folder("parent-1").mount(&server).await;
                mount_workbook_with_q2(q2.clone()).mount(&server).await;
                let outcome = structure(
                    &drive,
                    &sheets,
                    &opts(verb.clone(), dry_run),
                    &[allow_rule("parent-1")],
                )
                .await;
                assert_eq!(
                    outcome.result,
                    StructureResult::Unchanged {
                        detail: format!("sheet 'Q2' is already {state}")
                    },
                    "dry_run={dry_run}"
                );
                let text = describe(&outcome);
                assert!(
                    text.starts_with(&format!("Unchanged: sheet 'Q2' is already {state} in ")),
                    "{text}"
                );
                let requests = server.received_requests().await.unwrap();
                assert!(
                    !requests
                        .iter()
                        .any(|r| r.url.path().ends_with(":batchUpdate")),
                    "a no-op must not call batchUpdate"
                );
            }
        }
    }

    #[tokio::test]
    async fn hide_sheet_refuses_leaving_no_visible_sheets() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "spreadsheetId": "sheet-1",
                    "properties": {"title": "Budget"},
                    "sheets": [
                        {"properties": {"sheetId": 0, "title": "Q1", "index": 0, "hidden": true}},
                        {"properties": {"sheetId": 118_293, "title": "Q2", "index": 1}},
                    ],
                })),
            )
            .mount(&server)
            .await;
        let outcome = structure(
            &drive,
            &sheets,
            &opts(hide_sheet(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(
            detail.contains("would leave the workbook with no visible sheets"),
            "{detail}"
        );
    }

    // ── update-sheet-properties (issue #1835) ───────────────────────────

    fn update_sheet_properties(
        freeze_rows: Option<i64>,
        freeze_columns: Option<i64>,
        tab_color: Option<&str>,
        clear_tab_color: bool,
        right_to_left: Option<bool>,
        hide_gridlines: Option<bool>,
    ) -> StructureVerb {
        StructureVerb::UpdateSheetProperties {
            sheet: "Q2".to_string(),
            freeze_rows,
            freeze_columns,
            tab_color: tab_color.map(ToString::to_string),
            clear_tab_color,
            right_to_left,
            hide_gridlines,
        }
    }

    /// A `spreadsheets.get` reply like [`mount_workbook`], but `Q2` reports
    /// `frozenRowCount: 1` — the fixture
    /// [`update_sheet_properties_dry_run_reports_before_and_after`] needs to
    /// exercise the before->after line.
    fn mount_workbook_with_frozen_rows(
        sheet_id: i64,
        row_count: i64,
        frozen_row_count: i64,
    ) -> wiremock::Mock {
        mount_workbook_with_q2(serde_json::json!({
        "properties": {
            "sheetId": sheet_id, "title": "Q2", "index": 1,
            "gridProperties": {
                "rowCount": row_count, "columnCount": 10,
                "frozenRowCount": frozen_row_count,
            }}}))
    }

    /// A `spreadsheets.get` reply like [`mount_workbook`], but `Q2` already
    /// carries the three view properties whose "before" value is read off
    /// the snapshot rather than off `gridProperties.rowCount` —
    /// `frozenColumnCount`, `rightToLeft` and `hideGridlines`. Without a
    /// fixture that reports them, every fragment
    /// [`update_sheet_properties_fragments`] builds for them falls to the
    /// `before: None` shape, so the `"<label> <before> -> <after>"` half of
    /// the description would never be exercised for anything but frozen
    /// rows (issue #1835).
    fn mount_workbook_with_view_state() -> wiremock::Mock {
        mount_workbook_with_q2(serde_json::json!({
        "properties": {
            "sheetId": 118_293, "title": "Q2", "index": 1,
            "rightToLeft": true,
            "gridProperties": {
                "rowCount": 500, "columnCount": 10,
                "frozenColumnCount": 2,
                "hideGridlines": true,
            }}}))
    }

    #[tokio::test]
    async fn update_sheet_properties_apply_sends_only_the_set_fields_in_the_mask() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let verb = update_sheet_properties(Some(2), None, Some("#FF8800"), false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        assert_eq!(
            update["fields"],
            "gridProperties.frozenRowCount,tabColorStyle"
        );
        assert_eq!(update["properties"]["sheetId"], 118_293);
        assert_eq!(update["properties"]["gridProperties"]["frozenRowCount"], 2);
        let rgb = &update["properties"]["tabColorStyle"]["rgbColor"];
        assert!((rgb["red"].as_f64().unwrap() - 1.0).abs() < 1e-6, "{rgb}");
        assert!(
            (rgb["green"].as_f64().unwrap() - (136.0 / 255.0)).abs() < 1e-6,
            "{rgb}"
        );
        assert!((rgb["blue"].as_f64().unwrap() - 0.0).abs() < 1e-6, "{rgb}");
        assert!(
            update["properties"]["gridProperties"]
                .get("frozenColumnCount")
                .is_none(),
            "{update}"
        );
        assert!(
            update["properties"].get("rightToLeft").is_none(),
            "{update}"
        );
        assert!(update["properties"].get("hidden").is_none(), "{update}");
        assert!(update["properties"].get("title").is_none(), "{update}");
        assert!(update["properties"].get("index").is_none(), "{update}");
    }

    #[tokio::test]
    async fn update_sheet_properties_apply_clear_tab_color_names_tab_color_style_with_no_value() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let verb = update_sheet_properties(None, None, None, true, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        assert_eq!(update["fields"], "tabColorStyle");
        assert!(
            update["properties"].get("tabColorStyle").is_none(),
            "{update}"
        );
    }

    #[tokio::test]
    async fn update_sheet_properties_dry_run_reports_before_and_after() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook_with_frozen_rows(118_293, 500, 1)
            .mount(&server)
            .await;
        let verb = update_sheet_properties(Some(3), None, None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.contains("frozen rows 1 -> 3"), "{text}");
    }

    #[tokio::test]
    async fn update_sheet_properties_apply_sends_every_property_and_reports_each_one() {
        // The companion of
        // `update_sheet_properties_apply_sends_only_the_set_fields_in_the_mask`,
        // which sets two properties: this one sets all five, so every
        // `fields` entry and every description fragment is exercised, and
        // the mask's order is pinned against the order `build_request`
        // pushes them in. `mount_workbook`'s Q2 reports none of the three
        // optional view properties, so this is also the run where each
        // fragment takes its `before: None` shape ("<label> -> <after>").
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        // A bare hex, so the reported text also pins that the display
        // normalization supplies the '#' the user didn't type.
        let verb = update_sheet_properties(
            Some(2),
            Some(3),
            Some("0000FF"),
            false,
            Some(true),
            Some(true),
        );
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );

        let requests = server.received_requests().await.unwrap();
        let body: serde_json::Value = requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request");
        let update = &body["requests"][0]["updateSheetProperties"];
        assert_eq!(
            update["fields"],
            "gridProperties.frozenRowCount,gridProperties.frozenColumnCount,\
             gridProperties.hideGridlines,tabColorStyle,rightToLeft"
        );
        let grid = &update["properties"]["gridProperties"];
        assert_eq!(grid["frozenRowCount"], 2);
        assert_eq!(grid["frozenColumnCount"], 3);
        assert_eq!(grid["hideGridlines"], true);
        assert_eq!(update["properties"]["rightToLeft"], true);

        let text = describe(&outcome);
        assert!(text.starts_with("Updated sheet 'Q2'"), "{text}");
        for fragment in [
            "frozen rows -> 2",
            "frozen columns -> 3",
            "tab color -> #0000FF",
            "right-to-left -> true",
            "gridlines -> hidden",
        ] {
            assert!(text.contains(fragment), "{fragment} missing from {text}");
        }
    }

    #[tokio::test]
    async fn update_sheet_properties_dry_run_reports_clears_and_the_values_being_replaced() {
        // The other half of
        // `update_sheet_properties_apply_sends_every_property_and_reports_each_one`:
        // the sheet already carries `frozenColumnCount`/`rightToLeft`/
        // `hideGridlines`, so each fragment takes its
        // "<label> <before> -> <after>" shape, gridlines read as
        // hidden/shown rather than as booleans, and `--clear-tab-color`
        // states the clear instead of a target color. Frozen rows are left
        // unset, which is the only run where that property contributes no
        // fragment at all.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook_with_view_state().mount(&server).await;
        let verb = update_sheet_properties(None, Some(4), None, true, Some(false), Some(false));
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let text = describe(&outcome);
        assert!(text.starts_with("Would update sheet 'Q2'"), "{text}");
        assert!(!text.contains("frozen rows"), "{text}");
        for fragment in [
            "frozen columns 2 -> 4",
            "tab color cleared",
            "right-to-left true -> false",
            "gridlines hidden -> shown",
        ] {
            assert!(text.contains(fragment), "{fragment} missing from {text}");
        }
    }

    #[test]
    fn fields_changed_label_names_exactly_the_properties_the_verb_set() {
        // `record_attempt` logs what the verb *asked* to change, so this is
        // what lands in the request log's `fields_changed` context key for
        // an `update-sheet-properties` attempt — including a refused one.
        let every = update_sheet_properties(
            Some(2),
            Some(3),
            Some("#FF8800"),
            false,
            Some(true),
            Some(false),
        );
        assert_eq!(
            fields_changed_label(&every).as_deref(),
            Some(
                "frozenRowCount=2, frozenColumnCount=3, hideGridlines=false, \
                 tabColorStyle=#FF8800, rightToLeft=true"
            )
        );
        // A clear is a property change with no value, so it says so rather
        // than reporting a hex nobody asked for.
        let cleared = update_sheet_properties(None, None, None, true, None, None);
        assert_eq!(
            fields_changed_label(&cleared).as_deref(),
            Some("tabColorStyle=cleared")
        );
        // The shape `update_sheet_properties_refuses_when_nothing_is_set`
        // logs: refused before any property was set, so there is nothing to
        // name and the key is omitted rather than written empty.
        let empty = update_sheet_properties(None, None, None, false, None, None);
        assert_eq!(fields_changed_label(&empty), None);
        // Every other verb has no `fields_changed` at all.
        assert_eq!(fields_changed_label(&rename()), None);
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_a_tab_color_and_a_clear_together() {
        // The CLI's `clap::ArgGroup` already makes these two mutually
        // exclusive, but `StructureVerb` is also reachable from a
        // non-CLI caller, so the engine refuses the combination itself
        // rather than silently letting the color win.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = update_sheet_properties(None, None, Some("#FF8800"), true, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result); // omni-dev: coverage ignore-line reason="guards this test's assumption; validate_verb_args always refuses --tab-color with --clear-tab-color as RefusedInvalidRange"
        };
        assert!(detail.contains("mutually exclusive"), "{detail}");
    }

    #[tokio::test]
    async fn update_sheet_properties_names_its_own_subcommand_in_a_refusal() {
        // `label()` exists so a refusal names the command the user typed;
        // the `not a Google Sheet` refusal is the shortest path to it, and
        // nothing else in this module renders the verb's own name.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", "application/pdf", &["parent-1"])
            .mount(&server)
            .await;
        let verb = update_sheet_properties(Some(2), None, None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedNotASpreadsheet { .. }
        ));
        let text = describe(&outcome);
        assert!(
            text.contains("drive sheets update-sheet-properties"),
            "{text}"
        );
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_a_negative_freeze_count() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = update_sheet_properties(Some(-1), None, None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result); // omni-dev: coverage ignore-line reason="guards this test's assumption; check_freeze_bound always refuses a negative --freeze-rows as RefusedInvalidRange"
        };
        assert!(
            detail.contains("--freeze-rows must be at least 0"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_freezing_every_row() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook_with_frozen_rows(118_293, 5, 0)
            .mount(&server)
            .await;
        let verb = update_sheet_properties(Some(5), None, None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result); // omni-dev: coverage ignore-line reason="guards this test's assumption; check_freeze_bound always refuses a --freeze-rows at or above the sheet's known row count as RefusedInvalidRange"
        };
        assert!(detail.contains("would freeze every row"), "{detail}");
    }

    #[tokio::test]
    async fn update_sheet_properties_allows_freezing_up_to_one_less_than_the_row_count() {
        // The boundary `check_freeze_bound` is supposed to allow: one
        // fewer than the sheet's current row count leaves exactly one row
        // unfrozen, which Sheets permits (the `>=` refusal in
        // `update_sheet_properties_refuses_freezing_every_row` above only
        // pins the refused side of this same bound).
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook_with_frozen_rows(118_293, 5, 0)
            .mount(&server)
            .await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let verb = update_sheet_properties(Some(4), None, None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn update_sheet_properties_invents_no_freeze_ceiling_when_the_count_is_unknown() {
        // The other side of `check_freeze_bound`'s `Option`: a sheet with
        // no `gridProperties` at all — which is what Sheets reports for a
        // non-grid (`OBJECT`, full-page chart) sheet — leaves
        // `row_count`/`column_count` unknown. With no count to compare
        // against there is no ceiling to enforce, so the request goes
        // through and Sheets stays the authority on whether it is legal,
        // rather than omni-dev guessing a bound (ADR-0073 §7).
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "spreadsheetId": "sheet-1",
                    "properties": {"title": "Budget"},
                    "sheets": [
                        {"properties": {"sheetId": 118_293, "title": "Q2", "index": 0}}
                    ],
                })),
            )
            .mount(&server)
            .await;
        let verb = update_sheet_properties(Some(9_000), Some(9_000), None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::WouldChange { .. }),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_a_negative_freeze_column_count() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = update_sheet_properties(None, Some(-1), None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result); // omni-dev: coverage ignore-line reason="guards this test's assumption; check_freeze_bound always refuses a negative --freeze-columns as RefusedInvalidRange"
        };
        assert!(
            detail.contains("--freeze-columns must be at least 0"),
            "{detail}"
        );
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_freezing_every_column() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        // mount_workbook()'s Q2 has columnCount 10.
        mount_workbook().mount(&server).await;
        let verb = update_sheet_properties(None, Some(10), None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result); // omni-dev: coverage ignore-line reason="guards this test's assumption; check_freeze_bound always refuses a --freeze-columns at or above the sheet's known column count as RefusedInvalidRange"
        };
        assert!(detail.contains("would freeze every column"), "{detail}");
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_an_invalid_hex_color() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = update_sheet_properties(None, None, Some("nope"), false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(
            outcome.result,
            StructureResult::RefusedInvalidRange { .. }
        ));
    }

    #[tokio::test]
    async fn update_sheet_properties_refuses_when_nothing_is_set() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        let verb = update_sheet_properties(None, None, None, false, None, None);
        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result); // omni-dev: coverage ignore-line reason="guards this test's assumption; validate_verb_args always refuses an update-sheet-properties verb that set no property as RefusedInvalidRange"
        };
        assert!(detail.contains("at least one"), "{detail}");
    }

    // ── the Drive write lease (ADR-0080 §9) ─────────────────────────────

    fn allow_rule_no_lease(folder: &str) -> FolderPermissionRule {
        FolderPermissionRule {
            require_lease: false,
            ..allow_rule(folder)
        }
    }

    #[tokio::test]
    async fn refuses_without_a_lease_when_the_rule_requires_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // No batchUpdate mock mounted — a refusal must make zero mutating
        // calls.

        let mut o = opts(rename(), false);
        o.lease_token = None;
        let outcome = structure(&drive, &sheets, &o, &[allow_rule("parent-1")]).await;
        assert_eq!(outcome.result, StructureResult::RefusedNoLease);
    }

    #[tokio::test]
    async fn refuses_an_unknown_lease_token() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let mut o = opts(rename(), false);
        o.lease_token = Some("bogus-token".to_string());
        // Never seeded — no ledger exists at this fresh path.
        o.ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let outcome = structure(&drive, &sheets, &o, &[allow_rule("parent-1")]).await;
        assert_eq!(outcome.result, StructureResult::RefusedLeaseExpired);
    }

    #[tokio::test]
    async fn refuses_a_lease_bound_to_a_different_file() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "other-sheet", "1");
        let mut o = opts(rename(), false);
        o.lease_token = Some(token);
        o.ledger_path = ledger_path;
        let outcome = structure(&drive, &sheets, &o, &[allow_rule("parent-1")]).await;
        assert_eq!(outcome.result, StructureResult::RefusedLeaseWrongFile);
    }

    #[tokio::test]
    async fn refuses_a_stale_lease() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        // Live version "1" (`mount_file`'s default) but the lease was
        // acquired at "0" — the file has moved since.
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "sheet-1", "0");
        let mut o = opts(rename(), false);
        o.lease_token = Some(token);
        o.ledger_path = ledger_path;
        let outcome = structure(&drive, &sheets, &o, &[allow_rule("parent-1")]).await;
        assert_eq!(outcome.result, StructureResult::RefusedLeaseStale);
    }

    #[tokio::test]
    async fn reports_a_lock_acquisition_failure_as_failed() {
        // A pre-existing lock file simulates another `drive lease`
        // operation genuinely in progress — reported as an operational
        // failure, not folded into `RefusedLeaseExpired`.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let o = opts(rename(), false);
        // Under `flock` (issue #1687), a busy lock now waits rather than
        // hard-failing (`check_and_lock_lease` -> `acquire_waiting`), so a
        // held `LedgerLock` no longer reproduces an immediate failure here.
        // A directory at the lock path does: opening it for write fails
        // outright with an I/O error, which is never retried.
        let mut lock_path = o.ledger_path.clone().into_os_string();
        lock_path.push(".lock");
        std::fs::create_dir(std::path::PathBuf::from(lock_path)).unwrap();

        let outcome = structure(&drive, &sheets, &o, &[allow_rule("parent-1")]).await;
        assert!(matches!(outcome.result, StructureResult::Failed { .. }));
    }

    #[tokio::test]
    async fn a_failed_pre_lease_refetch_is_reported_as_failed_with_no_batch_update_call() {
        // The gate's own resolve step succeeds off the first `files.get`,
        // but the fresh re-fetch feeding the staleness check (ADR-0080 §6)
        // fails — the change must report `Failed` and never reach
        // `batchUpdate`.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .up_to_n_times(1)
            .with_priority(1)
            .mount(&server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(wiremock::ResponseTemplate::new(500))
            .with_priority(2)
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200))
            .expect(0)
            .mount(&server)
            .await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Failed { .. }));
    }

    #[tokio::test]
    async fn a_rule_that_does_not_require_a_lease_skips_the_check_entirely() {
        // No lease token and no ledger seeded, with a rule that sets
        // `require_lease: false` — the change must still succeed, taking
        // the `else { None }` branch and never consulting the ledger.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;

        let mut o = opts(rename(), false);
        o.lease_token = None;
        let outcome = structure(&drive, &sheets, &o, &[allow_rule_no_lease("parent-1")]).await;
        assert!(matches!(
            outcome.result,
            StructureResult::Changed { backup: None, .. }
        ));
    }

    #[tokio::test]
    async fn a_rule_that_does_not_require_a_lease_still_refuses_a_stale_one_if_presented() {
        // ADR-0080 §13: `require_lease: false` relaxes the *requirement*,
        // not the *meaning* — a token volunteered anyway is checked exactly
        // like a required one, including staleness.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        // Live version "1" (`mount_file`'s default) but the lease was
        // acquired at "0" — the file has moved since.
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // No batchUpdate mock mounted — a refusal must make zero mutating
        // calls.

        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease(&ledger_path, "sheet-1", "0");
        let mut o = opts(rename(), false);
        o.lease_token = Some(token);
        o.ledger_path = ledger_path;
        let outcome = structure(&drive, &sheets, &o, &[allow_rule_no_lease("parent-1")]).await;
        assert_eq!(outcome.result, StructureResult::RefusedLeaseStale);
    }

    /// A native document's lease backs it up as a Drive copy (ADR-0080
    /// §3); a real-run delete under it names that copy's file id — the one
    /// thing a user can search the Drive UI for — and says the copy dates
    /// from acquisition, since a multi-use lease (§5) may have written
    /// since.
    #[tokio::test]
    async fn a_leased_delete_names_the_drive_copy_to_restore_from() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;

        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease_with_backup(
            &ledger_path,
            "sheet-1",
            "1",
            LeaseBackup::DriveCopy {
                file_id: "backup-copy-1".to_string(),
            },
        );
        let mut o = opts(delete_sheet(), false);
        o.lease_token = Some(token);
        o.ledger_path = ledger_path;
        let outcome = structure(&drive, &sheets, &o, &[delete_allow_rule("parent-1")]).await;

        assert!(matches!(
            &outcome.result,
            StructureResult::Changed {
                backup: Some(backup),
                ..
            } if **backup == LeaseBackup::DriveCopy { file_id: "backup-copy-1".to_string() }
        ));
        let text = describe(&outcome);
        assert!(text.contains("Deleted sheet 'Q2'"), "{text}");
        assert!(
            text.contains(
                "backed the whole spreadsheet up when it was acquired (Drive copy backup-copy-1)"
            ),
            "{text}"
        );
        assert!(
            text.contains("restores a single deleted sheet automatically"),
            "{text}"
        );
        assert!(
            text.contains("Google Drive's own version history"),
            "{text}"
        );
        assert!(!text.contains("only recovery path"), "{text}");

        // The copy rides the JSON outcome too, so a machine caller can find
        // it without parsing the message.
        let json = serde_json::to_value(&outcome).unwrap();
        assert_eq!(json["result"]["backup"]["kind"], "drive_copy");
        assert_eq!(json["result"]["backup"]["file_id"], "backup-copy-1");
    }

    /// ADR-0080 §13: a `require_lease: false` rule takes no backup of its
    /// own, so `recovery_note` falls back to ADR-0077 §5's "no recovery
    /// path but Drive's own version history" wording — but a lease
    /// volunteered anyway is still checked and its backup still named,
    /// making that fallback wording false unless the presented lease is
    /// honoured.
    #[tokio::test]
    async fn a_presented_lease_under_a_non_requiring_rule_still_names_the_backup() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;

        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease_with_backup(
            &ledger_path,
            "sheet-1",
            "1",
            LeaseBackup::DriveCopy {
                file_id: "backup-copy-1".to_string(),
            },
        );
        let mut o = opts(delete_sheet(), false);
        o.lease_token = Some(token);
        o.ledger_path = ledger_path;
        let rule = FolderPermissionRule {
            require_lease: false,
            ..delete_allow_rule("parent-1")
        };
        let outcome = structure(&drive, &sheets, &o, &[rule]).await;

        assert!(matches!(
            &outcome.result,
            StructureResult::Changed {
                backup: Some(backup),
                ..
            } if **backup == LeaseBackup::DriveCopy { file_id: "backup-copy-1".to_string() }
        ));
        let text = describe(&outcome);
        assert!(
            text.contains(
                "backed the whole spreadsheet up when it was acquired (Drive copy backup-copy-1)"
            ),
            "{text}"
        );
        assert!(!text.contains("only recovery path"), "{text}");
    }

    /// The other half of the honesty rule: a `require_lease: false` rule
    /// reaches the delete with no lease and no backup, and the message
    /// must not claim one — it falls back to ADR-0077's original wording
    /// and says why.
    #[tokio::test]
    async fn an_unleased_delete_does_not_claim_a_backup_exists() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;

        let mut o = opts(delete_sheet(), false);
        o.lease_token = None;
        let rule = FolderPermissionRule {
            require_lease: false,
            ..delete_allow_rule("parent-1")
        };
        let outcome = structure(&drive, &sheets, &o, &[rule]).await;

        assert!(matches!(
            outcome.result,
            StructureResult::Changed { backup: None, .. }
        ));
        let text = describe(&outcome);
        assert!(text.contains("Deleted sheet 'Q2'"), "{text}");
        assert!(text.contains("no lease backup was taken"), "{text}");
        assert!(text.contains("`require_lease: false`"), "{text}");
        assert!(
            text.contains("version history is the only recovery path"),
            "{text}"
        );
        assert!(!text.contains("restore from that copy"), "{text}");
        assert!(serde_json::to_value(&outcome).unwrap()["result"]
            .get("backup")
            .is_none());
    }

    // ── an applied write whose reply is unreadable (issue #2021) ────────

    /// A 2xx `batchUpdate` whose body is not the reply shape — the
    /// mutation was applied, only its reply was lost.
    fn mount_unreadable_batch_update() -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1:batchUpdate",
            ))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_string("not json"))
    }

    #[tokio::test]
    async fn add_sheet_with_an_unreadable_reply_reports_applied_reply_unreadable() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_unreadable_batch_update()
            .expect(1)
            .mount(&server)
            .await;
        let o = opts(add_sheet(), false);
        let outcome = structure(&drive, &sheets, &o, &[allow_rule("parent-1")]).await;

        // The new sheet's id was only in the lost reply, so none is claimed.
        assert!(
            matches!(
                &outcome.result,
                StructureResult::AppliedReplyUnreadable {
                    summary,
                    sheet: None,
                    sheet_id: None,
                    backup: Some(_),
                    ..
                } if summary == "add-sheet 'Q3'"
            ),
            "{:?}",
            outcome.result
        );
        let record = mutation_record(&outcome, &o, Duration::ZERO);
        assert_eq!(record.status, "applied-reply-unreadable");
        assert_eq!(record.sheet_id, None);
        assert_eq!(record.fields_changed.as_deref(), Some("add-sheet 'Q3'"));
        assert!(record.error.is_some());
        assert_eq!(outcome.result.log_status(), "applied-reply-unreadable");
        let lines = describe_lines(&outcome);
        assert!(
            lines[0].starts_with("Applied, but the reply could not be read: add-sheet 'Q3'"),
            "{lines:?}"
        );
        assert!(lines[0].contains("do not retry"), "{lines:?}");
        assert!(
            !lines[0].contains("cannot be undone"),
            "an additive verb owes no recovery note: {lines:?}"
        );
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(
            lines[1].starts_with("  the new sheet's id was in the unreadable reply"),
            "{lines:?}"
        );
        let json = serde_json::to_value(&outcome).unwrap();
        assert_eq!(json["result"]["status"], "applied-reply-unreadable");
        assert!(json["result"].get("sheet_id").is_none(), "{json}");
        assert!(json["result"].get("sheet").is_none(), "{json}");
    }

    /// A delete whose reply was unreadable still deleted, so it owes the
    /// same recovery note — naming the same lease backup — a readable one
    /// gets from `describe_changed`.
    #[tokio::test]
    async fn a_delete_with_an_unreadable_reply_still_names_the_drive_copy_to_restore_from() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_unreadable_batch_update()
            .expect(1)
            .mount(&server)
            .await;

        let ledger_path = tempfile::tempdir()
            .unwrap()
            .keep()
            .join("lease-ledger.jsonl");
        let token = seed_lease_with_backup(
            &ledger_path,
            "sheet-1",
            "1",
            LeaseBackup::DriveCopy {
                file_id: "backup-copy-1".to_string(),
            },
        );
        let mut o = opts(delete_sheet(), false);
        o.lease_token = Some(token);
        o.ledger_path = ledger_path;
        let outcome = structure(&drive, &sheets, &o, &[delete_allow_rule("parent-1")]).await;

        assert!(
            matches!(
                &outcome.result,
                StructureResult::AppliedReplyUnreadable {
                    backup: Some(backup),
                    ..
                } if **backup == LeaseBackup::DriveCopy { file_id: "backup-copy-1".to_string() }
            ),
            "{:?}",
            outcome.result
        );
        let text = describe(&outcome);
        assert!(
            text.starts_with("Applied, but the reply could not be read: delete-sheet 'Q2'"),
            "{text}"
        );
        assert!(
            text.contains(&format!(
                "; {}",
                recovery_note(
                    Some(&LeaseBackup::DriveCopy {
                        file_id: "backup-copy-1".to_string(),
                    }),
                    true,
                )
            )),
            "{text}"
        );
        // The target sheet's id and snapshot are plan-time data, not the
        // reply's, so they survive exactly as `Changed` would carry them.
        assert!(
            text.contains("delete-sheet 'Q2' (sheetId 118293) in 'sheet-1'"),
            "{text}"
        );
        let json = serde_json::to_value(&outcome).unwrap();
        assert_eq!(json["result"]["backup"]["file_id"], "backup-copy-1");
        assert_eq!(json["result"]["sheet_id"], 118_293);
        assert_eq!(json["result"]["sheet"]["title"], "Q2");
        let record = mutation_record(&outcome, &o, Duration::ZERO);
        assert_eq!(record.sheet_id, Some(118_293));
        assert_eq!(record.fields_changed.as_deref(), Some("delete-sheet 'Q2'"));
        assert!(record.error.is_some());
    }

    /// `update-sheet-properties` logs its own field list, which names more
    /// than the summary; `fields_changed` is still never `None`.
    #[test]
    fn an_unreadable_reply_logs_the_verbs_own_field_list_when_it_has_one() {
        let verb = StructureVerb::UpdateSheetProperties {
            sheet: "Q2".to_string(),
            freeze_rows: Some(2),
            freeze_columns: None,
            tab_color: None,
            clear_tab_color: false,
            right_to_left: None,
            hide_gridlines: None,
        };
        let outcome =
            unreadable_outcome_with_id(verb.clone(), "update-sheet-properties 'Q2'", 118_293);
        let record = mutation_record(&outcome, &opts(verb, false), Duration::ZERO);
        assert_eq!(record.fields_changed.as_deref(), Some("frozenRowCount=2"));
        assert_eq!(record.sheet_id, Some(118_293));
    }

    #[test]
    fn describe_lines_names_the_known_sheet_id_of_an_unreadable_reply() {
        assert_eq!(
            describe_lines(&unreadable_outcome_with_id(
                rename(),
                "rename-sheet 'Q2' to 'Q3'",
                7
            )),
            vec![
                "Applied, but the reply could not be read: rename-sheet 'Q2' to 'Q3' \
                 (sheetId 7) in 'Budget' — do not retry; check the spreadsheet first \
                 (bad reply)"
                    .to_string()
            ]
        );
    }

    fn unreadable_outcome(verb: StructureVerb, summary: &str) -> StructureOutcome {
        StructureOutcome {
            spreadsheet_id: "sheet-1".to_string(),
            file_name: Some("Budget".to_string()),
            resolved_folder_id: None,
            verb,
            result: StructureResult::AppliedReplyUnreadable {
                summary: summary.to_string(),
                detail: "bad reply".to_string(),
                sheet: None,
                sheet_id: None,
                backup: None,
            },
        }
    }

    /// [`unreadable_outcome`] for a verb whose target sheet resolved to
    /// `sheet_id`, as the engine builds it.
    fn unreadable_outcome_with_id(
        verb: StructureVerb,
        summary: &str,
        sheet_id: i64,
    ) -> StructureOutcome {
        let mut outcome = unreadable_outcome(verb, summary);
        if let StructureResult::AppliedReplyUnreadable {
            sheet: s,
            sheet_id: id,
            ..
        } = &mut outcome.result
        {
            *s = Some(Box::new(SheetSnapshot {
                sheet_id: Some(sheet_id),
                title: "Q2".to_string(),
                ..Default::default()
            }));
            *id = Some(sheet_id);
        }
        outcome
    }

    #[test]
    fn describe_lines_renders_applied_reply_unreadable_for_an_additive_verb() {
        let lines = describe_lines(&unreadable_outcome(
            duplicate_sheet(),
            "duplicate-sheet 'Q2'",
        ));
        assert_eq!(
            lines,
            vec![
                "Applied, but the reply could not be read: duplicate-sheet 'Q2' in 'Budget' — \
                 do not retry; check the spreadsheet first (bad reply)"
                    .to_string(),
                "  the new sheet's id was in the unreadable reply; check the spreadsheet's tabs \
                 to find it"
                    .to_string(),
            ]
        );
        assert_eq!(
            describe_lines(&unreadable_outcome(rename(), "rename-sheet 'Q2' to 'Q3'")),
            vec![
                "Applied, but the reply could not be read: rename-sheet 'Q2' to 'Q3' in \
                 'Budget' — do not retry; check the spreadsheet first (bad reply)"
                    .to_string()
            ]
        );
    }

    #[test]
    fn describe_lines_renders_applied_reply_unreadable_for_a_destructive_verb() {
        let lines = describe_lines(&unreadable_outcome(
            delete_rows(),
            "delete-rows 'Q2' (ROWS 5:7)",
        ));
        assert_eq!(
            lines,
            vec![format!(
                "Applied, but the reply could not be read: delete-rows 'Q2' (ROWS 5:7) in \
                 'Budget' — do not retry; check the spreadsheet first (bad reply); {}",
                recovery_note(None, false)
            )]
        );
    }

    #[test]
    fn applied_summary_names_the_verb_sheet_and_span() {
        assert_eq!(applied_summary(&add_sheet()), "add-sheet 'Q3'");
        assert_eq!(applied_summary(&rename()), "rename-sheet 'Q2' to 'Q3'");
        assert_eq!(
            applied_summary(&delete_rows()),
            "delete-rows 'Q2' (ROWS 5:7)"
        );
        assert_eq!(
            applied_summary(&update_workbook_properties()),
            "update-workbook-properties"
        );
    }

    // ── move-rows / move-columns (issue #1834) ─────────────────────────

    /// The `batchUpdate` body the server actually received.
    fn sent_batch_update(requests: &[wiremock::Request]) -> serde_json::Value {
        requests
            .iter()
            .find(|r| r.url.path().ends_with(":batchUpdate"))
            .map(|r| serde_json::from_slice(&r.body).unwrap())
            .expect("a batchUpdate request")
    }

    /// [`mount_workbook`] with the `Q2` sheet object supplied wholesale —
    /// the hook the "does not consult" tests below use to add grid state
    /// this engine must keep ignoring.
    fn mount_workbook_with_q2(q2: serde_json::Value) -> wiremock::Mock {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(workbook_body(q2)))
    }

    /// Everything a move's real run needs mounted, minus the workbook.
    async fn mount_move_prereqs(server: &wiremock::MockServer) {
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(server)
            .await;
        mount_folder("parent-1").mount(server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(server)
            .await;
    }

    /// The conversion this verb exists to get right: `--at 2 --count 2`
    /// becomes the half-open `[1, 3)`, and `--before 6` becomes
    /// `destinationIndex: 5` — the API's *pre-move* numbering, so the block
    /// actually lands on rows 4-5, not row 6.
    #[tokio::test]
    async fn move_rows_apply_sends_move_dimension_with_pre_move_destination() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(move_rows(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );

        let requests = server.received_requests().await.unwrap();
        let body = sent_batch_update(&requests);
        assert_eq!(
            body["requests"][0]["moveDimension"],
            serde_json::json!({
                "source": {
                    "sheetId": 118_293, "dimension": "ROWS",
                    "startIndex": 1, "endIndex": 3,
                },
                "destinationIndex": 5,
            })
        );
        assert_eq!(body["requests"].as_array().unwrap().len(), 1);

        // The real-run message resolves the pre-move numbering for the
        // reader rather than echoing `--before` alone.
        let rendered = describe(&outcome);
        assert!(rendered.contains("Moved 2 row(s) 2-3"), "{rendered}");
        assert!(rendered.contains("to before row 6"), "{rendered}");
        assert!(rendered.contains("(now rows 4-5)"), "{rendered}");
    }

    #[tokio::test]
    async fn move_columns_apply_sends_move_dimension() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveColumns {
                    sheet: "Q2".to_string(),
                    at: 2,
                    count: 2,
                    before: 6,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );

        let requests = server.received_requests().await.unwrap();
        let body = sent_batch_update(&requests);
        assert_eq!(
            body["requests"][0]["moveDimension"],
            serde_json::json!({
                "source": {
                    "sheetId": 118_293, "dimension": "COLUMNS",
                    "startIndex": 1, "endIndex": 3,
                },
                "destinationIndex": 5,
            })
        );
    }

    /// The append boundary: `Q2` has 500 rows, so `--before 501` is the
    /// furthest legal destination — "move it to the very end" — and must
    /// not be refused the way `--before 502` is.
    #[tokio::test]
    async fn move_rows_to_the_end_uses_row_count_plus_one() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: 1,
                    count: 1,
                    before: 501,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );

        let requests = server.received_requests().await.unwrap();
        let body = sent_batch_update(&requests);
        assert_eq!(
            body["requests"][0]["moveDimension"]["destinationIndex"],
            500
        );
    }

    /// The source block must exist in full — `delete`'s rule, and the
    /// reason a move validates two spans rather than one.
    #[tokio::test]
    async fn move_rows_refuses_a_source_past_the_sheets_end() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: 499,
                    count: 3,
                    before: 1,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("500 row(s)"), "{detail}");
        assert!(detail.contains("501"), "{detail}");
    }

    #[tokio::test]
    async fn move_rows_refuses_a_destination_past_the_end() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: 5,
                    count: 1,
                    before: 502,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
            panic!("expected RefusedInvalidRange, got {:?}", outcome.result);
        };
        assert!(detail.contains("500 row(s)"), "{detail}");
        assert!(detail.contains("501"), "{detail}");
    }

    /// The refusal a move adds on top of insert's and delete's: for
    /// `--at 2 --count 2` the block occupies rows 2-3, and every
    /// `--before` in `2..=4` describes where it already is. Sheets accepts
    /// all three and changes nothing, so reporting "Moved" would be a
    /// lie — the "never promise a change the real run then rejects" rule
    /// read the other way round.
    #[tokio::test]
    async fn move_rows_refuses_a_destination_inside_or_adjacent_to_the_block() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        for before in 2..=4 {
            let outcome = structure(
                &drive,
                &sheets,
                &opts(
                    StructureVerb::MoveRows {
                        sheet: "Q2".to_string(),
                        at: 2,
                        count: 2,
                        before,
                    },
                    false,
                ),
                &[allow_rule("parent-1")],
            )
            .await;
            let StructureResult::RefusedInvalidRange { detail } = &outcome.result else {
                panic!(
                    "expected RefusedInvalidRange for --before {before}, got {:?}",
                    outcome.result
                );
            };
            assert!(detail.contains("nothing would move"), "{detail}");
            assert!(detail.contains("rows 2-3"), "{detail}");
        }
    }

    /// The two values immediately outside that band, which must stay legal.
    /// For rows 2-3: `--before 1` is the smallest upward move (one position
    /// earlier) and `--before 5` the smallest downward one — `4` is the
    /// no-op boundary, so `5` is the first real move above the block, not
    /// `4`.
    #[tokio::test]
    async fn move_rows_allows_a_destination_immediately_adjacent_but_outside_the_block() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        // `dry_run: true` throughout: the point is the classification, and
        // a dry run issues no `batchUpdate` to mock.
        for before in [1, 5] {
            let outcome = structure(
                &drive,
                &sheets,
                &opts(
                    StructureVerb::MoveRows {
                        sheet: "Q2".to_string(),
                        at: 2,
                        count: 2,
                        before,
                    },
                    true,
                ),
                &[allow_rule("parent-1")],
            )
            .await;
            assert!(
                matches!(outcome.result, StructureResult::WouldChange { .. }),
                "--before {before} must be a real move, got {:?}",
                outcome.result
            );
        }
    }

    #[test]
    fn move_bounds_refuse_every_argument_below_one() {
        let sheet = SheetSnapshot {
            sheet_id: Some(1),
            title: "Q2".to_string(),
            row_count: Some(500),
            column_count: Some(26),
            ..Default::default()
        };
        for (at, count, before, expected) in [
            (2, 0, 9, "--count must be at least 1, got 0"),
            (0, 1, 9, "--at must be at least 1, got 0"),
            (2, 1, 0, "--before must be at least 1, got 0"),
        ] {
            let Err(StructureResult::RefusedInvalidRange { detail }) =
                validate_move_bounds(Dimension::Rows, at, count, before, Some(&sheet))
            else {
                panic!(
                    "expected RefusedInvalidRange for --at {at} --count {count} --before {before}"
                );
            };
            assert_eq!(detail, expected);
        }
    }

    #[test]
    fn a_move_at_and_count_that_would_overflow_the_index_space_are_refused() {
        let sheet = SheetSnapshot {
            sheet_id: Some(1),
            title: "Q2".to_string(),
            row_count: Some(500),
            column_count: Some(26),
            ..Default::default()
        };
        // `--before 1` throughout, so the overflow guard is what fires and
        // not the inside-the-block refusal that follows it.
        for (at, count) in [(i64::MAX, 5), (500, i64::MAX)] {
            let Err(StructureResult::RefusedInvalidRange { detail }) =
                validate_move_bounds(Dimension::Rows, at, count, 1, Some(&sheet))
            else {
                panic!("expected RefusedInvalidRange for --at {at} --count {count}");
            };
            assert!(detail.contains("overflows the row index space"), "{detail}");
        }
    }

    /// `record_attempt` builds a record from the very arguments
    /// `validate_move_bounds` just rejected, so `dimension_range_label`'s
    /// span arithmetic runs on them. Plain arithmetic panics here rather
    /// than in the mutation it refused to make — the
    /// `a_refused_out_of_range_insert_still_records_without_panicking`
    /// regression, for the move verbs.
    #[tokio::test]
    async fn a_refused_move_still_records_without_panicking() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: i64::MAX,
                    count: 5,
                    before: 1,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::RefusedInvalidRange { .. }),
            "{:?}",
            outcome.result
        );
    }

    /// The dry run's second line is where `--before`'s pre-move numbering
    /// stops being a trap: rows 2-3 moved to before row 6 land on rows
    /// 4-5, because rows 4-5 slid up into the gap first.
    #[tokio::test]
    async fn move_rows_dry_run_describes_a_downward_move_and_its_landing_rows() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(move_rows(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        let lines = describe_lines(&outcome);
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(lines[0].contains("Would move 2 row(s) 2-3"), "{lines:?}");
        assert!(lines[0].contains("to before row 6"), "{lines:?}");
        assert_eq!(
            lines[1],
            "  (500 rows unchanged; rows 4-5 shift up to 2-3; moved rows land at 4-5)"
        );
    }

    /// The mirror image: an upward move lands the block exactly on the
    /// number typed, and pushes everything from there to its old start
    /// forward by `--count`.
    #[tokio::test]
    async fn move_rows_dry_run_describes_an_upward_move_and_its_landing_rows() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: 6,
                    count: 2,
                    before: 2,
                },
                true,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let lines = describe_lines(&outcome);
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(lines[0].contains("Would move 2 row(s) 6-7"), "{lines:?}");
        assert!(lines[0].contains("to before row 2"), "{lines:?}");
        assert_eq!(
            lines[1],
            "  (500 rows unchanged; rows 2-5 shift down to 4-7; moved rows land at 2-3)"
        );
    }

    /// [`move_rows_dry_run_describes_a_downward_move_and_its_landing_rows`]'s
    /// twin on the other dimension, pinning `describe_would_move`'s
    /// `Dimension::Columns` wording (noun, plural, and `left`/`right`
    /// direction words) before the two branches are collapsed into one
    /// template.
    #[tokio::test]
    async fn move_columns_dry_run_describes_a_downward_move_and_its_landing_columns() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveColumns {
                    sheet: "Q2".to_string(),
                    at: 2,
                    count: 2,
                    before: 6,
                },
                true,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let lines = describe_lines(&outcome);
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(lines[0].contains("Would move 2 column(s) 2-3"), "{lines:?}");
        assert!(lines[0].contains("to before column 6"), "{lines:?}");
        assert_eq!(
            lines[1],
            "  (10 columns unchanged; columns 4-5 shift left to 2-3; moved columns land at 4-5)"
        );
    }

    /// [`move_rows_dry_run_describes_an_upward_move_and_its_landing_rows`]'s
    /// twin on the other dimension — see the downward test above for why
    /// this pins the refactor.
    #[tokio::test]
    async fn move_columns_dry_run_describes_an_upward_move_and_its_landing_columns() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveColumns {
                    sheet: "Q2".to_string(),
                    at: 6,
                    count: 2,
                    before: 2,
                },
                true,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        let lines = describe_lines(&outcome);
        assert_eq!(lines.len(), 2, "{lines:?}");
        assert!(lines[0].contains("Would move 2 column(s) 6-7"), "{lines:?}");
        assert!(lines[0].contains("to before column 2"), "{lines:?}");
        assert_eq!(
            lines[1],
            "  (10 columns unchanged; columns 2-5 shift right to 4-7; moved columns land at 2-3)"
        );
    }

    /// A preview and a real run share one classification by construction
    /// (the dry run returns after the gate, not before it), so a refusal
    /// must read identically either way — `--dry-run` may never promise a
    /// move the real run then refuses.
    #[tokio::test]
    async fn move_rows_dry_run_matches_the_real_run_refusal() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook().mount(&server).await;

        let verb = StructureVerb::MoveRows {
            sheet: "Q2".to_string(),
            at: 5,
            count: 1,
            before: 502,
        };
        let real = structure(
            &drive,
            &sheets,
            &opts(verb.clone(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        let dry = structure(
            &drive,
            &sheets,
            &opts(verb, true),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(real.result, StructureResult::RefusedInvalidRange { .. }),
            "{:?}",
            real.result
        );
        assert_eq!(dry.result, real.result);
    }

    /// Frozen panes are Sheets' own business. `moveDimension` interacts with
    /// them server-side (a frozen band does not travel with the move), and
    /// no client-side check here may grow around that: the request must be
    /// byte-identical to the one sent against a sheet with no frozen rows,
    /// and the move must not be refused. ADR-0073 §7's rule — Sheets is the
    /// authority on its own semantics.
    #[tokio::test]
    async fn move_rows_does_not_consult_frozen_rows() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook_with_q2(serde_json::json!({
            "properties": {
                "sheetId": 118_293, "title": "Q2", "index": 1,
                "gridProperties": {
                    "rowCount": 500, "columnCount": 10, "frozenRowCount": 2,
                },
            },
        }))
        .mount(&server)
        .await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: 1,
                    count: 1,
                    before: 3,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );

        let requests = server.received_requests().await.unwrap();
        let body = sent_batch_update(&requests);
        assert_eq!(
            body["requests"][0]["moveDimension"],
            serde_json::json!({
                "source": {
                    "sheetId": 118_293, "dimension": "ROWS",
                    "startIndex": 0, "endIndex": 1,
                },
                "destinationIndex": 2,
            })
        );
    }

    /// The same claim for row/column groups: an outline group whose range
    /// spans the block being moved is state this engine never reads, so it
    /// can neither refuse nor reshape the request. Sheets resolves what
    /// happens to the group.
    #[tokio::test]
    async fn move_rows_does_not_consult_dimension_groups() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_move_prereqs(&server).await;
        mount_workbook_with_q2(serde_json::json!({
            "properties": {
                "sheetId": 118_293, "title": "Q2", "index": 1,
                "gridProperties": {"rowCount": 500, "columnCount": 10},
            },
            "rowGroups": [{
                "range": {
                    "sheetId": 118_293, "dimension": "ROWS",
                    "startIndex": 1, "endIndex": 4,
                },
            }],
        }))
        .mount(&server)
        .await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(
                StructureVerb::MoveRows {
                    sheet: "Q2".to_string(),
                    at: 2,
                    count: 1,
                    before: 1,
                },
                false,
            ),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );

        let requests = server.received_requests().await.unwrap();
        let body = sent_batch_update(&requests);
        assert_eq!(
            body["requests"][0]["moveDimension"],
            serde_json::json!({
                "source": {
                    "sheetId": 118_293, "dimension": "ROWS",
                    "startIndex": 1, "endIndex": 2,
                },
                "destinationIndex": 0,
            })
        );
    }

    // ── update-workbook-properties (issue #1836) ────────────────────────

    #[test]
    fn sheet_title_is_none_for_update_workbook_properties() {
        assert_eq!(update_workbook_properties().sheet_title(), None);
        assert_eq!(update_workbook_properties().new_sheet_title(), None);
        assert_eq!(update_workbook_properties().dimension(), None);
    }

    #[test]
    fn resolve_sheet_returns_none_for_update_workbook_properties_without_consulting_sheets() {
        // An empty `sheets` list would make every other verb's
        // `resolve_sheet` fail with `RefusedSheetNotFound` — this verb must
        // return `Ok(None)` regardless, since it never looks.
        let workbook = Spreadsheet {
            spreadsheet_id: Some("sheet-1".to_string()),
            properties: None,
            sheets: Vec::new(),
            named_ranges: Vec::new(),
        };
        assert_eq!(
            resolve_sheet(&workbook, &update_workbook_properties()),
            Ok(None)
        );
    }

    #[test]
    fn validate_verb_args_refuses_update_workbook_properties_with_no_fields() {
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: None,
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: None,
        };
        let workbook = Spreadsheet::default();
        let err = validate_verb_args(&workbook, &verb, None).unwrap_err();
        assert!(
            matches!(&err, StructureResult::RefusedInvalidRange { detail }
                if detail.contains("at least one property")),
            "{err:?}"
        );
    }

    fn update_time_zone(time_zone: &str) -> StructureVerb {
        StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: Some(time_zone.to_string()),
            auto_recalc: None,
            iterative_calculation: None,
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: None,
        }
    }

    #[test]
    fn validate_verb_args_refuses_an_unrecognised_time_zone() {
        // The API accepts this with a 200 and resets the workbook to
        // `Etc/GMT` (issue #1938), so the refusal has to be local.
        let workbook = Spreadsheet::default();
        let err =
            validate_verb_args(&workbook, &update_time_zone("Bogus/Zone9"), None).unwrap_err();
        assert!(
            matches!(&err, StructureResult::RefusedInvalidRange { detail }
                if detail.contains("'Bogus/Zone9'")
                    && detail.contains("IANA")
                    && detail.contains("America/New_York")),
            "{err:?}"
        );
    }

    #[test]
    fn validate_verb_args_accepts_recognised_iana_time_zones() {
        let workbook = Spreadsheet::default();
        for tz in ["Europe/London", "America/New_York", "Etc/GMT", "UTC"] {
            assert_eq!(
                validate_verb_args(&workbook, &update_time_zone(tz), None),
                Ok(()),
                "{tz}"
            );
        }
    }

    #[test]
    fn validate_verb_args_refuses_iterative_calculation_settings_without_the_toggle() {
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: None,
            iterative_calculation_max_iterations: Some(50),
            iterative_calculation_convergence_threshold: None,
        };
        let workbook = Spreadsheet::default();
        let err = validate_verb_args(&workbook, &verb, None).unwrap_err();
        assert!(
            matches!(&err, StructureResult::RefusedInvalidRange { detail }
                if detail.contains("--iterative-calculation on")),
            "{err:?}"
        );

        // Also refused when explicitly turning it *off*.
        let verb_off = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::Off),
            iterative_calculation_max_iterations: Some(50),
            iterative_calculation_convergence_threshold: None,
        };
        assert!(validate_verb_args(&workbook, &verb_off, None).is_err());
    }

    #[test]
    fn validate_verb_args_refuses_non_positive_iterative_calculation_bounds() {
        let workbook = Spreadsheet::default();
        let bad_max = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::On),
            iterative_calculation_max_iterations: Some(0),
            iterative_calculation_convergence_threshold: None,
        };
        assert!(validate_verb_args(&workbook, &bad_max, None).is_err());

        let bad_threshold = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::On),
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: Some(0.0),
        };
        assert!(validate_verb_args(&workbook, &bad_threshold, None).is_err());

        let nan_threshold = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::On),
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: Some(f64::NAN),
        };
        assert!(validate_verb_args(&workbook, &nan_threshold, None).is_err());
    }

    #[test]
    fn validate_verb_args_accepts_positive_iterative_calculation_bounds() {
        let workbook = Spreadsheet::default();
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::On),
            iterative_calculation_max_iterations: Some(50),
            iterative_calculation_convergence_threshold: Some(0.01),
        };
        assert!(validate_verb_args(&workbook, &verb, None).is_ok());
    }

    #[test]
    fn validate_verb_args_accepts_a_single_field() {
        let workbook = Spreadsheet::default();
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: Some("fr_FR".to_string()),
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: None,
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: None,
        };
        assert!(validate_verb_args(&workbook, &verb, None).is_ok());
    }

    #[test]
    fn build_request_masks_exactly_the_fields_given() {
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: Some("en_US".to_string()),
            time_zone: None,
            auto_recalc: Some(RecalculationInterval::Hour),
            iterative_calculation: None,
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: None,
        };
        let request = build_request(&verb, None).unwrap();
        let BatchUpdateRequestItem::UpdateSpreadsheetProperties(req) = request else {
            panic!("expected UpdateSpreadsheetProperties, got {request:?}"); // omni-dev: coverage ignore-line reason="build_request always returns UpdateSpreadsheetProperties for an UpdateWorkbookProperties verb, so this else-arm exists only to unwrap the shared enum"
        };
        assert_eq!(req.fields, "locale,autoRecalc");
        assert_eq!(req.properties.locale.as_deref(), Some("en_US"));
        assert_eq!(req.properties.time_zone, None);
        assert_eq!(
            req.properties.auto_recalc,
            Some(RecalculationInterval::Hour)
        );
        assert_eq!(req.properties.iterative_calculation_settings, None);
    }

    #[test]
    fn build_request_turns_iterative_calculation_on_with_explicit_settings() {
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::On),
            iterative_calculation_max_iterations: Some(50),
            iterative_calculation_convergence_threshold: Some(0.01),
        };
        let request = build_request(&verb, None).unwrap();
        let BatchUpdateRequestItem::UpdateSpreadsheetProperties(req) = request else {
            panic!("expected UpdateSpreadsheetProperties, got {request:?}"); // omni-dev: coverage ignore-line reason="build_request always returns UpdateSpreadsheetProperties for an UpdateWorkbookProperties verb, so this else-arm exists only to unwrap the shared enum"
        };
        assert_eq!(req.fields, "iterativeCalculationSettings");
        assert_eq!(
            req.properties.iterative_calculation_settings,
            Some(IterativeCalculationSettings {
                max_iterations: Some(50),
                convergence_threshold: Some(0.01),
            })
        );
    }

    #[test]
    fn build_request_turns_iterative_calculation_off_by_naming_the_field_without_a_value() {
        // The field-mask idiom `IterativeCalculationSettings`'s doc comment
        // describes: `fields` names the property, but
        // `iterative_calculation_settings` itself stays `None`, so it is
        // omitted from the JSON body and the server clears it.
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: None,
            time_zone: None,
            auto_recalc: None,
            iterative_calculation: Some(IterativeCalculationToggle::Off),
            iterative_calculation_max_iterations: None,
            iterative_calculation_convergence_threshold: None,
        };
        let request = build_request(&verb, None).unwrap();
        let BatchUpdateRequestItem::UpdateSpreadsheetProperties(req) = request else {
            panic!("expected UpdateSpreadsheetProperties, got {request:?}"); // omni-dev: coverage ignore-line reason="build_request always returns UpdateSpreadsheetProperties for an UpdateWorkbookProperties verb, so this else-arm exists only to unwrap the shared enum"
        };
        assert_eq!(req.fields, "iterativeCalculationSettings");
        assert_eq!(req.properties.iterative_calculation_settings, None);
        let json = serde_json::to_value(&req.properties).unwrap();
        assert!(
            json.as_object().unwrap().is_empty(),
            "expected an empty properties object, got {json}"
        );
    }

    #[test]
    fn workbook_properties_summary_formats_every_field() {
        let verb = StructureVerb::UpdateWorkbookProperties {
            locale: Some("en_US".to_string()),
            time_zone: Some("America/New_York".to_string()),
            auto_recalc: Some(RecalculationInterval::OnChange),
            iterative_calculation: Some(IterativeCalculationToggle::On),
            iterative_calculation_max_iterations: Some(50),
            iterative_calculation_convergence_threshold: Some(0.01),
        };
        let summary = workbook_properties_summary(&verb);
        assert_eq!(
            summary,
            "locale -> 'en_US', time zone -> 'America/New_York', \
             auto-recalc -> ON_CHANGE, iterative calculation -> on \
             (max 50 iterations, threshold 0.01)"
        );
    }

    #[tokio::test]
    async fn update_workbook_properties_dry_run_reports_would_change_with_no_sheet() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(update_workbook_properties(), true),
            &[allow_rule("parent-1")],
        )
        .await;
        match &outcome.result {
            StructureResult::WouldChange { sheet, sheet_count } => {
                assert_eq!(*sheet, None);
                assert_eq!(*sheet_count, 2);
            }
            other => panic!("expected WouldChange, got {other:?}"), // omni-dev: coverage ignore-line reason="guards this test's assumption; a dry run against an allowed target always reaches WouldChange here"
        }
        let lines = describe_lines(&outcome);
        assert_eq!(lines.len(), 1);
        assert!(
            lines[0].starts_with("Would update workbook properties of 'sheet-1'"),
            "{lines:?}"
        );

        // A dry run reads the workbook (to report `sheet_count` honestly)
        // but never calls `batchUpdate`.
        let requests = server.received_requests().await.unwrap();
        assert!(!requests
            .iter()
            .any(|r| r.url.path().ends_with(":batchUpdate")));
    }

    #[tokio::test]
    async fn update_workbook_properties_refuses_an_unrecognised_time_zone_on_dry_run_and_apply() {
        // Issue #1938: a dry run used to report "would change" for a zone the
        // API silently replaces with `Etc/GMT`. Both paths now refuse it.
        for dry_run in [true, false] {
            let server = wiremock::MockServer::start().await;
            let (drive, sheets) = clients(&server).await;
            mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
                .mount(&server)
                .await;
            mount_folder("parent-1").mount(&server).await;
            mount_workbook().mount(&server).await;

            let outcome = structure(
                &drive,
                &sheets,
                &opts(update_time_zone("Bogus/Zone9"), dry_run),
                &[allow_rule("parent-1")],
            )
            .await;
            assert!(
                matches!(&outcome.result, StructureResult::RefusedInvalidRange { detail }
                    if detail.contains("'Bogus/Zone9'")),
                "dry_run={dry_run}: {:?}",
                outcome.result
            );
            let requests = server.received_requests().await.unwrap();
            assert!(
                !requests
                    .iter()
                    .any(|r| r.url.path().ends_with(":batchUpdate")),
                "dry_run={dry_run}"
            );
        }
    }

    #[tokio::test]
    async fn update_workbook_properties_apply_sends_the_masked_request_and_reports_changed() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(update_workbook_properties(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        match &outcome.result {
            StructureResult::Changed {
                sheet, sheet_id, ..
            } => {
                assert_eq!(*sheet, None);
                assert_eq!(*sheet_id, None);
            }
            other => panic!("expected Changed, got {other:?}"), // omni-dev: coverage ignore-line reason="guards this test's assumption; an apply against an allowed target with a mocked batchUpdate always reaches Changed here"
        }

        let requests = server.received_requests().await.unwrap();
        let body = sent_batch_update(&requests);
        let update = &body["requests"][0]["updateSpreadsheetProperties"];
        assert_eq!(update["properties"]["locale"], "en_US");
        assert_eq!(update["properties"]["timeZone"], "America/New_York");
        assert_eq!(update["properties"]["autoRecalc"], "ON_CHANGE");
        assert_eq!(update["fields"], "locale,timeZone,autoRecalc");
    }

    #[test]
    fn record_attempt_carries_the_fields_changed_summary_and_no_sheet_title() {
        let opts = opts(update_workbook_properties(), false);
        assert_eq!(opts.verb.sheet_title(), None);
        assert_eq!(
            workbook_properties_summary(&opts.verb),
            "locale -> 'en_US', time zone -> 'America/New_York', auto-recalc -> ON_CHANGE"
        );
    }

    // ── plumbing ───────────────────────────────────────────────────────

    #[test]
    fn log_operation_is_distinct_per_verb() {
        let verbs = [
            add_sheet(),
            rename(),
            insert_rows(),
            StructureVerb::InsertColumns {
                sheet: "Q2".to_string(),
                at: 1,
                count: 1,
            },
            insert_range(),
            move_rows(),
            StructureVerb::MoveColumns {
                sheet: "Q2".to_string(),
                at: 1,
                count: 1,
                before: 3,
            },
            delete_sheet(),
            delete_rows(),
            StructureVerb::DeleteColumns {
                sheet: "Q2".to_string(),
                at: 1,
                count: 1,
            },
            delete_range(),
            duplicate_sheet(),
            reorder_sheet(),
            hide_sheet(),
            show_sheet(),
            update_workbook_properties(),
        ];
        let names: Vec<&str> = verbs.iter().map(StructureVerb::log_operation).collect();
        assert_eq!(
            names,
            vec![
                "sheets-add-sheet",
                "sheets-rename-sheet",
                "sheets-insert-rows",
                "sheets-insert-columns",
                "sheets-insert-range",
                "sheets-move-rows",
                "sheets-move-columns",
                "sheets-delete-sheet",
                "sheets-delete-rows",
                "sheets-delete-columns",
                "sheets-delete-range",
                "sheets-duplicate-sheet",
                "sheets-reorder-sheet",
                "sheets-hide-sheet",
                "sheets-show-sheet",
                "sheets-update-workbook-properties",
            ]
        );
        // One record per user-visible verb means the operations must not
        // collide with each other or with the cell verbs.
        let unique: HashSet<&&str> = names.iter().collect();
        assert_eq!(unique.len(), names.len());
        assert!(!names.contains(&"sheets-write"));
    }

    #[test]
    fn insert_range_records_its_one_based_inclusive_grid_context() {
        assert_eq!(
            grid_range_label(&insert_range()).as_deref(),
            Some("rows 2-4, columns 2-3")
        );
    }

    /// One of every [`StructureResult`] variant.
    ///
    /// Exhaustive and wildcard-free on purpose, mirroring `write.rs`'s
    /// `every_write_result`: adding a variant breaks this build, which is
    /// what forces the new arm through the newline check below.
    fn every_structure_result() -> Vec<StructureResult> {
        let all = vec![
            StructureResult::WouldChange {
                sheet: Some(Box::new(SheetSnapshot {
                    sheet_id: Some(7),
                    title: "Q2".to_string(),
                    row_count: Some(500),
                    column_count: Some(26),
                    ..Default::default()
                })),
                sheet_count: 2,
            },
            StructureResult::RefusedNotASpreadsheet {
                mime_type: "application/pdf".to_string(),
            },
            StructureResult::RefusedShortcut,
            StructureResult::RefusedNoVisibleParents,
            StructureResult::RefusedSheetNotFound {
                title: "Nope".to_string(),
                available: vec!["Q1".to_string(), "Q2".to_string()],
            },
            StructureResult::RefusedSheetExists {
                title: "Q1".to_string(),
            },
            StructureResult::RefusedInvalidRange {
                detail: "--count must be at least 1, got 0".to_string(),
            },
            StructureResult::Blocked { decided_by: None },
            StructureResult::RefusedNoLease,
            StructureResult::RefusedLeaseExpired,
            StructureResult::RefusedLeaseWrongFile,
            StructureResult::RefusedLeaseStale,
            StructureResult::Unchanged {
                detail: "sheet 'Q2' is already hidden".to_string(),
            },
            StructureResult::Changed {
                sheet: Some(Box::new(SheetSnapshot {
                    sheet_id: Some(7),
                    title: "Q2".to_string(),
                    row_count: Some(500),
                    column_count: Some(26),
                    ..Default::default()
                })),
                sheet_id: Some(7),
                backup: Some(Box::new(LeaseBackup::DriveCopy {
                    file_id: "backup-copy-1".to_string(),
                })),
            },
            StructureResult::AppliedReplyUnreadable {
                summary: "delete-sheet 'Q2'".to_string(),
                detail: "bad reply".to_string(),
                sheet: Some(Box::new(SheetSnapshot {
                    sheet_id: Some(7),
                    title: "Q2".to_string(),
                    row_count: Some(500),
                    column_count: Some(26),
                    ..Default::default()
                })),
                sheet_id: Some(7),
                backup: Some(Box::new(LeaseBackup::DriveCopy {
                    file_id: "backup-copy-1".to_string(),
                })),
            },
            StructureResult::Failed {
                detail: "boom".to_string(),
            },
        ];
        // Compile-time exhaustiveness: a new variant fails to match here.
        for result in &all {
            match result {
                StructureResult::WouldChange { .. }
                | StructureResult::RefusedNotASpreadsheet { .. }
                | StructureResult::RefusedShortcut
                | StructureResult::RefusedNoVisibleParents
                | StructureResult::RefusedSheetNotFound { .. }
                | StructureResult::RefusedSheetExists { .. }
                | StructureResult::RefusedInvalidRange { .. }
                | StructureResult::Blocked { .. }
                | StructureResult::RefusedNoLease
                | StructureResult::RefusedLeaseExpired
                | StructureResult::RefusedLeaseWrongFile
                | StructureResult::RefusedLeaseStale
                | StructureResult::Unchanged { .. }
                | StructureResult::Changed { .. }
                | StructureResult::AppliedReplyUnreadable { .. }
                | StructureResult::Failed { .. } => {}
            }
        }
        all
    }

    /// No `describe_lines` line ever contains a newline, and the insert
    /// preview and an add/duplicate's unreadable reply are the only arms
    /// that emit a second line.
    ///
    /// Both halves are load-bearing, and they are different claims. The
    /// second is presentation: `write.rs`/`create.rs` pin every arm to one
    /// line, and a structural insert earns its extra one because the shift is
    /// the substance of the dry run (ADR-0075 §6); an unreadable reply to an
    /// add/duplicate earns one because the new sheet's id is lost (#2021).
    ///
    /// The first is what makes `cli::drive::sheets::structure`'s sanitizing
    /// sound. Every line here interpolates untrusted text — a Drive-supplied
    /// file name, workbook sheet titles, raw API error details — and the CLI
    /// strips control characters from each line before supplying the
    /// separators itself. That is only equivalent to filtering each
    /// interpolation while this module contributes no newline of its own: a
    /// line built with an embedded `\n` would smuggle a separator past the
    /// filter and let an injected one pass for a real one.
    ///
    /// The wildcard-free `every_structure_result` is the other half — a new
    /// variant will not compile until it is listed there, so it cannot reach
    /// the terminal without passing through this check.
    #[test]
    fn no_describe_line_contains_a_newline() {
        for verb in [
            add_sheet(),
            rename(),
            insert_rows(),
            StructureVerb::InsertColumns {
                sheet: "Q2".to_string(),
                at: 2,
                count: 1,
            },
            move_rows(),
            StructureVerb::MoveColumns {
                sheet: "Q2".to_string(),
                at: 2,
                count: 1,
                before: 5,
            },
            delete_sheet(),
            delete_rows(),
            delete_columns(),
            insert_range(),
            insert_range_columns_shift(),
            delete_range(),
            delete_range_columns_shift(),
            duplicate_sheet(),
            duplicate_sheet_default(),
            reorder_sheet(),
            hide_sheet(),
            show_sheet(),
            update_workbook_properties(),
        ] {
            // A verb with a single axis (insert, delete-dimension or
            // move-dimension) earns a second `WouldChange` line for the
            // shift; every other verb, additive or destructive, stays one
            // line.
            let has_dimension_shift = verb.dimension().is_some();
            // The other two-line arm: an unreadable reply to an add or
            // duplicate adds the "find the new sheet's id" hint.
            let adds_a_sheet = matches!(
                verb,
                StructureVerb::AddSheet { .. } | StructureVerb::DuplicateSheet { .. }
            );
            for result in every_structure_result() {
                let has_second_line = (has_dimension_shift
                    && matches!(result, StructureResult::WouldChange { .. }))
                    || (adds_a_sheet
                        && matches!(result, StructureResult::AppliedReplyUnreadable { .. }));
                let outcome = StructureOutcome {
                    spreadsheet_id: "sheet-1".to_string(),
                    file_name: Some("Budget".to_string()),
                    resolved_folder_id: None,
                    verb: verb.clone(),
                    result,
                };
                let lines = describe_lines(&outcome);
                assert_eq!(
                    lines.len(),
                    usize::from(has_second_line) + 1,
                    "unexpected line count for {:?}/{:?}: {lines:?}",
                    outcome.verb,
                    outcome.result
                );
                for rendered in &lines {
                    assert!(
                        !rendered.chars().any(char::is_control),
                        "describe_lines emitted a control character for {:?}/{:?}: \
                         {rendered:?}",
                        outcome.verb,
                        outcome.result
                    );
                }
                // `describe` is the join, so it reconstructs exactly the
                // separators the CLI would supply and nothing else.
                assert_eq!(describe(&outcome), lines.join("\n"));
            }
        }
    }

    /// [`describe_would_delete_dimension`]'s own defensive branches, reached
    /// with arguments `validate_verb_args` would already have refused (an
    /// overflowing `--at`/`--count`) or a workbook snapshot the real pipeline
    /// never hands it (`sheet: None`, or a size too small to subtract
    /// `count` from) — the `describe_lines(&outcome)` bypass used above lets
    /// a test construct exactly that, the same way
    /// `dimension_range_label_omits_a_span_it_cannot_compute` does for
    /// `record_attempt`'s logging path.
    #[test]
    fn describe_would_delete_dimension_handles_unvalidated_edge_cases() {
        let would_change = |verb: StructureVerb, sheet: Option<SheetSnapshot>| StructureOutcome {
            spreadsheet_id: "sheet-1".to_string(),
            file_name: Some("Budget".to_string()),
            resolved_folder_id: None,
            verb,
            result: StructureResult::WouldChange {
                sheet: sheet.map(Box::new),
                sheet_count: 2,
            },
        };
        // `sheet_id: None` keeps every expected string free of the
        // `(sheetId N)` suffix, which is orthogonal to what this test checks.
        let sheet_with_columns = |column_count| SheetSnapshot {
            sheet_id: None,
            title: "Q2".to_string(),
            row_count: None,
            column_count: Some(column_count),
            ..Default::default()
        };

        // `--at`/`--count` overflowing the `last` computation: no dash-range
        // or shift line, just the plain summary.
        let overflow = describe(&would_change(
            StructureVerb::DeleteColumns {
                sheet: "Q2".to_string(),
                at: i64::MAX,
                count: 2,
            },
            Some(sheet_with_columns(26)),
        ));
        assert!(
            overflow.contains("Would delete 2 column(s) from column"),
            "{overflow}"
        );
        assert!(!overflow.contains('-'), "{overflow}");

        // No sheet snapshot at all: the shift line needs a real "before"
        // size, so it is omitted rather than guessed.
        let no_sheet = describe(&would_change(delete_columns(), None));
        assert_eq!(no_sheet, "Would delete 2 column(s) 3-4 of 'Q2' in 'Budget'");

        // A `before` too small for `count` to subtract from without
        // underflowing `i64::MIN`: also omitted rather than reported wrong.
        let after_underflows = describe(&would_change(
            StructureVerb::DeleteColumns {
                sheet: "Q2".to_string(),
                at: 0,
                count: i64::MAX,
            },
            Some(sheet_with_columns(-2)),
        ));
        assert_eq!(
            after_underflows,
            format!(
                "Would delete {} column(s) 0-{} of 'Q2' in 'Budget'",
                i64::MAX,
                i64::MAX - 1
            )
        );

        // Deleting exactly through the sheet's last column: "nothing
        // remains", not an inverted "existing N-M shift".
        let to_the_end = describe(&would_change(
            StructureVerb::DeleteColumns {
                sheet: "Q2".to_string(),
                at: 25,
                count: 2,
            },
            Some(sheet_with_columns(26)),
        ));
        assert!(
            to_the_end.contains("nothing remains after the deleted columns"),
            "{to_the_end}"
        );
    }

    #[test]
    fn log_status_covers_every_variant() {
        let statuses = [
            StructureResult::WouldChange {
                sheet: None,
                sheet_count: 1,
            }
            .log_status(),
            StructureResult::RefusedNotASpreadsheet {
                mime_type: "application/pdf".to_string(),
            }
            .log_status(),
            StructureResult::RefusedShortcut.log_status(),
            StructureResult::RefusedNoVisibleParents.log_status(),
            StructureResult::RefusedSheetNotFound {
                title: "x".to_string(),
                available: Vec::new(),
            }
            .log_status(),
            StructureResult::RefusedSheetExists {
                title: "x".to_string(),
            }
            .log_status(),
            StructureResult::RefusedInvalidRange {
                detail: "x".to_string(),
            }
            .log_status(),
            StructureResult::Blocked { decided_by: None }.log_status(),
            StructureResult::RefusedNoLease.log_status(),
            StructureResult::RefusedLeaseExpired.log_status(),
            StructureResult::RefusedLeaseWrongFile.log_status(),
            StructureResult::RefusedLeaseStale.log_status(),
            StructureResult::Unchanged {
                detail: "x".to_string(),
            }
            .log_status(),
            StructureResult::Changed {
                sheet: None,
                sheet_id: None,
                backup: None,
            }
            .log_status(),
            StructureResult::AppliedReplyUnreadable {
                summary: "x".to_string(),
                detail: "x".to_string(),
                sheet: None,
                sheet_id: None,
                backup: None,
            }
            .log_status(),
            StructureResult::Failed {
                detail: "x".to_string(),
            }
            .log_status(),
        ];
        let unique: HashSet<&&str> = statuses.iter().collect();
        assert_eq!(unique.len(), statuses.len(), "statuses must be distinct");
        assert!(statuses.iter().all(|s| !s.is_empty()));
    }

    #[test]
    fn a_verdict_of_allow_is_what_lets_a_run_proceed() {
        // Pins the gate's vocabulary this module depends on, so a rename of
        // the enum can't silently invert the check above.
        assert_ne!(Verdict::Allow, Verdict::Deny);
    }

    #[test]
    fn build_request_fails_rather_than_guessing_a_missing_sheet_id() {
        // Sheet id 0 is a real sheet (the first tab), so defaulting would
        // aim a rename at the wrong tab.
        let sheet = SheetSnapshot {
            sheet_id: None,
            title: "Q2".to_string(),
            row_count: None,
            column_count: None,
            ..Default::default()
        };
        let err = build_request(&rename(), Some(&sheet)).unwrap_err();
        assert!(err.contains("sheetId"), "{err}");
    }

    #[test]
    fn added_sheet_id_reads_the_add_sheet_reply_only() {
        let empty: BatchUpdateResponse =
            serde_json::from_value(serde_json::json!({"spreadsheetId": "s", "replies": [{}]}))
                .unwrap();
        assert_eq!(added_sheet_id(&empty), None);
        let added: BatchUpdateResponse = serde_json::from_value(serde_json::json!({
            "replies": [{"addSheet": {"properties": {"sheetId": 42, "title": "New"}}}]
        }))
        .unwrap();
        assert_eq!(added_sheet_id(&added), Some(42));
    }

    // ── file-id rules (issue #1612) ────────────────────────────────────

    #[tokio::test]
    async fn a_file_rule_grants_a_sheet_with_no_visible_parents() {
        // The case issue #1612 exists for: before file rules there was no
        // rule an operator could write that would permit this at all.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &[])
            .mount(&server)
            .await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .expect(1)
            .mount(&server)
            .await;

        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[FolderPermissionRule::file("sheet-1").allowing([DriveOperation::SheetsStructure])],
        )
        .await;

        assert!(
            matches!(outcome.result, StructureResult::Changed { .. }),
            "{:?}",
            outcome.result
        );
    }

    #[tokio::test]
    async fn a_file_rule_denies_even_when_a_parent_folder_would_allow() {
        // Depth −1 beats depth 0 in the restrictive direction too.
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        // No mock for parent-1 and none for any Sheets endpoint: the file
        // rule must decide before either is reached.

        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[
                allow_rule("parent-1"),
                FolderPermissionRule::file("sheet-1").denying([DriveOperation::SheetsStructure]),
            ],
        )
        .await;

        match &outcome.result {
            StructureResult::Blocked { decided_by } => {
                let rule = decided_by.as_ref().expect("a file rule decided this");
                assert_eq!(rule.kind_label(), "file");
                assert_eq!(rule.id(), "sheet-1");
            }
            other => panic!("expected Blocked, got {other:?}"),
        }
        let text = describe(&outcome);
        assert!(text.contains("refused by rule on file sheet-1"), "{text}");
        assert!(!text.contains("depth"), "a file rule has no depth: {text}");
    }

    #[tokio::test]
    async fn the_no_visible_parents_message_names_a_file_rule_as_the_fix() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &[])
            .mount(&server)
            .await;
        let outcome = structure(&drive, &sheets, &opts(rename(), false), &[]).await;
        let text = describe(&outcome);
        assert!(text.contains("file_id"), "{text}");
        assert!(text.contains("sheets-structure"), "{text}");
    }

    // ── the write's own audit trail (ADR-0080 §11) ─────────────────────

    #[tokio::test]
    async fn a_leased_structure_change_concludes_its_audit_pair_with_allowed() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        mount_workbook().mount(&server).await;
        mount_batch_update(serde_json::json!({"spreadsheetId": "sheet-1", "replies": [{}]}))
            .mount(&server)
            .await;
        let dir = tempfile::tempdir().unwrap();
        let audit = crate::test_support::AuditLogGuard::redirect(dir.path());
        let verb = StructureVerb::RenameSheet {
            sheet: "Q2".to_string(),
            new_title: "Q2 (final)".to_string(),
        };

        let outcome = structure(
            &drive,
            &sheets,
            &opts(verb, false),
            &[allow_rule("parent-1")],
        )
        .await;
        assert!(matches!(outcome.result, StructureResult::Changed { .. }));

        let records = audit.records();
        assert_eq!(audit.verdicts(), ["pending", "allowed"], "{records:?}");
        // The verb, not the engine — the same `["drive", <log_operation>]`
        // this write's `drivemutation` record carries, so an auditor can
        // see which verb ran without joining back to `log.jsonl`.
        assert_eq!(records[0].command, ["drive", "sheets-rename-sheet"]);
    }

    /// #1688: a sheet that resolved by title but reported no `sheetId` (a
    /// server contract violation, see [`build_request_fails_rather_than_guessing_a_missing_sheet_id`])
    /// is exactly the case `build_request` refuses on — and it must never
    /// open a `pending` audit record for a write that can never be issued.
    /// `build_request_fails_rather_than_guessing_a_missing_sheet_id` covers
    /// the pure function; this covers the engine path through it, which was
    /// untested before this fix (the bug this test guards against left the
    /// `pending` record unconcluded).
    #[tokio::test]
    async fn a_missing_sheet_id_fails_before_opening_the_audit_pair() {
        let server = wiremock::MockServer::start().await;
        let (drive, sheets) = clients(&server).await;
        mount_file("sheet-1", GOOGLE_SHEET_MIME_TYPE, &["parent-1"])
            .mount(&server)
            .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "spreadsheetId": "sheet-1",
                    "properties": {"title": "Budget"},
                    "sheets": [
                        {"properties": {"title": "Q2", "index": 0}}
                    ],
                })),
            )
            .mount(&server)
            .await;
        // No batchUpdate mock mounted: `build_request`'s own missing-`sheetId`
        // check is the one that must catch this, before any mutating call.
        let dir = tempfile::tempdir().unwrap();
        let audit = crate::test_support::AuditLogGuard::redirect(dir.path());

        let outcome = structure(
            &drive,
            &sheets,
            &opts(rename(), false),
            &[allow_rule("parent-1")],
        )
        .await;
        match outcome.result {
            StructureResult::Failed { detail } => {
                assert!(detail.contains("sheetId"), "{detail}");
            }
            other => panic!("expected Failed, got {other:?}"),
        }
        assert!(audit.records().is_empty(), "{:?}", audit.records());
    }
}